diff --git a/Cargo.lock b/Cargo.lock index 99e243cc92..1ac8567334 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -1918,7 +1918,7 @@ dependencies = [ [[package]] name = "craft-ipp" version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#af4e8181e69dd26d6f3537b881dd78ec466d374d" +source = "git+https://github.com/storytold/craft-libs?rev=bfd8fec34b2b0c7ecc5855f5ffc2c2f3e138bafc#bfd8fec34b2b0c7ecc5855f5ffc2c2f3e138bafc" [[package]] name = "craft-jpeg" @@ -2030,23 +2030,12 @@ source = "git+https://github.com/storytold/craft-libs?rev=bfd8fec34b2b0c7ecc5855 dependencies = [ "blake3", "craft-atomic", - "craft-pcraft-format 0.1.0 (git+https://github.com/storytold/craft-libs?rev=bfd8fec34b2b0c7ecc5855f5ffc2c2f3e138bafc)", + "craft-pcraft-format", "craft-zip", "ruzstd", "thiserror 2.0.21", ] -[[package]] -name = "craft-pcraft-format" -version = "0.1.0" -source = "git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff#af4e8181e69dd26d6f3537b881dd78ec466d374d" -dependencies = [ - "flate2", - "serde", - "serde_json", - "thiserror 2.0.21", -] - [[package]] name = "craft-pcraft-format" version = "0.1.0" @@ -6742,7 +6731,7 @@ dependencies = [ "craft-develop-model", "craft-file-formats", "craft-image-codecs", - "craft-pcraft-format 0.1.0 (git+https://github.com/storytold/craft-libs?rev=3eb5b528b08211844bc5c95c5a4fd169894d52ff)", + "craft-pcraft-format", "craft-print", "craft-psd", "craft-tracked", @@ -6834,7 +6823,7 @@ dependencies = [ "blake3", "craft-image-codecs", "craft-pcraft-bundle", - "craft-pcraft-format 0.1.0 (git+https://github.com/storytold/craft-libs?rev=bfd8fec34b2b0c7ecc5855f5ffc2c2f3e138bafc)", + "craft-pcraft-format", "craft-zip", "crc32fast", "exacl", @@ -10806,7 +10795,7 @@ checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" [[package]] name = "winit" version = "0.30.13" -source = "git+https://github.com/storytold/winit.git?rev=a517b3846ee8457d84ee4975110bfda6797c44dc#a517b3846ee8457d84ee4975110bfda6797c44dc" +source = "git+https://github.com/storytold/winit.git?rev=f8b490f135ea439dd31aae100bb5591c63cb076f#f8b490f135ea439dd31aae100bb5591c63cb076f" dependencies = [ "ahash", "android-activity", diff --git a/Cargo.toml b/Cargo.toml index 51d87c8c4f..ec26f4a625 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -374,4 +374,4 @@ egui_system_font_provider = { git = "https://github.com/storytold/egui.git", rev eframe = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } egui_demo_lib = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } egui_inspection = { git = "https://github.com/storytold/egui.git", rev = "14c39fed181756be6f357c284354e0ab55b64443" } -winit = { git = "https://github.com/storytold/winit.git", rev = "a517b3846ee8457d84ee4975110bfda6797c44dc" } +winit = { git = "https://github.com/storytold/winit.git", rev = "f8b490f135ea439dd31aae100bb5591c63cb076f" } diff --git a/crates/automation/src/rpc/tests.rs b/crates/automation/src/rpc/tests.rs index 991e6c0fb1..dc871e6f14 100644 --- a/crates/automation/src/rpc/tests.rs +++ b/crates/automation/src/rpc/tests.rs @@ -573,7 +573,7 @@ fn doc_export_layers_reports_skips_in_workspace_and_trusted_sessions() { 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.newAdjustmentLayer.levels"})).unwrap(); 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(); @@ -586,23 +586,22 @@ fn doc_export_layers_reports_skips_in_workspace_and_trusted_sessions() { 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_0002_Background.png")])); + assert_eq!(reply["result"]["files"], json!([format!("{out_dir}/card_0001_Levels.png"), format!("{out_dir}/card_0002_Background.png")])); if !trusted { - assert_eq!(reply["result"]["count"], 1); + assert_eq!(reply["result"]["count"], 2); } 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"} + {"layer": hidden, "name": "Hidden", "reason": "hidden by visibleOnly"} ]) ); - assert_eq!(std::fs::read_dir(base.join("out")).unwrap().count(), 1); + assert_eq!(std::fs::read_dir(base.join("out")).unwrap().count(), 2); 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); + assert_eq!(all["files"].as_array().unwrap().len(), 3); + assert_eq!(all["skipped"].as_array().unwrap().len(), 0); // Workspace no-overwrite errors still fail and remove only newly created files. if !trusted { let collision = base.join("collision"); diff --git a/crates/automation/tests/it/mcp.rs b/crates/automation/tests/it/mcp.rs index dffd1e59e7..e972e46e60 100644 --- a/crates/automation/tests/it/mcp.rs +++ b/crates/automation/tests/it/mcp.rs @@ -983,22 +983,22 @@ async fn doc_export_layers_reports_skipped_layers() { let hidden = json_of(&call(&client, "command_run", json!({"id": "layer.new.layer", "params": {"name": "Hidden"}})).await)["layer"].clone(); json_of(&call(&client, "command_run", json!({"id": "layer.setProps", "params": {"visible": false}})).await); let result = json_of(&call(&client, "doc_export_layers", json!({"dir": "layers"})).await); - assert_eq!(result["count"], 1); - assert_eq!(result["files"], json!(["layers/card_0002_Background.png"])); + assert_eq!(result["count"], 2); + assert_eq!(result["files"], json!(["layers/card_0001_Levels_α.png", "layers/card_0002_Background.png"])); assert_eq!( result["skipped"], json!([ - {"layer": hidden, "name": "Hidden", "reason": "hidden by visibleOnly"}, - {"layer": adjustment, "name": "Levels/α", "reason": "adjustment layer has no pixels of its own"} + {"layer": hidden, "name": "Hidden", "reason": "hidden by visibleOnly"} ]) ); let all = json_of(&call(&client, "doc_export_layers", json!({"dir": "all", "visible_only": false})).await); - assert_eq!(all["count"], 2); - assert_eq!(all["skipped"].as_array().unwrap().len(), 1); - assert_eq!(std::fs::read_dir(base.join("layers")).unwrap().count(), 1); - assert_eq!(std::fs::read_dir(base.join("all")).unwrap().count(), 2); + assert_eq!(all["count"], 3); + assert_eq!(all["skipped"].as_array().unwrap().len(), 0); + assert_eq!(std::fs::read_dir(base.join("layers")).unwrap().count(), 2); + assert_eq!(std::fs::read_dir(base.join("all")).unwrap().count(), 3); // Every top-level layer is still accounted for when none can be exported. json_of(&call(&client, "command_run", json!({"id": "layer.setProps", "params": {"layer": background, "visible": false}})).await); + json_of(&call(&client, "command_run", json!({"id": "layer.setProps", "params": {"layer": adjustment, "visible": false}})).await); let none = json_of(&call(&client, "doc_export_layers", json!({"dir": "none"})).await); assert_eq!(none["files"], json!([])); assert_eq!(none["count"], 0); diff --git a/crates/engine-core/Cargo.toml b/crates/engine-core/Cargo.toml index 9e98cbb775..5c99a34f9e 100644 --- a/crates/engine-core/Cargo.toml +++ b/crates/engine-core/Cargo.toml @@ -18,8 +18,8 @@ craft-ui-macros = { workspace = true } photocraft-geom = { workspace = true } photocraft-color = { workspace = true } craft-cms = { workspace = true } -# PCTIP codec from craft-libs#1564; isolated pin until the shared revision is adopted workspace-wide. -craft-pcraft-tip = { package = "craft-pcraft-format", git = "https://github.com/storytold/craft-libs", rev = "3eb5b528b08211844bc5c95c5a4fd169894d52ff" } +# PCTIP codec from craft-libs#1564; kept at the same shared revision as the workspace. +craft-pcraft-tip = { package = "craft-pcraft-format", git = "https://github.com/storytold/craft-libs", rev = "bfd8fec34b2b0c7ecc5855f5ffc2c2f3e138bafc" } photocraft-raster = { workspace = true } photocraft-doc = { workspace = true } photocraft-ops = { workspace = true } diff --git a/crates/engine-core/src/cmd/analysis_cmds.rs b/crates/engine-core/src/cmd/analysis_cmds.rs index 9eb24468ea..5a729e5a0b 100644 --- a/crates/engine-core/src/cmd/analysis_cmds.rs +++ b/crates/engine-core/src/cmd/analysis_cmds.rs @@ -1058,6 +1058,27 @@ fn feature_values(m: &mut Map, f: &Feature, count: usize, factor: m.insert("histogram".into(), json!(f.histogram)); } +/// The start of Record Measurements' error when no data point is enabled for the source it records; the source's +/// name and a full stop follow (#17407). +pub const NO_DATA_POINTS: &str = "There are no measurement data points currently enabled for the "; + +/// The second line of that alert. +pub const NO_DATA_POINTS_DETAIL: &str = "Data points must be set before measurements can be recorded."; + +/// The name the alert gives source `source` (`selection`, `ruler` or `count`). +pub fn data_points_source_name(source: &str) -> &'static str { + match source { + "ruler" => "Ruler Tool", + "count" => "Count Tool", + _ => "Selection", + } +} + +/// Record Measurements' error for `source` with no data point enabled: the alert's two lines. +fn no_data_points(source: &str) -> String { + format!("{NO_DATA_POINTS}{}.\n{NO_DATA_POINTS_DETAIL}", data_points_source_name(source)) +} + fn record(s: &mut Session, p: &Value) -> Result { const CMD: &str = "image.analysis.recordMeasurements"; let d = doc(s)?; @@ -1117,6 +1138,11 @@ fn record(s: &mut Session, p: &Value) -> Result { rows.push(m); } } + // No data point enabled for the source: the reference application's alert, and nothing is recorded (no + // empty row, no label number used up, #17407). + if s.analysis.data_points.of(source).is_empty() { + return Err(EngineError::Other(no_data_points(source))); + } s.analysis.next_measurement += 1; let keep = s.analysis.data_points.of(source).to_vec(); let mut ids = Vec::new(); @@ -1414,4 +1440,6 @@ mod analysis_straighten_selection_tests; #[cfg(test)] mod data_points_empty_set_tests; #[cfg(test)] +mod record_no_data_points_tests; +#[cfg(test)] mod tests; diff --git a/crates/engine-core/src/cmd/analysis_cmds/record_no_data_points_tests.rs b/crates/engine-core/src/cmd/analysis_cmds/record_no_data_points_tests.rs new file mode 100644 index 0000000000..73a0b401b2 --- /dev/null +++ b/crates/engine-core/src/cmd/analysis_cmds/record_no_data_points_tests.rs @@ -0,0 +1,72 @@ +//! #17407: Record Measurements with no data point enabled for the source it records refuses with the reference +//! application's alert text, records nothing and does not use up a label number. Ruler and Count get the same check, +//! naming their tool. + +use super::*; + +const RECORD: &str = "image.analysis.recordMeasurements"; +const POINTS: &str = "image.analysis.selectDataPoints"; + +fn session() -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 200, "height": 120, "background": "white"})).unwrap(); + s +} + +fn log_len(s: &mut Session) -> usize { + s.execute("measurementLog.list", json!({})).unwrap()["rows"].as_array().map_or(0, Vec::len) +} + +fn message(e: &EngineError) -> String { + e.to_string() +} + +#[test] +fn a_selection_with_only_ruler_points_on_warns_and_records_nothing() { + let mut s = session(); + s.execute(POINTS, json!({"selection": [], "ruler": ["length", "angle"], "count": []})).unwrap(); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap(); + + let e = s.execute(RECORD, json!({})).unwrap_err(); + assert_eq!( + message(&e), + "There are no measurement data points currently enabled for the Selection.\nData points must be set before measurements can be recorded." + ); + assert!(message(&e).starts_with(NO_DATA_POINTS)); + assert_eq!(log_len(&mut s), 0, "no empty row"); + + // The label number was not used up: after setting a point, the first row is "Measurement 1". + s.execute(POINTS, json!({"selection": ["label", "area"]})).unwrap(); + let r = s.execute(RECORD, json!({})).unwrap(); + assert_eq!(r["rows"][0]["values"]["label"], json!("Measurement 1"), "{r}"); + assert_eq!(log_len(&mut s), 1); +} + +#[test] +fn ruler_and_count_get_the_same_check_with_their_tool_name() { + let mut s = session(); + s.execute(POINTS, json!({"selection": ["area"], "ruler": [], "count": []})).unwrap(); + s.execute("image.analysis.rulerTool", json!({"start": [10, 50], "end": [40, 10]})).unwrap(); + let e = s.execute(RECORD, json!({"source": "ruler"})).unwrap_err(); + assert_eq!(message(&e), format!("{NO_DATA_POINTS}Ruler Tool.\n{NO_DATA_POINTS_DETAIL}")); + + s.execute("count.add", json!({"x": 20, "y": 20})).unwrap(); + let e = s.execute(RECORD, json!({"source": "count"})).unwrap_err(); + assert_eq!(message(&e), format!("{NO_DATA_POINTS}Count Tool.\n{NO_DATA_POINTS_DETAIL}")); + assert_eq!(log_len(&mut s), 0); + + // With a point on, each source records as before. + s.execute(POINTS, json!({"ruler": ["length"], "count": ["count"]})).unwrap(); + assert!(s.execute(RECORD, json!({"source": "ruler"})).is_ok()); + assert!(s.execute(RECORD, json!({"source": "count"})).is_ok()); + assert_eq!(log_len(&mut s), 2); +} + +#[test] +fn a_source_that_has_points_records_whatever_the_other_sources_hold() { + let mut s = session(); + s.execute(POINTS, json!({"selection": ["area"], "ruler": [], "count": []})).unwrap(); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap(); + let r = s.execute(RECORD, json!({})).unwrap(); + assert_eq!(r["rows"][0]["values"]["area"], json!(5000.0), "{r}"); +} diff --git a/crates/engine-core/src/cmd/atn_cmds/crop_angle_sign_tests.rs b/crates/engine-core/src/cmd/atn_cmds/crop_angle_sign_tests.rs new file mode 100644 index 0000000000..01fe9955e1 --- /dev/null +++ b/crates/engine-core/src/cmd/atn_cmds/crop_angle_sign_tests.rs @@ -0,0 +1,106 @@ +use craft_psd::atn::{self, AtnAction, AtnEvent, AtnFile, AtnItem}; +use craft_psd::descriptor::{UnicodeString, Value as D}; +use photocraft_doc::{LayerContent, LayerId, Size, SmartObject}; +use photocraft_geom::{Point, Rect}; +use photocraft_paint::tile::{b64_decode, b64_encode}; +use serde_json::json; + +use super::{ang, desc, get_num, px}; +use crate::Session; + +fn document() -> (Session, LayerId, LayerId) { + let mut s = crate::session(); + s.execute("prefs.set", json!({"path": "actions.createSingleHistoryState", "value": false})).unwrap(); + s.execute("file.new", json!({"width": 400, "height": 300})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Embedded square"})).unwrap(); + s.edit("Paint square", |doc, active| { + let surface = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + surface.fill_rect(Rect::new(150, 100, 250, 200), &[0.2, 0.4, 0.8, 1.0]); + Ok(()) + }) + .unwrap(); + let converted = s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + let shape = s.execute("shape.create", json!({"kind": "rect", "rect": [250, 20, 140, 70], "fill": "#ff6600"})).unwrap(); + (s, LayerId(converted["layer"].as_u64().unwrap()), LayerId(shape["layer"].as_u64().unwrap())) +} + +fn smart_object(s: &Session, id: LayerId) -> &SmartObject { + let LayerContent::Smart(smart) = &s.active().unwrap().doc.layer(id).unwrap().content else { panic!("expected a Smart Object") }; + smart +} + +fn shape_corners(s: &Session, id: LayerId) -> Vec { + let LayerContent::Shape(shape) = &s.active().unwrap().doc.layer(id).unwrap().content else { panic!("expected a shape") }; + shape.path.subpaths[0].knots.iter().map(|knot| knot.anchor).collect() +} + +fn play_atn(s: &mut Session, data: &str) { + let loaded = s.execute("actions.load", json!({"data": data})).unwrap(); + assert_eq!(loaded["unsupported"], json!([]), "{loaded}"); + let before = s.active().unwrap().history.past_len(); + let played = s.execute("actions.play", json!({"action": loaded["actions"][0]})).unwrap(); + assert_eq!(played["ran"], 1, "{played}"); + assert!(played.get("failed").is_none(), "{played}"); + let state = s.active().unwrap(); + assert_eq!(state.history.past_len(), before + 1); + assert_eq!(state.history.undo_label(), Some("Crop")); + assert_eq!(state.doc.size, Size::new(300, 200)); +} + +#[test] +fn imported_crop_turns_shape_and_smart_object_clockwise() { + let frame = desc("Rctn").with("Top ", px(50.0)).with("Left", px(50.0)).with("Btom", px(250.0)).with("Rght", px(350.0)); + let crop = desc("null").with("To ", D::Descriptor(frame)).with("Angl", ang(10.0)).with("Dlt ", D::Boolean(false)); + let file = AtnFile { + name: UnicodeString::new_nul("Crops"), + actions: vec![AtnAction { + name: UnicodeString::new_nul("Turn and crop"), + items: vec![AtnItem { event: AtnEvent::Code(*b"Crop"), dictionary: b"Crop".to_vec(), descriptor: Some(crop), ..Default::default() }], + ..Default::default() + }], + ..Default::default() + }; + let (mut s, smart, shape) = document(); + let origin = smart_object(&s, smart).source.clone(); + play_atn(&mut s, &b64_encode(&atn::write(&file).unwrap())); + + let placed = smart_object(&s, smart); + assert_eq!(placed.source, origin); + let corners = [(0.0, 0.0), (100.0, 0.0), (100.0, 100.0), (0.0, 100.0)].map(|(x, y)| placed.transform.apply(Point::new(x, y))); + for (point, (x, y)) in corners.into_iter().zip([(109.4, 42.1), (207.9, 59.4), (190.6, 157.9), (92.1, 140.6)]) { + assert!((point.x - x).abs() <= 1.0 && (point.y - y).abs() <= 1.0, "{point:?} expected ({x}, {y})"); + } + + let corners = shape_corners(&s, shape); + let bounds = [ + corners.iter().map(|p| p.x).fold(f64::INFINITY, f64::min), + corners.iter().map(|p| p.y).fold(f64::INFINITY, f64::min), + corners.iter().map(|p| p.x).fold(f64::NEG_INFINITY, f64::max), + corners.iter().map(|p| p.y).fold(f64::NEG_INFINITY, f64::max), + ]; + for (edge, expected) in bounds.into_iter().zip([209.0, -20.0, 360.0, 74.0]) { + assert!((edge - expected).abs() <= 1.0, "{bounds:?}"); + } +} + +#[test] +fn recorded_crop_exports_a_canvas_angle_and_replays_the_same_geometry() { + for angle in [-10.0, 6.5] { + let (mut recorded, smart, shape) = document(); + recorded.execute("actions.record", json!({"name": "Turn and crop"})).unwrap(); + recorded.execute("image.crop", json!({"x": 50, "y": 50, "width": 300, "height": 200, "angle": angle, "deleteCroppedPixels": false})).unwrap(); + recorded.execute("actions.stop", json!({})).unwrap(); + let saved = recorded.execute("actions.save", json!({"action": "Turn and crop"})).unwrap(); + assert_eq!(saved["skipped"], json!([])); + let data = saved["data"].as_str().unwrap(); + let file = atn::parse(&b64_decode(data).unwrap()).unwrap(); + let [step] = file.actions[0].items.as_slice() else { panic!("expected a single Crop step") }; + assert_eq!(step.event.id(), "Crop"); + assert_eq!(get_num(step.descriptor.as_ref().unwrap(), "Angl"), Some(-angle)); + + let (mut replayed, replayed_smart, replayed_shape) = document(); + play_atn(&mut replayed, data); + assert_eq!(smart_object(&replayed, replayed_smart).transform, smart_object(&recorded, smart).transform); + assert_eq!(shape_corners(&replayed, replayed_shape), shape_corners(&recorded, shape)); + } +} diff --git a/crates/engine-core/src/cmd/atn_cmds/steps_doc.rs b/crates/engine-core/src/cmd/atn_cmds/steps_doc.rs index 9dcc36a101..98f28c0426 100644 --- a/crates/engine-core/src/cmd/atn_cmds/steps_doc.rs +++ b/crates/engine-core/src/cmd/atn_cmds/steps_doc.rs @@ -7,6 +7,10 @@ use super::fields::{Mapped, none, step, steps}; use super::tables::{ALIGN, EXTENSION, INTENT, INTERPOLATION, MODES, PROFILES, PURGE, SAVE_FORMATS, lookup, lookup_back}; use super::{D, Descriptor, Id, Map, ReferenceItem, STOP_MESSAGE, UnicodeString, Value, json}; +#[cfg(test)] +#[path = "crop_angle_sign_tests.rs"] +mod crop_angle_sign_tests; + /// `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 } }; @@ -631,7 +635,8 @@ pub(super) fn crop_from(d: &Descriptor) -> Mapped { p.insert("height".into(), (bottom - top).round().into()); } if let Some(a) = get_num(d, "Angl") { - p.insert("angle".into(), a.into()); + // ATN records the canvas turn. PhotoCraft's Crop angle describes the frame's turn. + p.insert("angle".into(), (-a).into()); } if let Some(del) = get_bool(d, "Dlt ") { p.insert("deleteCroppedPixels".into(), del.into()); @@ -650,7 +655,7 @@ pub(super) fn crop_to(_: &str, p: &Value) -> Option { 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)); + d = d.with("Angl", ang(-a)); } if let Some(del) = jbool(p, "deleteCroppedPixels") { d = d.with("Dlt ", D::Boolean(del)); diff --git a/crates/engine-core/src/cmd/background_cmds.rs b/crates/engine-core/src/cmd/background_cmds.rs index e2ceaa8da2..bb7e314bf6 100644 --- a/crates/engine-core/src/cmd/background_cmds.rs +++ b/crates/engine-core/src/cmd/background_cmds.rs @@ -12,7 +12,10 @@ use serde_json::{Value, json}; use crate::commands::CommandSpec; use crate::{EngineError, Result, Session}; -const CMD: &str = "layer.new.backgroundFromLayer"; +pub(crate) const CMD: &str = "layer.new.backgroundFromLayer"; + +/// Why Background from Layer is greyed with two or more layers selected (#17306). +const SEVERAL_SELECTED: &str = "several layers selected; select one layer to make it the Background"; /// The document's Background layer, if it has one (always the bottom layer). pub(crate) fn background_id(doc: &Document) -> Option { @@ -41,7 +44,19 @@ fn convertible(l: &Layer) -> std::result::Result<(), String> { } } +/// The menu's precondition: greyed, as in the reference, with two or more layers selected +/// (#17306); otherwise [`can_convert_active`]. fn can_convert(s: &Session) -> std::result::Result<(), String> { + let d = s.active().ok_or("no document open")?; + if d.selected_layers().len() > 1 { + return Err(SEVERAL_SELECTED.into()); + } + can_convert_active(s) +} + +/// Can the active layer become the Background? A call that names its `"layer"` (scripts, +/// actions) is checked with this alone: it converts that layer whatever else is selected. +pub(crate) fn can_convert_active(s: &Session) -> std::result::Result<(), String> { let d = s.active().ok_or("no document open")?; if background_id(&d.doc).is_some() { return Err("the document already has a Background layer".into()); @@ -52,7 +67,13 @@ fn can_convert(s: &Session) -> std::result::Result<(), String> { fn background_from_layer(s: &mut Session, p: &Value) -> Result { let id = match p.get("layer") { - None | Some(Value::Null) => crate::commands::layer_param(s, p)?, + None | Some(Value::Null) => { + // Without a named layer the selection is the target, and it must be one layer. + if s.active().is_some_and(|d| d.selected_layers().len() > 1) { + return Err(EngineError::Disabled(CMD.into(), SEVERAL_SELECTED.into())); + } + crate::commands::layer_param(s, p)? + } Some(v) => LayerId(v.as_u64().ok_or_else(|| EngineError::BadParams { cmd: CMD.into(), msg: "`layer` must be a layer id".into() })?), }; let bg = s.tools.background; diff --git a/crates/engine-core/src/cmd/edit_cmds.rs b/crates/engine-core/src/cmd/edit_cmds.rs index 63278e0f8f..5849b59bfd 100644 --- a/crates/engine-core/src/cmd/edit_cmds.rs +++ b/crates/engine-core/src/cmd/edit_cmds.rs @@ -887,7 +887,8 @@ fn toggle_last_state(s: &mut Session) -> Result { /// Edit › Transform › Again: replay the last `edit.transform` on the selected layers (#6501). fn transform_again(s: &mut Session) -> Result { let ids = s.active().map(crate::transform_cmds::selection_targets).unwrap_or_default(); - let p = transform_again_params(s, &ids)?; + let mut p = transform_again_params(s, &ids)?; + p["stepName"] = json!(crate::transform_cmds::TRANSFORM_AGAIN); s.execute("edit.transform", p) } diff --git a/crates/engine-core/src/cmd/edit_menu_cmds.rs b/crates/engine-core/src/cmd/edit_menu_cmds.rs index bc42f3ad82..fec5597045 100644 --- a/crates/engine-core/src/cmd/edit_menu_cmds.rs +++ b/crates/engine-core/src/cmd/edit_menu_cmds.rs @@ -24,6 +24,16 @@ use crate::{EngineError, Result, Session}; pub use crate::state::{CustomShape, EditState, FadeSource, FadeTarget, FindCursor}; +/// Edit › Fade's menu label, as the reference application shows it (#13803): `Fade …` (`Fade Invert…`, `Fade Gaussian Blur…`) while Fade can run, plain +/// `Fade…` when it can't. +pub fn fade_menu_label(s: &Session) -> String { + match s.edit_state.fade.as_ref().filter(|_| can_fade(s).is_ok()) { + Some(f) => format!("Fade {}…", f.label), + None => "Fade…".into(), + } +} + /// Commands whose result Edit › Fade can blend back against the previous state. fn fadeable(id: &str) -> bool { id.starts_with("filter.") diff --git a/crates/engine-core/src/cmd/file_cmds.rs b/crates/engine-core/src/cmd/file_cmds.rs index 49b9aa0c9a..278d0de5c4 100644 --- a/crates/engine-core/src/cmd/file_cmds.rs +++ b/crates/engine-core/src/cmd/file_cmds.rs @@ -489,6 +489,10 @@ mod layers_to_files_single_layer_tests; #[path = "file_cmds/layers_to_files_png_names_tests.rs"] mod layers_to_files_png_names_tests; +#[cfg(test)] +#[path = "file_cmds/layers_to_files_adjustment_tests.rs"] +mod layers_to_files_adjustment_tests; + #[cfg(test)] #[path = "file_cmds/place_job_tests.rs"] mod place_job_tests; diff --git a/crates/engine-core/src/cmd/file_cmds/export.rs b/crates/engine-core/src/cmd/file_cmds/export.rs index 7a8a484726..0c89a9dcb9 100644 --- a/crates/engine-core/src/cmd/file_cmds/export.rs +++ b/crates/engine-core/src/cmd/file_cmds/export.rs @@ -84,7 +84,7 @@ pub fn export_layers_report_with(s: &Session, p: &Value, mut write: impl FnMut(& } let mut report = LayerExportReport::default(); let mut planned = Vec::new(); - plan_layer_exports(&doc.layers, &mut Vec::new(), "", visible_only, &mut planned, &mut report.skipped)?; + plan_layer_exports(&doc.layers, &mut Vec::new(), "", &format, visible_only, &mut planned, &mut report.skipped)?; // PNG file names use dashes for spaces (measured); the other formats keep them. let part = |text: &str| if format == "png" { sanitize(text).replace(' ', "-") } else { sanitize(text) }; // The prefix is optional; only the layer name needs the empty-name fallback. @@ -165,6 +165,7 @@ fn plan_layer_exports<'a>( layers: &'a [Layer], groups: &mut Vec<&'a Layer>, path: &str, + format: &str, visible_only: bool, planned: &mut Vec>, skipped: &mut Vec, @@ -182,20 +183,31 @@ fn plan_layer_exports<'a>( continue; } groups.push(l); - let r = plan_layer_exports(children, groups, &format!("{path}{number:04}s_"), visible_only, planned, skipped); + let r = plan_layer_exports(children, groups, &format!("{path}{number:04}s_"), format, visible_only, planned, skipped); groups.pop(); r?; continue; } // Every layer takes its index, even one skipped as hidden or as an adjustment, so a file - // keeps the same number whether Visible Layers Only is on or off (#13959). + // keeps the same number whether Visible Layers Only is on or off (#13959). An adjustment + // layer has no pixels of its own: for PNG and JPEG it exports like an empty layer under its + // own number, as measured (#13966); the other formats were not measured and still skip it, + // leaving its number unused. let number = format!("{path}{art:04}"); art += 1; if !l.visible && visible_only { skipped.push(SkippedExportLayer { layer: l.id.0, name: l.name.clone(), reason: "hidden by visibleOnly" }); continue; } - if matches!(l.content, LayerContent::Adjustment(_)) { + // Only a top-level adjustment whose mask hides nothing was measured: the white mask every + // new one gets. One whose mask hides something (painted, or made from a selection), that + // has a vector mask or that sits in a group was not, so it keeps today's skip in every format. + let masked = l.vector_mask.is_some() + || l.mask + .as_ref() + .is_some_and(|m| m.enabled && (m.surface.default_pixel().first().is_some_and(|v| *v < 1.0) || !m.surface.content_bounds().is_empty())); + let measured = !masked && groups.is_empty() && matches!(format, "png" | "jpg" | "jpeg"); + if matches!(l.content, LayerContent::Adjustment(_)) && !measured { skipped.push(SkippedExportLayer { layer: l.id.0, name: l.name.clone(), reason: "adjustment layer has no pixels of its own" }); continue; } diff --git a/crates/engine-core/src/cmd/file_cmds/layers_to_files_adjustment_tests.rs b/crates/engine-core/src/cmd/file_cmds/layers_to_files_adjustment_tests.rs new file mode 100644 index 0000000000..6db0c876ed --- /dev/null +++ b/crates/engine-core/src/cmd/file_cmds/layers_to_files_adjustment_tests.rs @@ -0,0 +1,125 @@ +//! Layers to Files writes a file for an adjustment layer, like an empty layer, for PNG and JPEG +//! (#13966); the formats that were not measured still skip it. + +use super::*; + +fn tmp(name: &str) -> String { + let d = std::env::temp_dir().join(format!("photocraft-l2f-adjustment-{}-{name}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d.to_string_lossy().into_owned() +} + +/// A 100 x 80 document: `Background`, then `Empty`, then a Levels adjustment layer named `Levels 1`. +fn session() -> Session { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 100, "height": 80, "depth": 8})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Empty"})).unwrap(); + s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap(); + s.execute("layer.setProps", json!({"name": "Levels 1"})).unwrap(); + s +} + +fn decode_file(dir: &str, name: &str) -> photocraft_codecs::Image { + photocraft_codecs::decode(&std::fs::read(std::path::Path::new(dir).join(name)).unwrap()).unwrap() +} + +#[test] +fn png_with_trim_writes_a_full_canvas_transparent_file_for_the_adjustment() { + let dir = tmp("png"); + let mut s = session(); + let r = s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": "doc", "trim": true})).unwrap(); + assert_eq!(r["skipped"], json!([])); + let files: Vec<&str> = r["files"].as_array().unwrap().iter().map(|v| v.as_str().unwrap()).collect(); + let names: Vec<&str> = files.iter().map(|f| f.rsplit(['/', '\\']).next().unwrap()).collect(); + assert_eq!(names, ["doc_0000_Levels-1.png", "doc_0001_Empty.png", "doc_0002_Background.png"]); + let img = decode_file(&dir, "doc_0000_Levels-1.png"); + assert_eq!((img.width(), img.height()), (100, 80)); + let rgba = img.to_rgba8(); + assert!(rgba.chunks(4).all(|p| p[3] == 0), "every pixel is fully transparent"); + let empty = decode_file(&dir, "doc_0001_Empty.png"); + assert_eq!((empty.width(), empty.height()), (100, 80)); +} + +#[test] +fn jpeg_writes_a_white_full_canvas_image_for_the_adjustment() { + let dir = tmp("jpeg"); + let mut s = session(); + let r = s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": "doc", "format": "jpg"})).unwrap(); + assert_eq!(r["skipped"], json!([])); + let img = decode_file(&dir, "doc_0000_Levels 1.jpg"); + assert_eq!((img.width(), img.height()), (100, 80)); + let rgba = img.to_rgba8(); + assert!(rgba.chunks(4).all(|p| p[..3].iter().all(|&c| c >= 253)), "white"); + let empty = decode_file(&dir, "doc_0001_Empty.jpg").to_rgba8(); + assert_eq!(rgba, empty, "the same as the empty layer"); +} + +#[test] +fn a_hidden_adjustment_is_skipped_by_visible_only() { + let dir = tmp("hidden"); + let mut s = session(); + let adjustment = s.active().unwrap().doc.layers.last().unwrap().id.0; + s.execute("layer.setProps", json!({"visible": false})).unwrap(); + let r = s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": "doc"})).unwrap(); + assert_eq!(r["skipped"], json!([{"layer": adjustment, "name": "Levels 1", "reason": "hidden by visibleOnly"}])); + assert_eq!(r["files"].as_array().unwrap().len(), 2); + let all = s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": "all", "visibleOnly": false})).unwrap(); + assert_eq!(all["skipped"], json!([])); + assert_eq!(all["files"].as_array().unwrap().len(), 3); +} + +#[test] +fn other_formats_still_skip_the_adjustment_and_keep_its_number() { + // Only PNG and JPEG were measured; PSD (like TIFF, BMP, Targa and PDF) keeps today's skip. + let dir = tmp("psd"); + let mut s = session(); + let adjustment = s.active().unwrap().doc.layers.last().unwrap().id.0; + let r = s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": "doc", "format": "psd"})).unwrap(); + assert_eq!(r["skipped"], json!([{"layer": adjustment, "name": "Levels 1", "reason": "adjustment layer has no pixels of its own"}])); + let files: Vec<&str> = r["files"].as_array().unwrap().iter().map(|v| v.as_str().unwrap()).collect(); + let names: Vec<&str> = files.iter().map(|f| f.rsplit(['/', '\\']).next().unwrap()).collect(); + assert_eq!(names, ["doc_0001_Empty.psd", "doc_0002_Background.psd"]); +} + +#[test] +fn an_adjustment_whose_mask_hides_part_of_it_is_still_skipped() { + // Not measured: a mask that hides something (here made from a selection) keeps today's skip. + let dir = tmp("masked"); + let mut s = crate::session(); + s.execute("file.new", json!({"width": 100, "height": 80, "depth": 8})).unwrap(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 50, "height": 80})).unwrap(); + s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap(); + let adjustment = s.active().unwrap().doc.layers.last().unwrap().id.0; + let r = s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": "doc"})).unwrap(); + assert_eq!(r["skipped"], json!([{"layer": adjustment, "name": "Levels 1", "reason": "adjustment layer has no pixels of its own"}])); + assert_eq!(r["files"].as_array().unwrap().len(), 1, "only the Background"); +} + +#[test] +fn an_adjustment_with_a_vector_mask_is_still_skipped() { + let dir = tmp("vector-masked"); + let mut s = crate::session(); + s.execute("file.new", json!({"width": 100, "height": 80, "depth": 8})).unwrap(); + let path = json!({"subpaths": [{"closed": true, "knots": [[0, 0], [50, 0], [50, 80], [0, 80]]}]}); + s.execute("layer.newAdjustmentLayer.levels", json!({"path": path})).unwrap(); + let adjustment = s.active().unwrap().doc.layers.last().unwrap().id.0; + let r = s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": "doc", "format": "jpg"})).unwrap(); + assert_eq!(r["skipped"], json!([{"layer": adjustment, "name": "Levels 1", "reason": "adjustment layer has no pixels of its own"}])); +} + +#[test] +fn an_adjustment_inside_a_group_is_still_skipped() { + // Not measured: an adjustment in a group keeps today's skip, and its number. + let mut s = session(); + s.edit("group the adjustment", |doc, _| { + let levels = doc.layers.pop().unwrap(); + doc.layers.push(Layer::group("Grp", vec![levels])); + Ok(()) + }) + .unwrap(); + let adjustment = s.active().unwrap().doc.layers.last().unwrap().children().unwrap()[0].id.0; + let r = s.execute("file.export.layersToFiles", json!({"dir": tmp("grouped"), "prefix": "doc"})).unwrap(); + assert_eq!(r["skipped"], json!([{"layer": adjustment, "name": "Levels 1", "reason": "adjustment layer has no pixels of its own"}])); + assert_eq!(r["files"].as_array().unwrap().len(), 2, "Empty and Background"); +} diff --git a/crates/engine-core/src/cmd/file_cmds/tests.rs b/crates/engine-core/src/cmd/file_cmds/tests.rs index 1274d51383..2f6cb00e47 100644 --- a/crates/engine-core/src/cmd/file_cmds/tests.rs +++ b/crates/engine-core/src/cmd/file_cmds/tests.rs @@ -2749,7 +2749,7 @@ fn layers_to_files_reports_skipped_layers_without_changing_files() { for depth in [8, 16, 32] { let dir = tmp(&format!("skipped-layers-{depth}")); let mut s = session(4, 4, depth); - let adjustment = s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap()["layer"].clone(); + s.execute("layer.newAdjustmentLayer.levels", json!({})).unwrap(); s.execute("layer.setProps", json!({"name": "Levels/α"})).unwrap(); let hidden = s.execute("layer.new.layer", json!({"name": "Levels/α"})).unwrap()["layer"].clone(); s.execute("layer.setProps", json!({"visible": false})).unwrap(); @@ -2758,22 +2758,16 @@ fn layers_to_files_reports_skipped_layers_without_changing_files() { assert_eq!( result["skipped"], json!([ - {"layer": hidden, "name": "Levels/α", "reason": "hidden by visibleOnly"}, - {"layer": adjustment, "name": "Levels/α", "reason": "adjustment layer has no pixels of its own"} + {"layer": hidden, "name": "Levels/α", "reason": "hidden by visibleOnly"} ]) ); - assert_eq!(result["files"], json!([join(&dir, "doc_0002_Background.png")])); - assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 1); + assert_eq!(result["files"], json!([join(&dir, "doc_0001_Levels_α.png"), join(&dir, "doc_0002_Background.png")])); + assert_eq!(std::fs::read_dir(&dir).unwrap().count(), 2); assert_eq!(s.active().unwrap().doc.layers.len(), before.layers.len()); assert!(!s.active().unwrap().doc.layer(LayerId(hidden.as_u64().unwrap())).unwrap().visible); let all = s.execute("file.export.layersToFiles", json!({"dir": dir, "prefix": "all", "visibleOnly": false})).unwrap(); - assert_eq!( - all["skipped"], - json!([ - {"layer": adjustment, "name": "Levels/α", "reason": "adjustment layer has no pixels of its own"} - ]) - ); - assert_eq!(all["files"], json!([join(&dir, "all_0000_Levels_α.png"), join(&dir, "all_0002_Background.png")])); + assert_eq!(all["skipped"], json!([])); + assert_eq!(all["files"], json!([join(&dir, "all_0000_Levels_α.png"), join(&dir, "all_0001_Levels_α.png"), join(&dir, "all_0002_Background.png")])); } } diff --git a/crates/engine-core/src/cmd/frame_cmds.rs b/crates/engine-core/src/cmd/frame_cmds.rs index a1254511c2..5850fce2ef 100644 --- a/crates/engine-core/src/cmd/frame_cmds.rs +++ b/crates/engine-core/src/cmd/frame_cmds.rs @@ -254,7 +254,10 @@ fn convert(s: &mut Session, p: &Value) -> Result { Some(v) => v.as_f64().filter(|v| v.is_finite() && (1.0..=300_000.0).contains(v)).ok_or_else(|| bad(format!("{k} must be 1..=300000"))), } }; - f.transform.m = [n("width", a)?, b, c, n("height", d)?, x, y]; + // The frame keeps the layer's centre, as in the reference (#17325): a new width or height moves the + // origin by half the change. `normalized` gives an axis-aligned transform, so `b` and `c` are 0. + let (w, h) = (n("width", a)?, n("height", d)?); + f.transform.m = [w, b, c, h, x + (a - w) / 2.0, y + (d - h) / 2.0]; } if !f.valid() { return Err(bad("invalid converted frame")); @@ -415,6 +418,8 @@ pub fn specs() -> Vec { #[cfg(test)] mod content_name_tests; #[cfg(test)] +mod convert_resize_tests; +#[cfg(test)] mod from_layers_hidden_tests; #[cfg(test)] mod mode_tests; diff --git a/crates/engine-core/src/cmd/frame_cmds/convert_resize_tests.rs b/crates/engine-core/src/cmd/frame_cmds/convert_resize_tests.rs new file mode 100644 index 0000000000..ca863c5703 --- /dev/null +++ b/crates/engine-core/src/cmd/frame_cmds/convert_resize_tests.rs @@ -0,0 +1,55 @@ +//! #17325: Convert to Frame with a new width or height resizes the frame around the layer's centre, as the reference +//! application does; without either the frame keeps the layer's bounds. + +use super::*; + +/// A 400 × 200 document with a shape layer "Rect" covering 200..280 × 60..120. +fn rect_layer() -> (Session, u64) { + let mut s = crate::session(); + s.execute("file.new", json!({"width": 400, "height": 200})).unwrap(); + let r = s.execute("shape.create", json!({"kind": "rect", "rect": [200, 60, 80, 60], "fill": "#e07020"})).unwrap(); + let id = r["layer"].as_u64().unwrap(); + s.execute("layer.setProps", json!({"layer": id, "name": "Rect"})).unwrap(); + (s, id) +} + +/// The frame's rect as (x0, x1, y0, y1). +fn frame_rect(s: &Session, id: u64) -> (f64, f64, f64, f64) { + let l = s.active().unwrap().doc.layer(LayerId(id)).unwrap(); + let [w, _, _, h, x, y] = l.frame.as_ref().expect("a frame").transform.m; + (x, x + w, y, y + h) +} + +#[test] +fn the_layer_has_the_measured_bounds() { + let (mut s, id) = rect_layer(); + s.execute("layer.frame.convert", json!({"layer": id})).unwrap(); + assert_eq!(frame_rect(&s, id), (200.0, 280.0, 60.0, 120.0), "without width or height the frame keeps the layer bounds"); +} + +#[test] +fn a_new_width_grows_around_the_centre() { + let (mut s, id) = rect_layer(); + let r = s.execute("layer.frame.convert", json!({"layer": id, "name": "MyFrame", "width": 160})).unwrap(); + assert_eq!(r["name"], "MyFrame"); + assert_eq!(frame_rect(&s, id), (160.0, 320.0, 60.0, 120.0)); +} + +#[test] +fn a_new_height_grows_around_the_centre() { + let (mut s, id) = rect_layer(); + s.execute("layer.frame.convert", json!({"layer": id, "height": 100})).unwrap(); + assert_eq!(frame_rect(&s, id), (200.0, 280.0, 40.0, 140.0)); +} + +#[test] +fn both_shrink_around_the_centre_and_the_mask_follows() { + let (mut s, id) = rect_layer(); + s.execute("layer.frame.convert", json!({"layer": id, "width": 40, "height": 20})).unwrap(); + assert_eq!(frame_rect(&s, id), (220.0, 260.0, 80.0, 100.0)); + let l = s.active().unwrap().doc.layer(LayerId(id)).unwrap(); + let path = &l.vector_mask.as_ref().unwrap().path; + let coverage = |x: i32, y: i32| photocraft_vector::path_coverage(path, photocraft_geom::Rect::new(x, y, x + 1, y + 1))[0]; + assert_eq!(coverage(240, 90), 1.0, "the centre is inside"); + assert_eq!(coverage(210, 90), 0.0, "the old left edge is outside"); +} diff --git a/crates/engine-core/src/cmd/frame_cmds/tests.rs b/crates/engine-core/src/cmd/frame_cmds/tests.rs index d672a24ff9..a09ada1282 100644 --- a/crates/engine-core/src/cmd/frame_cmds/tests.rs +++ b/crates/engine-core/src/cmd/frame_cmds/tests.rs @@ -247,7 +247,8 @@ fn converting_a_shape_uses_its_outline_and_leaves_an_empty_frame() { let l = s.active().unwrap().doc.layer(LayerId(id)).unwrap(); assert_eq!(l.name, "Portrait"); assert!(l.children().unwrap().is_empty()); - assert_eq!(l.frame.as_ref().unwrap().transform.m, [20., 0., 0., 25., 10., 15.]); + // The ellipse's 40 × 30 box at (10, 15) resized to 20 × 25 around its centre (30, 30) (#17325). + assert_eq!(l.frame.as_ref().unwrap().transform.m, [20., 0., 0., 25., 20., 17.5]); assert_eq!(TestMask(l.vector_mask.as_ref().unwrap().path.clone()).value(10, 15), 0.0); assert!(s.undo()); assert!(matches!(s.active().unwrap().doc.layer(LayerId(id)).unwrap().content, LayerContent::Shape(_))); diff --git a/crates/engine-core/src/cmd/photo_cmds.rs b/crates/engine-core/src/cmd/photo_cmds.rs index 6a2ae71ece..1b4ef684b0 100644 --- a/crates/engine-core/src/cmd/photo_cmds.rs +++ b/crates/engine-core/src/cmd/photo_cmds.rs @@ -627,22 +627,14 @@ fn apply_photometric(rois: &mut [RoiImage], fmt: PixelFormat, geometry: Option f64 { + pl.inverse(u, v).map_or(0.0, |(sx, sy)| { + let (w, h) = (size.0 as f64, size.1 as f64); + let (dx, dy) = (sx - w / 2.0, sy - h / 2.0); + (dx * dx + dy * dy) / (w * w / 4.0 + h * h / 4.0) + }) +} + +/// A colour sample brightened by the factor `f` (CMYK scales the light, not the ink), within range unless float. +fn scale_sample(v: f32, f: f32, fmt: PixelFormat) -> f32 { + let v = if fmt.mode == ColorMode::Cmyk { 1.0 - (1.0 - v) * f } else { v * f }; + if fmt.sample == SampleType::F32 { v } else { v.clamp(0.0, 1.0) } +} + +/// Vignette estimates read the layers box-averaged to at most this many pixels across: the falloff is smooth, and +/// [`panorama::photometric`] samples about 40 000 points of the overlaps anyway. +const VIGNETTE_SIDE: usize = 1024; + +/// The light in `surf`'s colour channels and its coverage, box-averaged over `k × k` pixels on a grid aligned to the +/// origin. The estimate fits light: CMYK reads as the red, green and blue light its inks let through, Lab as one +/// channel, its lightness as encoded luminance ([`lab_light`]). +fn roi_downsampled(surf: &Surface, k: usize) -> Result { + let fmt = surf.format(); + let cmyk = fmt.mode == ColorMode::Cmyk; + let lab = fmt.mode == ColorMode::Lab; + let n = fmt.channels(); + let cc = match fmt.mode { + ColorMode::Cmyk => 3, + ColorMode::Lab => 1, + mode => mode.color_channels(), + }; + let b = surf.content_bounds(); + if b.is_empty() { + return Ok(RoiImage { x0: 0, y0: 0, w: 0, h: 0, ch: cc, px: Vec::new(), alpha: Vec::new() }); + } + let ki = k as i32; + let (gx0, gy0) = (b.x0.div_euclid(ki), b.y0.div_euclid(ki)); + let (w, h) = (((b.x1 - gx0 * ki) as usize).div_ceil(k), ((b.y1 - gy0 * ki) as usize).div_ceil(k)); + let overflow = || crate::allocation::error("Auto-Align", "vignette estimate size overflowed"); + let cells = w.checked_mul(h).ok_or_else(overflow)?; + let samples = cells.checked_mul(cc).ok_or_else(overflow)?; + let mut px = crate::allocation::capacity(samples, "Auto-Align vignette estimate")?; + px.resize(samples, 0.0f32); + let mut alpha = crate::allocation::capacity(cells, "Auto-Align vignette estimate")?; + alpha.resize(cells, 0.0f32); + let mut row = vec![0.0f32; w * k * n]; + for y in gy0 * ki..(gy0 + h as i32) * ki { + surf.read_region_into(Rect::new(gx0 * ki, y, (gx0 + w as i32) * ki, y + 1), &mut row); + let line = ((y - gy0 * ki) as usize / k) * w; + for (x, q) in row.chunks_exact(n).enumerate() { + let cell = line + x / k; + let a = if fmt.alpha { q[n - 1] } else { 1.0 }; + alpha[cell] += a; + for c in 0..cc { + let light = if cmyk { + (1.0 - q[c]) * (1.0 - q[3]) + } else if lab { + lab_light(q[0]) + } else { + q[c] + }; + px[cell * cc + c] += light * a; + } + } + } + let area = (k * k) as f32; + for (cell, a) in alpha.iter_mut().enumerate() { + for v in &mut px[cell * cc..(cell + 1) * cc] { + *v = if *a > 0.0 { *v / *a } else { 0.0 }; + } + *a /= area; + } + Ok(RoiImage { x0: gx0, y0: gy0, w, h, ch: cc, px, alpha }) +} + +/// The vignetting falloff shared by `layers`, each warped into canvas coordinates by its placement from a `size` frame +/// (Auto-Align's Vignette Removal, #14197): Photomerge's estimate from the layers' overlaps, read at most +/// [`VIGNETTE_SIDE`] pixels across. Exposure gains are estimated beside it, so a brighter layer isn't taken for +/// vignetting, and then dropped. `[0, 0]` when the overlaps show none: too few, or every scene point at about the same +/// radius in each layer (a bracket whose layers nearly coincide). +pub fn estimate_vignette(layers: &[(&Surface, &Placement)], size: (usize, usize)) -> Result<[f64; 2]> { + let area = layers.iter().fold(Rect::EMPTY, |a, (s, _)| a.union(&s.content_bounds())); + if area.is_empty() { + return Ok([0.0, 0.0]); + } + let k = (area.width().max(area.height()) as usize).div_ceil(VIGNETTE_SIDE).max(1); + let rois = layers.iter().map(|(s, _)| roi_downsampled(s, k)).collect::>>()?; + // The same source points, landing on the `k`× smaller grid: a cell's centre is the centre of its `k × k` pixels. + let shrink = Homography([1.0 / k as f64, 0.0, 0.0, 0.0, 1.0 / k as f64, 0.0, 0.0, 0.0, 1.0]); + let placements: Vec = layers.iter().map(|(_, pl)| Placement { h: shrink.mul(&pl.h), ..(*pl).clone() }).collect(); + let sizes = vec![size; layers.len()]; + Ok(panorama::photometric(&rois, Some((&placements, &sizes)), true, true).vignette) +} + +/// `surf`, warped into canvas coordinates by `pl` from a `size` frame, with the falloff `vignette` +/// ([`estimate_vignette`]) divided out of its colour channels: of the light that CMYK's inks let through +/// ([`brighten_cmyk`]) and of Lab's lightness ([`brighten_lab`]). +pub fn remove_vignette(surf: &Surface, pl: &Placement, size: (usize, usize), vignette: [f64; 2]) -> Surface { + let fmt = surf.format(); + let (n, cc) = (fmt.channels(), fmt.mode.color_channels()); + let photo = panorama::Photometric { gains: vec![vec![1.0; cc]], vignette }; + let b = surf.content_bounds(); + let mut out = surf.clone(); + let mut row = vec![0.0f32; b.width() as usize * n]; + for y in b.y0..b.y1 { + let line = Rect::new(b.x0, y, b.x1, y + 1); + surf.read_region_into(line, &mut row); + for (x, q) in (b.x0..).zip(row.chunks_exact_mut(n)) { + let f = photo.factor(0, 0, source_r2(pl, size, x as f64 + 0.5, y as f64 + 0.5)); + match fmt.mode { + ColorMode::Cmyk => brighten_cmyk(q, f, fmt), + ColorMode::Lab => brighten_lab(q, f, fmt), + _ => { + for v in &mut q[..cc] { + *v = scale_sample(*v, f, fmt); + } + } + } + } + out.write_region(line, &row); + } + out +} + +/// CMYK pixel `q` with the red, green and blue light its inks let through brightened by the factor `f`, within range +/// unless float. Only C, M and Y thin out while they can carry it; K thins out as far as the brightest light needs, so a +/// grey printed in K alone still brightens. +fn brighten_cmyk(q: &mut [f32], f: f32, fmt: PixelFormat) { + let float = fmt.sample == SampleType::F32; + let light: [f32; 3] = std::array::from_fn(|c| { + let l = (1.0 - q[c]) * (1.0 - q[3]) * f; + if float { l } else { l.clamp(0.0, 1.0) } + }); + let k = q[3].min(1.0 - light.iter().fold(0.0f32, |a, l| a.max(*l))).max(0.0); + if k >= 1.0 { + return; + } + for c in 0..3 { + let v = 1.0 - light[c] / (1.0 - k); + q[c] = if float { v } else { v.clamp(0.0, 1.0) }; + } + q[3] = k; +} + +/// CIE L*a*b*'s companding: a tristimulus value relative to white → its `f`, a cube root above a linear toe. +fn lab_f(t: f32) -> f32 { + if t > (6.0f32 / 29.0).powi(3) { t.cbrt() } else { t / (3.0 * (6.0f32 / 29.0).powi(2)) + 4.0 / 29.0 } +} + +/// The inverse of [`lab_f`]. +fn lab_f_inv(f: f32) -> f32 { + if f > 6.0 / 29.0 { f * f * f } else { 3.0 * (6.0f32 / 29.0).powi(2) * (f - 4.0 / 29.0) } +} + +/// Lab's encoded L (0..1 for L* 0..100) as the sRGB-encoded luminance the vignette is fitted to and divided out of, as +/// RGB's encoded values are. +fn lab_light(l: f32) -> f32 { + photocraft_color::convert::linear_to_srgb(lab_f_inv((l * 100.0 + 16.0) / 116.0).max(0.0)) +} + +/// Lab pixel `q` with its light ([`lab_light`]) brightened by the factor `f`: X, Y and Z grow by the same ratio, as they +/// do when the light itself is brighter, so a neutral pixel stays neutral and a colour keeps its hue and saturation. +fn brighten_lab(q: &mut [f32], f: f32, fmt: PixelFormat) { + let float = fmt.sample == SampleType::F32; + let fy = (q[0] * 100.0 + 16.0) / 116.0; + let (a, b) = (q[1] * 255.0 - 128.0, q[2] * 255.0 - 128.0); + let xyz = [lab_f_inv(fy + a / 500.0), lab_f_inv(fy), lab_f_inv(fy - b / 200.0)]; + if xyz[1] <= 0.0 { + return; + } + let light = scale_sample(photocraft_color::convert::linear_to_srgb(xyz[1]), f, fmt); + let grow = photocraft_color::convert::srgb_to_linear(light) / xyz[1]; + let [fx, fy, fz] = xyz.map(|t| lab_f(t * grow)); + let lab = [(116.0 * fy - 16.0) / 100.0, (500.0 * (fx - fy) + 128.0) / 255.0, (200.0 * (fy - fz) + 128.0) / 255.0]; + for (v, n) in q.iter_mut().zip(lab) { + *v = if float { n } else { n.clamp(0.0, 1.0) }; + } +} + /// Per-image seam weights (1 inside an image's seam region, else 0) over each ROI. fn compute_seam_weights(rois: &[RoiImage], canvas: Rect, order: &[usize]) -> Vec> { let n = rois.len(); diff --git a/crates/engine-core/src/cmd/photo_cmds/tests.rs b/crates/engine-core/src/cmd/photo_cmds/tests.rs index 23baa9f901..0a2c17863f 100644 --- a/crates/engine-core/src/cmd/photo_cmds/tests.rs +++ b/crates/engine-core/src/cmd/photo_cmds/tests.rs @@ -654,3 +654,21 @@ fn photomerge_open_documents_ignores_the_folder() { let _ = s.execute("file.automate.photomerge", json!({"useOpenDocuments": true, "layout": "reposition", "paths": paths})); } } + +/// Vignette Removal brightens a Lab colour as brighter light would, in the linear toe of L* too: its linear red, green +/// and blue grow by one ratio, so the colour keeps its hue and saturation (#14197). +#[test] +fn a_brightened_lab_shadow_keeps_its_colour() { + use photocraft_color::convert::{lab_to_srgb, srgb_to_linear}; + let linear = |q: &[f32]| lab_to_srgb([q[0] * 100.0, q[1] * 255.0 - 128.0, q[2] * 255.0 - 128.0]).map(srgb_to_linear); + let fmt = PixelFormat::new(ColorMode::Lab, SampleType::F32, true); + for lab in [[4.0f32, 3.0, -2.0], [40.0, 20.0, -15.0]] { + let mut q = [lab[0] / 100.0, (lab[1] + 128.0) / 255.0, (lab[2] + 128.0) / 255.0, 1.0]; + let before = linear(&q); + brighten_lab(&mut q, 1.3, fmt); + let after = linear(&q); + let grow = after.iter().zip(&before).map(|(a, b)| a / b).collect::>(); + assert!(grow[0] > 1.0, "{lab:?} brightens: {grow:?}"); + assert!(grow.iter().all(|g| (g / grow[0] - 1.0).abs() < 0.01), "{lab:?}: every channel grows alike: {before:?} → {after:?}"); + } +} diff --git a/crates/engine-core/src/cmd/transform_cmds.rs b/crates/engine-core/src/cmd/transform_cmds.rs index 803c3ab8ef..9f1990ce71 100644 --- a/crates/engine-core/src/cmd/transform_cmds.rs +++ b/crates/engine-core/src/cmd/transform_cmds.rs @@ -19,6 +19,7 @@ fn has_layer(s: &Session) -> std::result::Result<(), String> { /// The History step name of a shape-tool bounding box scale (`edit.transform` `stepName`). pub const TRANSFORM_PATH: &str = "Transform Path"; +pub(crate) const TRANSFORM_AGAIN: &str = "Transform Again"; fn bad(msg: impl Into) -> EngineError { EngineError::BadParams { cmd: "edit.transform".into(), msg: msg.into() } @@ -858,12 +859,12 @@ fn with_panel_target(s: &Session, p: &Value) -> Value { } fn transform(s: &mut Session, p: &Value) -> Result { - // The shape tools' bounding box scales live shapes with this command and names the step as - // the reference does. Passed in, not renamed after: the edit may land later as a job. + // Pass the history label to the edit job so it is used when the transform lands. let step_name = match p.get("stepName") { None | Some(Value::Null) => "Free Transform", Some(Value::String(n)) if n == TRANSFORM_PATH => TRANSFORM_PATH, - Some(_) => return Err(bad("`stepName` must be \"Transform Path\"")), + Some(Value::String(n)) if n == TRANSFORM_AGAIN => TRANSFORM_AGAIN, + Some(_) => return Err(bad("`stepName` must be \"Transform Path\" or \"Transform Again\"")), }; let p = &with_panel_target(s, p); let st = s.active().ok_or(EngineError::NoDocument)?; @@ -1037,7 +1038,7 @@ pub fn specs() -> Vec { label: "Free Transform", menu: &[], shortcut: None, - params: r##"{"layer":id?,"layers":[id,…]? (several layers moved by one box, one step; default with neither = the selected layers, as Photoshop's Free Transform with several selected; refused as locked when the Background is among several),"rect":[x0,y0,x1,y1]? (source frame; default = the layers' content ∩ selection),"quad":[[x,y]×4]? (where the frame's corners go, clockwise from top-left),"matrix":[a,b,c,d,e,f]? (affine alternative),"scaleX":%?,"scaleY":%?,"rotate":deg?,"dx":px?,"dy":px?,"reference":"center|topLeft|top|topRight|left|right|bottomLeft|bottom|bottomRight"|[x,y]="center" (relative alternative: scale and rotate about this point, then move),"interpolation":"bicubic|bilinear|nearest|bicubicSharper|bicubicSmoother|bicubicAutomatic"="bicubic" (Photoshop's bicubic variants render as Bicubic),"stepName":"Transform Path"? (History step name; the shape tools' bounding box sends it; default "Free Transform"; any other value is refused),"target":"pixels"|"mask"|"quickMask"|{"channel":i}=Channels panel target (an unlinked mask, an alpha channel or the Quick Mask transforms alone; a linked mask moves with its layer)}"##, + params: r##"{"layer":id?,"layers":[id,…]? (several layers moved by one box, one step; default with neither = the selected layers, as Photoshop's Free Transform with several selected; refused as locked when the Background is among several),"rect":[x0,y0,x1,y1]? (source frame; default = the layers' content ∩ selection),"quad":[[x,y]×4]? (where the frame's corners go, clockwise from top-left),"matrix":[a,b,c,d,e,f]? (affine alternative),"scaleX":%?,"scaleY":%?,"rotate":deg?,"dx":px?,"dy":px?,"reference":"center|topLeft|top|topRight|left|right|bottomLeft|bottom|bottomRight"|[x,y]="center" (relative alternative: scale and rotate about this point, then move),"interpolation":"bicubic|bilinear|nearest|bicubicSharper|bicubicSmoother|bicubicAutomatic"="bicubic" (Photoshop's bicubic variants render as Bicubic),"stepName":"Transform Path|Transform Again"? (History step name; default "Free Transform"),"target":"pixels"|"mask"|"quickMask"|{"channel":i}=Channels panel target (an unlinked mask, an alpha channel or the Quick Mask transforms alone; a linked mask moves with its layer)}"##, enabled: has_layer, journal: true, run: transform, diff --git a/crates/engine-core/src/session/execute.rs b/crates/engine-core/src/session/execute.rs index cb5a2bcdc0..7df0e97e86 100644 --- a/crates/engine-core/src/session/execute.rs +++ b/crates/engine-core/src/session/execute.rs @@ -167,6 +167,11 @@ impl Session { if let Some(why) = bitmap_mode_refusal(self, spec.id, params) { return Err(why.into()); } + // A named layer is converted whatever else is selected; the menu (no params) is greyed + // with several layers selected (#17306). + if spec.id == crate::background_cmds::CMD && params.get("layer").is_some_and(|l| !l.is_null()) { + return crate::background_cmds::can_convert_active(self); + } channel_cmds::mask_target_enabled(self, spec.id, params).unwrap_or_else(|| (spec.enabled)(self)) } diff --git a/crates/engine-vector/src/cmd/align_cmds.rs b/crates/engine-vector/src/cmd/align_cmds.rs index f7066086e7..3e1b39879d 100644 --- a/crates/engine-vector/src/cmd/align_cmds.rs +++ b/crates/engine-vector/src/cmd/align_cmds.rs @@ -8,7 +8,8 @@ //! ([`photocraft_algo::direct`], `registration`: auto falls back to it, or ask for it). Projections: Auto, Perspective //! (homography), Cylindrical and Spherical (rigid motion on the cylinder / sphere, focal length //! from the homographies or EXIF), Collage (similarity) and Reposition (translation). The -//! reference stays put in the planar projections. +//! reference stays put in the planar projections. Vignette Removal estimates one radial falloff +//! from the layers' overlaps, as Photomerge does, and divides it out of every aligned layer. //! //! Auto-Blend gives each selected layer a mask so the composite shows, per pixel, the sharpest //! layer (Stack Images, for focus stacking) or one layer per region with seams routed where the @@ -21,7 +22,7 @@ //! from focus ([`photocraft_algo::dff`]): black = the bottom layer, white = the top, so that once //! on a layer mask it drives Lens Blur's depth map. -use photocraft_algo::panorama::Layout; +use photocraft_algo::panorama::{Layout, Placement}; use photocraft_algo::pyramid; use photocraft_algo::transform::Interp; use photocraft_algo::warp::warp_mesh_gray; @@ -31,7 +32,9 @@ use photocraft_raster::{Surface, to_rgba}; use serde_json::{Value, json}; use crate::commands::CommandSpec; -use crate::photo_cmds::{BlendOptions, NO_DETAIL, plane_matrix, register, register_direct, seam_blend, seam_order, warp_placed}; +use crate::photo_cmds::{ + BlendOptions, NO_DETAIL, estimate_vignette, plane_matrix, register, register_direct, remove_vignette, seam_blend, seam_order, warp_placed, +}; use crate::{EngineError, Result, Session}; fn bad(cmd: &str, msg: impl Into) -> EngineError { @@ -84,6 +87,12 @@ fn auto_align(s: &mut Session, p: &Value) -> Result { let projection = p.get("projection").and_then(Value::as_str).unwrap_or("auto"); let layout = Layout::parse(projection) .ok_or_else(|| bad(cmd, format!("unknown projection `{projection}` (auto|perspective|cylindrical|spherical|collage|reposition)")))?; + let vignette = match p.get("vignetteRemoval") { + None | Some(Value::Null) => false, + Some(v) => v.as_bool().ok_or_else(|| bad(cmd, "`vignetteRemoval` must be true or false"))?, + }; + // The dialog greys and clears Vignette Removal under Collage and Reposition; a script's request is ignored there too. + let vignette = vignette && !matches!(layout, Layout::Collage | Layout::Reposition); let st = s.active().ok_or(EngineError::NoDocument)?; let doc = st.doc.clone(); let reference = match p.get("reference").and_then(Value::as_u64) { @@ -130,7 +139,7 @@ fn auto_align(s: &mut Session, p: &Value) -> Result { if let Some(l) = moves.iter().find(|&&i| pinned(&doc, ids[i])).and_then(|&i| doc.layer(ids[i])) { return Err(EngineError::Other(format!("Auto-Align can't move the locked layer \"{}\"", l.name))); } - let warped: Vec<(LayerId, Surface, Option)> = moves + let mut warped: Vec<(LayerId, Surface, Option)> = moves .iter() .map(|&i| { let pl = al.placements[i].as_ref().ok_or_else(|| EngineError::Other("Auto-Align lost a layer's placement".into()))?; @@ -150,6 +159,47 @@ fn auto_align(s: &mut Session, p: &Value) -> Result { Ok((ids[i], px, mask)) }) .collect::>()?; + // Vignette Removal (#14197): one falloff for all the aligned layers, from their overlaps, divided out of each. The + // reference of a planar layout stays put but is brightened too, unless a lock keeps its pixels. + let size = (area.width() as usize, area.height() as usize); + let still = (!moves.contains(&ref_idx)).then_some(ref_idx).and_then(|i| Some((i, al.placements[i].as_ref()?))); + let mut falloff = None; + let mut reference_px = None; + let mut warnings: Vec = Vec::new(); + if vignette { + // The reference keeps its own pixels, but its placement carries the lens distortion `k1` that Geometric + // Distortion may fit: the estimate reads it warped by that placement, as it reads the layers that moved, and its + // correction measures radii in its own pixels, with no distortion. + let still_warped = match still { + Some((i, pl)) if pl.k1 != 0.0 => { + let b = surfs[i].content_bounds(); + Some(if b.is_empty() { surfs[i].clone() } else { warp_placed(surfs[i], b, (0.0, 0.0), pl, (0.0, 0.0), interp)? }) + } + _ => None, + }; + let mut layers: Vec<(&Surface, &Placement)> = warped.iter().zip(&moves).filter_map(|((_, px, _), &i)| Some((px, al.placements[i].as_ref()?))).collect(); + layers.extend(still.map(|(i, pl)| (still_warped.as_ref().unwrap_or(surfs[i]), pl))); + let v = estimate_vignette(&layers, size)?; + if negligible(v) { + warnings.push(NO_VIGNETTE.to_owned()); + } else { + for ((_, px, _), &i) in warped.iter_mut().zip(&moves) { + if let Some(pl) = al.placements[i].as_ref() { + *px = remove_vignette(px, pl, size, v); + } + } + if let Some((i, pl)) = still { + let locks = doc.effective_locks(ids[i]); + if locks.all || locks.pixels { + warnings + .push(format!("Vignette Removal left the locked reference layer \"{}\" as it was", doc.layer(ids[i]).map_or("", |l| l.name.as_str()))); + } else { + reference_px = Some((ids[i], remove_vignette(surfs[i], &Placement { k1: 0.0, ..pl.clone() }, size, v))); + } + } + } + falloff = Some(v); + } s.edit("Auto-Align Layers", |doc, _| { for (id, px, mask) in &warped { // Photoshop turns the Background into a normal layer before moving it. @@ -162,6 +212,12 @@ fn auto_align(s: &mut Session, p: &Value) -> Result { m.surface = ms.clone(); } } + // The reference doesn't move, so a Background stays the Background. + if let Some((id, px)) = &reference_px + && let Some(surf) = doc.layer_mut(*id).ok_or(EngineError::NoLayer(*id))?.surface_mut() + { + *surf = px.clone(); + } Ok(()) })?; let model = match al.layout { @@ -179,10 +235,19 @@ fn auto_align(s: &mut Session, p: &Value) -> Result { }) .collect(); Ok( - json!({"reference": reference.0, "layout": al.layout.name(), "registration": used, "focal": al.focal, "rms": al.rms, "aligned": aligned, "failed": failed}), + json!({"reference": reference.0, "layout": al.layout.name(), "registration": used, "focal": al.focal, "rms": al.rms, "aligned": aligned, "failed": failed, "vignette": falloff, "warnings": warnings}), ) } +/// Auto-Align's warning when Vignette Removal was asked for but the layers' overlaps show no falloff to remove. +const NO_VIGNETTE: &str = "Vignette Removal found no vignetting to remove: the layers' overlaps don't show any (layers that nearly coincide, as in a focus or exposure bracket, can't show it)"; + +/// Whether the falloff `log V = a·r² + b·r⁴` changes no pixel by as much as 1% out to the corners (r² = 1): what the +/// overlaps of layers that nearly coincide leave, where the estimate stays at its prior. +fn negligible([a, b]: [f64; 2]) -> bool { + (0..=10).map(|i| f64::from(i) / 10.0).all(|r2| (a * r2 + b * r2 * r2).abs() < 0.01) +} + /// The most memory Auto-Blend's working buffers may take past the canvas: a bound independent /// of the layers' own bounding boxes, which a sparse layer (a dot at each far corner) can make /// arbitrarily large, and of how many layers are blended. @@ -456,7 +521,7 @@ pub fn specs() -> Vec { spec!( "edit.autoAlignLayers", "Auto-Align Layers…", - r##"{"projection":"auto|perspective|cylindrical|spherical|collage|reposition","reference":layer id?=the locked selected layer, else the bottom selected layer,"geometricCorrection":bool=false,"interpolation":"bicubic|bilinear|nearest","registration":"auto|features|intensity"}"##, + r##"{"projection":"auto|perspective|cylindrical|spherical|collage|reposition","reference":layer id?=the locked selected layer, else the bottom selected layer,"geometricCorrection":bool=false,"vignetteRemoval":bool=false (ignored with collage and reposition),"interpolation":"bicubic|bilinear|nearest","registration":"auto|features|intensity"}"##, two_layers, auto_align ), @@ -478,3 +543,6 @@ mod auto_blend_background_tests; #[cfg(test)] mod auto_blend_stack_bottom_mask_tests; + +#[cfg(test)] +mod auto_align_vignette_tests; diff --git a/crates/engine-vector/src/cmd/align_cmds/auto_align_vignette_tests.rs b/crates/engine-vector/src/cmd/align_cmds/auto_align_vignette_tests.rs new file mode 100644 index 0000000000..bef3ceb0af --- /dev/null +++ b/crates/engine-vector/src/cmd/align_cmds/auto_align_vignette_tests.rs @@ -0,0 +1,261 @@ +//! Auto-Align's Vignette Removal (#14197): one falloff estimated from the layers' overlaps, as Photomerge does, and +//! divided out of every aligned layer; off, and under Collage or Reposition, the layers come out as before. + +use photocraft_color::convert::{lab_to_srgb, srgb_to_lab}; +use photocraft_color::{ColorMode, PixelFormat}; + +use super::*; + +const W: i32 = 400; +const H: i32 = 300; + +/// A scene larger than the canvas: soft mid-tone patches on a gentle gradient, every value well inside 0..1. +fn scene() -> Vec<[f32; 3]> { + let (sw, sh) = (W + 120, H + 100); + let mut px: Vec<[f32; 3]> = + (0..sw * sh).map(|i| 0.45 + 0.1 * (i % sw) as f32 / sw as f32 + 0.05 * (i / sw) as f32 / sh as f32).map(|v| [v, v, v]).collect(); + let mut seed = 7u64; + let mut rnd = || { + seed = seed.wrapping_mul(6364136223846793005).wrapping_add(1442695040888963407); + (seed >> 33) as f32 / (1u64 << 31) as f32 + }; + for _ in 0..400 { + let (x, y) = ((rnd() * (sw - 20) as f32) as i32, (rnd() * (sh - 16) as f32) as i32); + let (rw, rh) = (4 + (rnd() * 16.0) as i32, 4 + (rnd() * 12.0) as i32); + let c = [0.3 + 0.5 * rnd(), 0.3 + 0.5 * rnd(), 0.3 + 0.5 * rnd()]; + for yy in y..y + rh { + for xx in x..x + rw { + px[(yy * sw + xx) as usize] = c; + } + } + } + px +} + +/// The CMYK test layers' black ink, everywhere. +const BLACK_INK: f32 = 0.1; + +/// A canvas-sized layer: the scene seen from (`ox`, `oy`), darkened towards the corners by `exp(falloff · r²)` +/// (r = 1 at a corner), as a lens does. `look` is the document's mode, or `cmyk-k` for the scene in grey in K alone; in +/// `cmyk` the scene's light is printed in C, M and Y over [`BLACK_INK`]. +fn photo_layer(s: &mut Session, look: &str, name: &str, ox: i32, oy: i32, falloff: f32) -> LayerId { + let px = scene(); + s.execute("layer.new.layer", json!({"name": name})).unwrap(); + let id = s.active().unwrap().active_layer.unwrap(); + s.edit("photo", |doc, _| { + let surf = doc.layer_mut(id).unwrap().surface_mut().unwrap(); + let fmt = surf.format(); + let n = fmt.channels(); + let mut row = vec![0.0f32; W as usize * n]; + for y in 0..H { + for x in 0..W { + let (dx, dy) = (x as f32 + 0.5 - W as f32 / 2.0, y as f32 + 0.5 - H as f32 / 2.0); + let v = (falloff * (dx * dx + dy * dy) / ((W * W + H * H) as f32 / 4.0)).exp(); + let c = px[((y + oy) * (W + 120) + x + ox) as usize]; + let q = &mut row[x as usize * n..(x as usize + 1) * n]; + let c = c.map(|c| c * v); + match look { + "cmyk" => q.copy_from_slice(&[1.0 - c[0], 1.0 - c[1], 1.0 - c[2], BLACK_INK, 1.0]), + "cmyk-k" => q.copy_from_slice(&[0.0, 0.0, 0.0, 1.0 - (c[0] + c[1] + c[2]) / 3.0, 1.0]), + "lab" => { + let [l, a, b] = srgb_to_lab(c); + q.copy_from_slice(&[l / 100.0, (a + 128.0) / 255.0, (b + 128.0) / 255.0, 1.0]); + } + _ => q.copy_from_slice(&[c[0], c[1], c[2], 1.0]), + } + } + surf.write_region(Rect::new(0, y, W, y + 1), &row); + } + Ok(()) + }) + .unwrap(); + id +} + +/// Two vignetted photos of one scene, `shift` apart, both selected. +fn pair(falloff: f32, shift: (i32, i32)) -> (Session, [LayerId; 2]) { + pair_in("rgb", falloff, shift) +} + +/// [`pair`] drawn as [`photo_layer`]'s `look`. +fn pair_in(look: &str, falloff: f32, shift: (i32, i32)) -> (Session, [LayerId; 2]) { + let mut s = crate::session(); + let mode = look.split('-').next().unwrap_or(look); + s.execute("file.new", json!({"width": W, "height": H, "mode": mode, "background": "transparent"})).unwrap(); + let a = photo_layer(&mut s, look, "A", 0, 0, falloff); + let b = photo_layer(&mut s, look, "B", shift.0, shift.1, falloff); + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + s.execute("layer.select", json!({"layer": b.0, "mode": "add"})).unwrap(); + (s, [a, b]) +} + +fn pixels(s: &Session, id: LayerId) -> Vec { + s.active().unwrap().doc.layer(id).unwrap().surface().unwrap().read_region(Rect::new(-200, -200, W + 200, H + 200)) +} + +/// The red, green and blue light of pixel `q` summed: what CMYK's inks let through, and Lab's colour in sRGB. +fn light(mode: ColorMode, q: &[f32]) -> f32 { + match mode { + ColorMode::Cmyk => q[..3].iter().map(|c| (1.0 - c) * (1.0 - q[3])).sum(), + ColorMode::Lab => lab_to_srgb([q[0] * 100.0, q[1] * 255.0 - 128.0, q[2] * 255.0 - 128.0]).iter().sum(), + _ => q[..3].iter().sum(), + } +} + +fn format(s: &Session) -> PixelFormat { + s.active().unwrap().doc.pixel_format() +} + +/// How far apart the two aligned layers are where both are opaque: the mean |log| of their luminance ratio. The scene is +/// the same in both, so what's left is each one's vignetting at a different place in the frame. +fn mismatch(s: &Session, [a, b]: [LayerId; 2]) -> f64 { + let (pa, pb) = (pixels(s, a), pixels(s, b)); + let (mode, ch) = (format(s).mode, format(s).channels()); + let (mut sum, mut n) = (0.0, 0usize); + for (qa, qb) in pa.chunks_exact(ch).zip(pb.chunks_exact(ch)) { + if qa[ch - 1] > 0.999 && qb[ch - 1] > 0.999 { + let (la, lb) = (light(mode, qa), light(mode, qb)); + sum += f64::from((la / lb).ln().abs()); + n += 1; + } + } + assert!(n > 10_000, "the layers overlap"); + sum / n as f64 +} + +/// The mean luminance of layer `id` in the four corner squares of its own frame, a few pixels in from its warped edge. +fn corners(s: &Session, id: LayerId) -> f32 { + let surf = s.active().unwrap().doc.layer(id).unwrap().surface().unwrap(); + let b = surf.content_bounds(); + let (mode, ch) = (format(s).mode, format(s).channels()); + let mut sum = 0.0; + for (x, y) in [(b.x0 + 4, b.y0 + 4), (b.x1 - 34, b.y0 + 4), (b.x0 + 4, b.y1 - 34), (b.x1 - 34, b.y1 - 34)] { + sum += surf.read_region(Rect::new(x, y, x + 30, y + 30)).chunks_exact(ch).map(|q| light(mode, q)).sum::(); + } + sum / (4.0 * 900.0 * 3.0) +} + +fn align(s: &mut Session, params: Value) -> Value { + let r = s.execute("edit.autoAlignLayers", params).unwrap(); + assert_eq!(r["failed"], json!([]), "{r}"); + r +} + +#[test] +fn shifted_vignetted_layers_come_out_flatter_with_their_corners_brightened() { + shifted_layers_come_out_flatter("rgb"); +} + +/// CMYK samples are ink, which grows towards darkened corners: the falloff is fitted to their light, and the light of +/// C, M and Y is brightened once, not again through K's. +#[test] +fn shifted_vignetted_cmyk_layers_come_out_flatter_with_their_corners_brightened() { + shifted_layers_come_out_flatter("cmyk"); +} + +/// A grey printed in K alone can only brighten if K thins out. +#[test] +fn shifted_vignetted_cmyk_layers_in_black_ink_alone_come_out_flatter_with_their_corners_brightened() { + shifted_layers_come_out_flatter("cmyk-k"); +} + +/// Lab's lightness is brightened, and its a and b only as far as a brighter light would take them: no colour cast. +#[test] +fn shifted_vignetted_lab_layers_come_out_flatter_without_a_colour_cast() { + let ab = |s: &Session, id: LayerId| { + let surf = s.active().unwrap().doc.layer(id).unwrap().surface().unwrap(); + let b = surf.content_bounds(); + let px = surf.read_region(Rect::new(b.x0 + 4, b.y0 + 4, b.x0 + 34, b.y0 + 34)); + let mean = |c: usize| px.as_chunks::<4>().0.iter().map(|q| q[c] * 255.0 - 128.0).sum::() / 900.0; + [mean(1), mean(2)] + }; + let (mut s, ids) = pair_in("lab", -0.5, (60, 40)); + align(&mut s, json!({"projection": "auto"})); + let before = ids.map(|id| ab(&s, id)); + let (s, ids) = shifted_layers_come_out_flatter("lab"); + for (i, id) in ids.into_iter().enumerate() { + let after = ab(&s, id); + assert!((0..2).all(|c| (after[c] - before[i][c]).abs() < 5.0), "layer {i}'s corner a and b stay put: {after:?} vs {:?}", before[i]); + } +} + +/// Aligns a shifted vignetted pair drawn as `look` without and with Vignette Removal, checks the second is flatter with +/// brighter corners, and returns it. +fn shifted_layers_come_out_flatter(look: &str) -> (Session, [LayerId; 2]) { + let (mut s, ids) = pair_in(look, -0.5, (60, 40)); + let r = align(&mut s, json!({"projection": "auto"})); + assert_eq!(r["vignette"], Value::Null, "off by default: {r}"); + let (before, plain) = (mismatch(&s, ids), ids.map(|id| pixels(&s, id))); + let dark = ids.map(|id| corners(&s, id)); + s.undo(); + let r = align(&mut s, json!({"projection": "auto", "vignetteRemoval": false})); + assert!(ids.map(|id| pixels(&s, id)) == plain, "false is today's result: {r}"); + s.undo(); + let r = align(&mut s, json!({"projection": "auto", "vignetteRemoval": true})); + let v = r["vignette"].as_array().unwrap_or_else(|| panic!("{r}")); + assert!(v[0].as_f64().unwrap() + v[1].as_f64().unwrap() < -0.1, "a darkening falloff is found: {r}"); + assert_eq!(r["warnings"], json!([]), "{r}"); + let after = mismatch(&s, ids); + assert!(after < before * 0.6, "the overlap agrees better: {after} vs {before}"); + for (i, id) in ids.into_iter().enumerate() { + assert!(corners(&s, id) > dark[i] * 1.1, "layer {i}'s corners are brighter, the reference's too: {r}"); + } + (s, ids) +} + +#[test] +fn collage_and_reposition_ignore_vignette_removal() { + for projection in ["collage", "reposition"] { + let (mut s, ids) = pair(-0.5, (60, 40)); + align(&mut s, json!({"projection": projection})); + let plain = ids.map(|id| pixels(&s, id)); + s.undo(); + let r = align(&mut s, json!({"projection": projection, "vignetteRemoval": true})); + assert!(ids.map(|id| pixels(&s, id)) == plain, "{projection}: {r}"); + assert_eq!(r["vignette"], Value::Null, "{projection}: {r}"); + } +} + +/// Layers that coincide see every scene point at the same radius, so the overlaps can't show a falloff: the layers are +/// left as they are and the result says so, rather than claiming a correction. +#[test] +fn coinciding_layers_report_that_no_vignetting_was_found() { + let (mut s, ids) = pair(-0.5, (0, 0)); + align(&mut s, json!({"projection": "auto", "registration": "intensity"})); + let plain = ids.map(|id| pixels(&s, id)); + s.undo(); + let r = align(&mut s, json!({"projection": "auto", "registration": "intensity", "vignetteRemoval": true})); + assert_eq!(r["warnings"], json!([NO_VIGNETTE]), "{r}"); + assert!(ids.map(|id| pixels(&s, id)) == plain, "{r}"); +} + +#[test] +fn a_wrong_typed_vignette_removal_is_an_error() { + let (mut s, ids) = pair(-0.5, (60, 40)); + for bad in [json!("yes"), json!(1), json!(1e308), json!([true]), json!({"on": true})] { + let e = s.execute("edit.autoAlignLayers", json!({"vignetteRemoval": bad})).unwrap_err(); + assert!(e.to_string().contains("vignetteRemoval"), "{bad}: {e}"); + } + assert_eq!(s.active().unwrap().doc.layer(ids[1]).unwrap().surface().unwrap().content_bounds(), Rect::new(0, 0, W, H), "nothing moved"); +} + +/// A reference whose pixels are locked stays as it was, and the result says so; the layers aligned onto it are still +/// brightened. +#[test] +fn a_pixel_locked_reference_keeps_its_pixels() { + let (mut s, [a, b]) = pair(-0.5, (60, 40)); + s.edit("lock", |doc, _| { + doc.layer_mut(a).unwrap().locks.set("pixels", true); + Ok(()) + }) + .unwrap(); + align(&mut s, json!({"projection": "auto"})); + let dark = corners(&s, b); + s.undo(); + let kept = pixels(&s, a); + let r = align(&mut s, json!({"projection": "auto", "vignetteRemoval": true})); + assert_eq!(r["reference"], a.0, "{r}"); + assert!(pixels(&s, a) == kept, "{r}"); + assert!(r["warnings"].as_array().is_some_and(|w| w.len() == 1 && w[0].as_str().is_some_and(|m| m.contains("\"A\""))), "{r}"); + assert!(corners(&s, b) > dark * 1.1, "{r}"); +} diff --git a/crates/engine/tests/it/background_from_layer_multi_select.rs b/crates/engine/tests/it/background_from_layer_multi_select.rs new file mode 100644 index 0000000000..1c1bca541f --- /dev/null +++ b/crates/engine/tests/it/background_from_layer_multi_select.rs @@ -0,0 +1,133 @@ +//! Layer › New › Background from Layer with several layers selected (#17306). +//! +//! Measured in the reference: with two layers selected the menu item is greyed. With one layer it +//! is live for pixel, type, smart object, fill and shape layers and greyed for groups and +//! adjustment layers. A script or action that names the layer (`"layer": id`) converts that +//! layer, whatever is selected. + +use photocraft_doc::LayerId; +use photocraft_engine::Session; +use serde_json::{Value, json}; + +const CMD: &str = "layer.new.backgroundFromLayer"; + +/// A document without a Background: a transparent "Layer 1" plus A and B on top. +fn no_background() -> (Session, [LayerId; 3]) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 16, "height": 12, "background": "transparent"})).unwrap(); + let base = s.active().unwrap().active_layer.unwrap(); + let a = new_layer(&mut s, "A"); + let b = new_layer(&mut s, "B"); + (s, [base, a, b]) +} + +fn new_layer(s: &mut Session, name: &str) -> LayerId { + LayerId(s.execute("layer.new.layer", json!({"name": name})).unwrap()["layer"].as_u64().unwrap()) +} + +fn ids(r: &Value) -> LayerId { + LayerId(r["layer"].as_u64().unwrap()) +} + +fn order(s: &Session) -> Vec { + s.active().unwrap().doc.layers.iter().map(|l| l.id).collect() +} + +fn background(s: &Session) -> Option { + s.active().unwrap().doc.background().map(|l| l.id) +} + +#[test] +fn two_selected_layers_grey_the_command_and_a_call_without_layer_is_refused() { + let (mut s, [_, a, b]) = no_background(); + s.execute("layer.select", json!({"layers": [a.0, b.0]})).unwrap(); + assert_eq!(s.active().unwrap().selected_layers().len(), 2); + assert!(!s.is_enabled(CMD), "greyed with two layers selected"); + let why = s.disabled_reason(CMD).unwrap(); + assert!(why.contains("layers selected"), "the reason names the multi-selection: {why}"); + + let before = order(&s); + let revision = s.active().unwrap().revision; + let err = s.execute(CMD, json!({})).unwrap_err().to_string(); + assert!(err.contains("layers selected"), "the error names the reason: {err}"); + assert_eq!(order(&s), before, "no layer moved"); + assert_eq!(background(&s), None, "no Background made"); + assert_eq!(s.active().unwrap().revision, revision, "the document did not change"); + + // Three layers selected: greyed too. + let (mut s, [base, a, b]) = no_background(); + s.execute("layer.select", json!({"layers": [base.0, a.0, b.0]})).unwrap(); + assert!(!s.is_enabled(CMD)); + assert!(s.execute(CMD, json!({"layer": null})).is_err(), "a null layer is the selection too"); +} + +#[test] +fn an_explicit_layer_converts_that_layer_with_several_selected() { + // The named layer is one of the selected ones. + let (mut s, [_, a, b]) = no_background(); + s.execute("layer.select", json!({"layers": [a.0, b.0]})).unwrap(); + let r = s.execute(CMD, json!({"layer": a.0})).unwrap(); + assert_eq!(ids(&r), a); + assert_eq!(background(&s), Some(a), "A is the Background"); + assert_eq!(order(&s)[0], a, "at the bottom"); + + // The named layer is outside the selection. + let (mut s, [base, a, b]) = no_background(); + s.execute("layer.select", json!({"layers": [a.0, b.0]})).unwrap(); + s.execute(CMD, json!({"layer": base.0})).unwrap(); + assert_eq!(background(&s), Some(base)); +} + +#[test] +fn one_selected_layer_keeps_todays_rules() { + let live = |make: &dyn Fn(&mut Session)| { + let (mut s, _) = no_background(); + make(&mut s); + assert_eq!(s.active().unwrap().selected_layers().len(), 1); + s.is_enabled(CMD) + }; + assert!(live(&|_| {}), "pixel layer"); + assert!( + live(&|s| { + s.execute("type.create", json!({"x": 2, "y": 10, "text": "I", "size": 8})).unwrap(); + }), + "type layer" + ); + assert!( + live(&|s| { + s.execute("edit.fill", json!({"contents": "black"})).unwrap(); + s.execute("layer.smartObjects.convertToSmartObject", json!({})).unwrap(); + }), + "smart object" + ); + assert!( + live(&|s| { + s.execute("layer.newFillLayer.solidColor", json!({"color": "#4080c0"})).unwrap(); + }), + "solid colour fill layer" + ); + assert!( + live(&|s| { + s.execute("shape.create", json!({"kind": "rect", "rect": [2, 2, 6, 6]})).unwrap(); + }), + "shape layer" + ); + assert!( + !live(&|s| { + s.execute("layer.new.group", json!({})).unwrap(); + }), + "group" + ); + assert!( + !live(&|s| { + s.execute("layer.newAdjustmentLayer.invert", json!({})).unwrap(); + }), + "adjustment layer" + ); + + // And one selected pixel layer converts as before. + let (mut s, [_, a, _]) = no_background(); + s.execute("layer.select", json!({"layer": a.0})).unwrap(); + s.execute(CMD, json!({})).unwrap(); + assert_eq!(background(&s), Some(a)); +} diff --git a/crates/engine/tests/it/main.rs b/crates/engine/tests/it/main.rs index 784aaaa30f..652e368a46 100644 --- a/crates/engine/tests/it/main.rs +++ b/crates/engine/tests/it/main.rs @@ -38,6 +38,7 @@ mod auto_blend_layer_kinds; mod average_smart; mod background_and_mask_depth; mod background_from_layer_history_name; +mod background_from_layer_multi_select; mod background_job_target; mod background_layer_consistency; mod brush_smoothing; @@ -194,6 +195,7 @@ mod smart_rerender_fallback; mod style_and_align; mod svg_smart_object; mod tone_target_picker; +mod transform_again_history_name_tests; mod transform_budget_unclamped; mod type_format_targets; mod type_postscript_font; diff --git a/crates/engine/tests/it/transform_again_history_name_tests.rs b/crates/engine/tests/it/transform_again_history_name_tests.rs new file mode 100644 index 0000000000..1a12667cfd --- /dev/null +++ b/crates/engine/tests/it/transform_again_history_name_tests.rs @@ -0,0 +1,80 @@ +use photocraft_doc::LayerId; +use photocraft_engine::Session; +use photocraft_geom::Rect; +use serde_json::json; + +fn skewed_document(layer_count: usize) -> (Session, Vec) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 1000, "height": 700})).unwrap(); + let mut layers = Vec::new(); + for (name, rect, color) in + [("A", Rect::new(100, 100, 300, 300), [1.0, 0.0, 0.0, 1.0]), ("B", Rect::new(500, 300, 800, 500), [0.0, 0.0, 1.0, 1.0])].into_iter().take(layer_count) + { + let made = s.execute("layer.new.layer", json!({"name": name})).unwrap(); + let id = LayerId(made["layer"].as_u64().unwrap()); + s.edit("Paint rectangle", |doc, _| { + doc.layer_mut(id).unwrap().surface_mut().unwrap().fill_rect(rect, &color); + Ok(()) + }) + .unwrap(); + layers.push(id); + } + s.execute("layer.select", json!({"layer": layers[0].0})).unwrap(); + for id in &layers[1..] { + s.execute("layer.select", json!({"layer": id.0, "mode": "add"})).unwrap(); + } + s.execute("edit.transform", json!({"rect": [100, 100, 800, 500], "quad": [[200, 100], [900, 100], [800, 500], [100, 500]], "interpolation": "nearest"})) + .unwrap(); + (s, layers) +} + +fn bounds(s: &Session, layers: &[LayerId]) -> Vec { + let doc = &s.active().unwrap().doc; + layers.iter().map(|id| doc.layer(*id).unwrap().surface().unwrap().content_bounds()).collect() +} + +#[test] +fn transform_again_adds_one_named_undo_step_for_single_and_multiple_layers() { + for layer_count in [1, 2] { + let (mut s, layers) = skewed_document(layer_count); + let state = s.active().unwrap(); + let before = state.doc.clone(); + let previous_steps = state.history.past_len(); + assert_eq!(state.history.undo_label(), Some("Free Transform")); + + s.execute("edit.transform.again", json!({})).unwrap(); + let state = s.active().unwrap(); + assert_eq!(state.history.past_len(), previous_steps + 1); + assert_eq!(state.history.undo_label(), Some("Transform Again")); + assert_eq!(bounds(&s, &layers), [Rect::new(200, 100, 500, 300), Rect::new(500, 300, 900, 500)][..layer_count]); + + assert_eq!(s.execute("history.undo", json!({})).unwrap(), json!(true)); + let state = s.active().unwrap(); + assert_eq!(state.doc, before); + assert_eq!(state.history.past_len(), previous_steps); + assert_eq!(state.history.redo_label(), Some("Transform Again")); + } +} + +#[test] +fn recorded_transform_again_plays_the_concrete_transform_once() { + let (mut s, layers) = skewed_document(2); + s.execute("prefs.set", json!({"path": "actions.createSingleHistoryState", "value": false})).unwrap(); + s.execute("actions.record", json!({"name": "Repeat skew"})).unwrap(); + s.execute("edit.transform.again", json!({})).unwrap(); + s.execute("actions.stop", json!({})).unwrap(); + let repeated_bounds = bounds(&s, &layers); + let recorded = s.execute("actions.get", json!({"action": "Repeat skew"})).unwrap(); + let [step] = recorded["steps"].as_array().unwrap().as_slice() else { panic!("expected a single recorded step: {recorded}") }; + assert_eq!(step[0], "edit.transform"); + + assert_eq!(s.execute("history.undo", json!({})).unwrap(), json!(true)); + let before = s.active().unwrap().history.past_len(); + let played = s.execute("actions.play", json!({"action": "Repeat skew"})).unwrap(); + assert_eq!(played["ran"], 1, "{played}"); + assert!(played.get("failed").is_none(), "{played}"); + assert_eq!(bounds(&s, &layers), repeated_bounds); + let state = s.active().unwrap(); + assert_eq!(state.history.past_len(), before + 1); + assert_eq!(state.history.undo_label(), Some("Transform Again")); +} diff --git a/crates/ipp/Cargo.toml b/crates/ipp/Cargo.toml index 94d8bf6793..c8e0546c5e 100644 --- a/crates/ipp/Cargo.toml +++ b/crates/ipp/Cargo.toml @@ -7,7 +7,7 @@ license.workspace = true rust-version.workspace = true [dependencies] -craft-ipp = { git = "https://github.com/storytold/craft-libs", rev = "3eb5b528b08211844bc5c95c5a4fd169894d52ff" } +craft-ipp = { git = "https://github.com/storytold/craft-libs", rev = "bfd8fec34b2b0c7ecc5855f5ffc2c2f3e138bafc" } [lints] workspace = true diff --git a/crates/ui-egui/src/brush_behind_key_tests.rs b/crates/ui-egui/src/brush_behind_key_tests.rs index 8aff494bdf..00cd8c319e 100644 --- a/crates/ui-egui/src/brush_behind_key_tests.rs +++ b/crates/ui-egui/src/brush_behind_key_tests.rs @@ -34,7 +34,7 @@ fn options_show_behind(app: &mut PhotocraftApp, ctx: &Context) -> bool { match shape { egui::Shape::Text(text) => text.galley.text() == "Behind", egui::Shape::Vec(shapes) => shapes.iter().any(has_behind), - egui::Shape::PaintChunk(chunk) => chunk.iter().any(|clipped| has_behind(&clipped.shape)), + egui::Shape::PaintChunk(shapes) => shapes.iter().map(|clipped| &clipped.shape).any(has_behind), _ => false, } } diff --git a/crates/ui-egui/src/brush_resize_overlay_tests.rs b/crates/ui-egui/src/brush_resize_overlay_tests.rs index 4cce091112..92df799b02 100644 --- a/crates/ui-egui/src/brush_resize_overlay_tests.rs +++ b/crates/ui-egui/src/brush_resize_overlay_tests.rs @@ -28,13 +28,13 @@ fn harness() -> Harness<'static, Box> { h } -/// The shapes under `shape`, each with the clip it is painted under: a retained paint chunk's child keeps its own clip, -/// intersected with the chunk's, as the tessellator does. fn flatten<'a>(shape: &'a Shape, clip: egui::Rect, out: &mut Vec<(&'a Shape, egui::Rect)>) { - match shape { - Shape::Vec(v) => v.iter().for_each(|s| flatten(s, clip, out)), - Shape::PaintChunk(chunk) => chunk.iter().for_each(|clipped| flatten(&clipped.shape, clip.intersect(clipped.clip_rect), out)), - shape => out.push((shape, clip)), + if let Shape::Vec(v) = shape { + v.iter().for_each(|s| flatten(s, clip, out)); + } else if let Shape::PaintChunk(shapes) = shape { + shapes.iter().for_each(|clipped| flatten(&clipped.shape, clip.intersect(clipped.clip_rect), out)); + } else { + out.push((shape, clip)); } } diff --git a/crates/ui-egui/src/canvas/canvas_tool_menu.rs b/crates/ui-egui/src/canvas/canvas_tool_menu.rs index 810aec8d19..cb06dcb1d8 100644 --- a/crates/ui-egui/src/canvas/canvas_tool_menu.rs +++ b/crates/ui-egui/src/canvas/canvas_tool_menu.rs @@ -1984,25 +1984,32 @@ pub fn entries(app: &PhotocraftApp, menu: &CanvasToolMenu) -> Vec> out.push(Entry::separator()); continue; }; - let text = match row_label(app, menu, label, command) { - // Spelled out so `cargo xtask i18n-coverage` lists the new label. - "Free Transform Points" => tl!("Free Transform Points"), - "Fill Subpath…" => tl!("Fill Subpath…"), - "Fill Subpaths…" => tl!("Fill Subpaths…"), - "Stroke Subpath…" => tl!("Stroke Subpath…"), - "Stroke Subpaths…" => tl!("Stroke Subpaths…"), - "Rasterize Vector Mask" => tl!("Rasterize Vector Mask"), - // `layer_menu_ui::layer_count_label`'s labels, likewise (#12358). - "Duplicate Layer…" => tl!("Duplicate Layer…"), - "Delete Layer" => tl!("Delete Layer"), - "Duplicate Layers…" => tl!("Duplicate Layers…"), - "Delete Layers" => tl!("Delete Layers"), - "Rasterize Layers" => tl!("Rasterize Layers"), - "Hide Contextual Task Bar" => tl!("Hide Contextual Task Bar"), - "Show Contextual Task Bar" => tl!("Show Contextual Task Bar"), - key => tl!(key), + let shown = row_label(app, menu, label, command); + // The same label as Edit › Fade (#13803). + let text = if shown == "Fade…" { + crate::menus::fade_label(app) + } else { + match shown { + // Spelled out so `cargo xtask i18n-coverage` lists the new label. + "Free Transform Points" => tl!("Free Transform Points"), + "Fill Subpath…" => tl!("Fill Subpath…"), + "Fill Subpaths…" => tl!("Fill Subpaths…"), + "Stroke Subpath…" => tl!("Stroke Subpath…"), + "Stroke Subpaths…" => tl!("Stroke Subpaths…"), + "Rasterize Vector Mask" => tl!("Rasterize Vector Mask"), + // `layer_menu_ui::layer_count_label`'s labels, likewise (#12358). + "Duplicate Layer…" => tl!("Duplicate Layer…"), + "Delete Layer" => tl!("Delete Layer"), + "Duplicate Layers…" => tl!("Duplicate Layers…"), + "Delete Layers" => tl!("Delete Layers"), + "Rasterize Layers" => tl!("Rasterize Layers"), + "Hide Contextual Task Bar" => tl!("Hide Contextual Task Bar"), + "Show Contextual Task Bar" => tl!("Show Contextual Task Bar"), + key => tl!(key), + } + .to_string() }; - out.push(Entry::new(command.to_string(), text.to_string()).enabled(entry_enabled(app, menu, command)).checked(mode_checked(app, menu, command))); + out.push(Entry::new(command.to_string(), text).enabled(entry_enabled(app, menu, command)).checked(mode_checked(app, menu, command))); } out } diff --git a/crates/ui-egui/src/canvas/document_display.rs b/crates/ui-egui/src/canvas/document_display.rs index 1a1e2c96c0..6ad7487057 100644 --- a/crates/ui-egui/src/canvas/document_display.rs +++ b/crates/ui-egui/src/canvas/document_display.rs @@ -325,6 +325,21 @@ pub(crate) fn show(app: &mut PhotocraftApp, ui: &mut egui::Ui, view: &mut View, let mut overlay_context = None; let shown = canvas.show_at(ui, rect, |ui, body| { let Some(space) = canvas_space(&body.env) else { return }; + if !measuring && app.session.active_index() == Some(idx) { + let hovered = ui + .input(|i| i.pointer.hover_pos()) + .filter(|pos| space.view.rect.contains(*pos) && ui.ctx().layer_id_at(*pos).is_none_or(|layer| layer == ui.layer_id())) + .map(|pos| { + let at = space.view.to_doc(pos); + [at.x, at.y] + }); + let next = if primary { hovered } else { hovered.or(app.hover_doc) }; + if app.hover_doc != next { + app.hover_doc = next; + // The Info panel may have already drawn earlier in this frame. + ctx.request_repaint(); + } + } pasteboards(app, ui, body.rect, idx, border, label.clone()); guides = super::rulers::show(app, ui, host, ruler_guide(&body.env)); selection_controls(app, ui, body.rect, idx, &label); diff --git a/crates/ui-egui/src/canvas/tests.rs b/crates/ui-egui/src/canvas/tests.rs index 4af188f35b..65f2f26e94 100644 --- a/crates/ui-egui/src/canvas/tests.rs +++ b/crates/ui-egui/src/canvas/tests.rs @@ -666,7 +666,7 @@ fn flattened_paint_shapes(output: &egui::FullOutput) -> Vec<&egui::Shape> { fn open<'a>(shape: &'a egui::Shape, into: &mut Vec<&'a egui::Shape>) { match shape { egui::Shape::Vec(list) => list.iter().for_each(|shape| open(shape, into)), - egui::Shape::PaintChunk(chunk) => chunk.iter().for_each(|clipped| open(&clipped.shape, into)), + egui::Shape::PaintChunk(list) => list.iter().map(|clipped| &clipped.shape).for_each(|shape| open(shape, into)), shape => into.push(shape), } } diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index e79fcf9af5..1c7a0413a7 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -446,6 +446,7 @@ pub(crate) type PromptRow = fn(&mut PhotocraftApp, &egui::Context, &mut PromptAn pub(crate) const PROMPTS: &[PromptRow] = &[ crate::tools::tool_reset::answer, crate::analysis::note_alerts::answer, + crate::analysis::no_data_points_answer, delete_layer_prompt::answer, mask_trash_prompt::answer, disk_change_prompt::answer, diff --git a/crates/ui-egui/src/dialogs/file_ui/custom_paper_tests.rs b/crates/ui-egui/src/dialogs/file_ui/custom_paper_tests.rs index 4f0dc6347b..fdfe0c9dee 100644 --- a/crates/ui-egui/src/dialogs/file_ui/custom_paper_tests.rs +++ b/crates/ui-egui/src/dialogs/file_ui/custom_paper_tests.rs @@ -92,24 +92,26 @@ pub(super) fn click(h: &mut Harness<'_, Box>, label: &str) { h.run_steps(3); } -/// Scrolls the open paper list until the row `label` is shown: the list draws only the rows in view, so a row is not in -/// the access tree until the wheel has brought it into view. The list can open scrolled to its chosen row, so the wheel -/// goes down first and then up, past where it started. +/// Scrolls the open paper list until the row `label` is shown: the list draws only the rows in view, so a row near +/// the end is not in the access tree until the wheel has brought it into view. fn reveal(h: &mut Harness<'_, Box>, label: &str) { - for step in 0..120 { - if h.query_by_label(label).is_some() { - return; + // Reopening preserves the list offset: the next option may be above or below it. + for delta in [3.0, -3.0] { + for _ in 0..40 { + if h.query_by_label(label).is_some() { + return; + } + let list = h.query_all_by_role(egui::accesskit::Role::ListBox).last().expect("an open list").rect(); + h.hover_at(list.center()); + h.event(Event::MouseWheel { + source: egui::MouseWheelSource::Unknown, + unit: egui::MouseWheelUnit::Line, + delta: vec2(0.0, delta), + phase: egui::TouchPhase::Move, + modifiers: Modifiers::NONE, + }); + h.run_steps(2); } - let list = h.query_all_by_role(egui::accesskit::Role::ListBox).last().expect("an open list").rect(); - h.hover_at(list.center()); - h.event(Event::MouseWheel { - source: egui::MouseWheelSource::Unknown, - unit: egui::MouseWheelUnit::Line, - delta: vec2(0.0, if step < 40 { -3.0 } else { 3.0 }), - phase: egui::TouchPhase::Move, - modifiers: Modifiers::NONE, - }); - h.run_steps(2); } panic!("the row {label} never came into view"); } diff --git a/crates/ui-egui/src/i18n/live_tests.rs b/crates/ui-egui/src/i18n/live_tests.rs index 5e16c09ed6..f0cc6b5584 100644 --- a/crates/ui-egui/src/i18n/live_tests.rs +++ b/crates/ui-egui/src/i18n/live_tests.rs @@ -1,6 +1,7 @@ //! Behavioural checks for switching languages in a running shell. use super::*; +use crate::paint_test_support::drawn_text; use crate::prefs_ui::{apply_window, open_preferences, set_draft, window_open}; use crate::{PhotocraftApp, Services}; use craft::settings::testing::MemoryFiles; @@ -335,19 +336,3 @@ fn preferences_preview_does_not_commit_until_applied_and_survives_reload() { assert_eq!(restored.prefs().interface.language, "ko"); }); } - -fn drawn_text(h: &egui_kittest::Harness<'_, Box>) -> Vec { - fn collect(shape: &egui::Shape, text: &mut Vec) { - match shape { - egui::Shape::Text(shape) => text.push(shape.galley.job.text.clone()), - egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| collect(shape, text)), - egui::Shape::PaintChunk(chunk) => chunk.iter().for_each(|clipped| collect(&clipped.shape, text)), - _ => {} - } - } - let mut text = Vec::new(); - for shape in &h.output().shapes { - collect(&shape.shape, &mut text); - } - text -} diff --git a/crates/ui-egui/src/input/hold_keys/tests.rs b/crates/ui-egui/src/input/hold_keys/tests.rs index d9de57562f..2dae9cad76 100644 --- a/crates/ui-egui/src/input/hold_keys/tests.rs +++ b/crates/ui-egui/src/input/hold_keys/tests.rs @@ -218,7 +218,7 @@ fn painted_paths(h: &Harness<'static, Box>) -> Vec> { match s { egui::Shape::Path(p) if !p.closed => out.push(p.points.clone()), egui::Shape::Vec(v) => v.iter().for_each(|s| walk(s, out)), - egui::Shape::PaintChunk(chunk) => chunk.iter().for_each(|clipped| walk(&clipped.shape, out)), + egui::Shape::PaintChunk(v) => v.iter().map(|clipped| &clipped.shape).for_each(|s| walk(s, out)), _ => {} } } diff --git a/crates/ui-egui/src/levels_clipping_tests.rs b/crates/ui-egui/src/levels_clipping_tests.rs index 712431e449..3d4ba412d5 100644 --- a/crates/ui-egui/src/levels_clipping_tests.rs +++ b/crates/ui-egui/src/levels_clipping_tests.rs @@ -315,7 +315,7 @@ fn meshes_with(shapes: &[egui::epaint::ClippedShape], tex: egui::TextureId) -> u match s { egui::Shape::Mesh(m) => usize::from(m.texture_id == tex), egui::Shape::Vec(v) => v.iter().map(|s| count(s, tex)).sum(), - egui::Shape::PaintChunk(chunk) => chunk.iter().map(|clipped| count(&clipped.shape, tex)).sum(), + egui::Shape::PaintChunk(v) => v.iter().map(|clipped| &clipped.shape).map(|s| count(s, tex)).sum(), _ => 0, } } diff --git a/crates/ui-egui/src/lib.rs b/crates/ui-egui/src/lib.rs index dbf4286ee1..5e124d2801 100644 --- a/crates/ui-egui/src/lib.rs +++ b/crates/ui-egui/src/lib.rs @@ -83,6 +83,9 @@ pub use file_dialog::{FileDialogAnswer, FileDialogFn, FileDialogReply, FileDialo pub use file_open::OsEvent; pub use state::{Tool, UiState}; +#[cfg(test)] +mod paint_test_support; + mod app; mod input; mod prefs; diff --git a/crates/ui-egui/src/menu_catalog.rs b/crates/ui-egui/src/menu_catalog.rs index 46eba70539..849635a4b3 100644 --- a/crates/ui-egui/src/menu_catalog.rs +++ b/crates/ui-egui/src/menu_catalog.rs @@ -80,6 +80,8 @@ pub static CATALOG: &[(&[&str], &str, Option<&str>, &str)] = &[ (&["Edit"], "Undo", None, "edit.undo"), (&["Edit"], "Redo", None, "edit.redo"), (&["Edit"], "Toggle Last State", Some("Cmd+Alt+Z"), "edit.toggleLastState"), + // Fade sits in its own group, between separators (#13803). + (&["Edit"], "---", None, "---"), (&["Edit"], "Fade…", Some("Cmd+Shift+F"), "edit.fade"), (&["Edit"], "---", None, "---"), (&["Edit"], "Cut", None, "edit.cut"), diff --git a/crates/ui-egui/src/menus.rs b/crates/ui-egui/src/menus.rs index 280403f58f..71be6f2e01 100644 --- a/crates/ui-egui/src/menus.rs +++ b/crates/ui-egui/src/menus.rs @@ -13,6 +13,8 @@ use crate::PhotocraftApp; mod bar; pub mod enable_rules; pub(crate) mod facts; +#[cfg(test)] +mod fade_label_tests; mod invoke; mod items; pub mod native_menu; @@ -29,10 +31,10 @@ pub(crate) use invoke::{invoke_unguarded, panel_alias}; pub use items::{MenuModel, base_rows, is_live, menu_rows, model, row}; #[cfg(test)] pub(crate) use items::{fresh_bar, model_id}; -pub use state::is_enabled; pub(crate) use state::reveal_label; #[cfg(test)] use state::translated_menu_label; +pub use state::{fade_label, is_enabled}; /// What may run from the menus now: the gate (a dialog, the shortcut recorder) and the per-command /// rules (a full-window workspace, a pending crop). Both bars, the runtime's command gate and diff --git a/crates/ui-egui/src/menus/fade_label_tests.rs b/crates/ui-egui/src/menus/fade_label_tests.rs new file mode 100644 index 0000000000..82d2895c02 --- /dev/null +++ b/crates/ui-egui/src/menus/fade_label_tests.rs @@ -0,0 +1,61 @@ +//! #13803: Edit › Fade names the step it fades (`Fade Invert…`), reads plain `Fade…` and is +//! greyed when nothing can be faded, sits in its own group between separators, and the selection +//! right-click menu and `ui.menu.list` show the same label. + +use super::*; +use serde_json::json; + +fn app() -> Box { + let mut app = crate::PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 64, "height": 48})).unwrap(); + app +} + +/// Edit › Fade's (label, enabled) as the menus and `ui.menu.list` report it. +fn fade(app: &crate::PhotocraftApp) -> (String, bool) { + let row = menu_rows(app).into_iter().find(|r| r.command.id == "edit.fade").expect("Edit › Fade"); + (row.label, row.enabled) +} + +#[test] +fn the_label_names_the_step_it_fades() { + let mut app = app(); + app.run("image.adjustments.invert", json!({})).unwrap(); + assert_eq!(fade(&app), ("Fade Invert…".into(), true)); + app.run("filter.blur.gaussianBlur", json!({"radius": 2})).unwrap(); + assert_eq!(fade(&app).0, "Fade Gaussian Blur…"); + app.run("paint.stroke", json!({"points": [[8, 20], [56, 20]], "size": 6})).unwrap(); + assert_eq!(fade(&app).0, "Fade Brush Tool…"); + assert_eq!(fade_label(&app), "Fade Brush Tool…", "the right-click menu's row shows the same"); +} + +#[test] +fn nothing_to_fade_reads_plain_fade_and_is_greyed() { + let mut app = app(); + assert_eq!(fade(&app), ("Fade…".into(), false), "a fresh document"); + app.run("image.adjustments.invert", json!({})).unwrap(); + app.run("select.all", json!({})).unwrap(); + app.run("select.deselect", json!({})).unwrap(); + assert_eq!(fade(&app), ("Fade…".into(), false), "after Deselect"); + assert_eq!(fade_label(&app), "Fade…"); + let empty = crate::PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + assert_eq!(fade(&empty), ("Fade…".into(), false), "no document"); +} + +#[test] +fn fade_sits_in_its_own_group() { + let rows = menu_rows(&app()); + let edit: Vec<&str> = rows.iter().filter(|r| r.path == ["Edit"]).map(|r| r.label.as_str()).take(7).collect(); + assert_eq!(edit, ["Undo", "Redo", "Toggle Last State", "---", "Fade…", "---", "Cut"], "{edit:?}"); +} + +/// CodeRabbit on #15091: the label comes from the engine, so hiding Fade in Edit › Menus (which drops its row +/// from the menu list) does not turn the right-click menu's Fade back into plain `Fade…`. +#[test] +fn a_hidden_menu_row_does_not_change_the_right_click_label() { + let mut app = app(); + app.run("image.adjustments.invert", json!({})).unwrap(); + app.session.prefs.edit(|p| p.menus.hidden.push("edit.fade".into())); + assert!(menu_rows(&app).iter().all(|r| r.command.id != "edit.fade"), "the row is hidden from the menu list"); + assert_eq!(fade_label(&app), "Fade Invert…"); +} diff --git a/crates/ui-egui/src/menus/items.rs b/crates/ui-egui/src/menus/items.rs index 6a046a5b8e..454f427e9e 100644 --- a/crates/ui-egui/src/menus/items.rs +++ b/crates/ui-egui/src/menus/items.rs @@ -236,6 +236,10 @@ pub fn base_rows(app: &PhotocraftApp) -> Vec { { item.label = "Merge Group".into(); } + // Edit › Fade names the step it fades (#13803). + if let Some(item) = find(&mut rows, "edit.fade") { + item.label = photocraft_engine::edit_menu_cmds::fade_menu_label(&app.session); + } // 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. diff --git a/crates/ui-egui/src/menus/state.rs b/crates/ui-egui/src/menus/state.rs index ad1496d046..b8316b7d10 100644 --- a/crates/ui-egui/src/menus/state.rs +++ b/crates/ui-egui/src/menus/state.rs @@ -244,5 +244,24 @@ pub(super) fn translated_menu_label(lang: crate::i18n::Lang, id: &str, label: &s { return crate::i18n::fmt(crate::i18n::tr(lang, "New Window for {name}"), &[("name", name)]); } + if id == "edit.fade" { + return translated_fade_label(lang, label); + } crate::i18n::tr_id(lang, id, label).to_string() } + +/// Edit › Fade's `label` translated: `Fade Invert…` is the translated "Fade…" around the step's own +/// history name (#13803), plain `Fade…` just the translation. +pub(super) fn translated_fade_label(lang: crate::i18n::Lang, label: &str) -> String { + match label.strip_prefix("Fade ").and_then(|l| l.strip_suffix('…')) { + Some(step) => crate::i18n::tr_id(lang, "edit.fade", "Fade…").replace('…', &format!(" {step}…")), + None => crate::i18n::tr_id(lang, "edit.fade", label).to_string(), + } +} + +/// Edit › Fade's label as the menus show it, translated (#13803): `Fade Invert…` while Fade can +/// run, `Fade…` when it can't. The selection right-click menu shows the same. Read from the engine, +/// not from the menu rows, so hiding Fade in Edit › Menus does not change the right-click menu. +pub fn fade_label(app: &crate::PhotocraftApp) -> String { + translated_fade_label(crate::i18n::current(), &photocraft_engine::edit_menu_cmds::fade_menu_label(&app.session)) +} diff --git a/crates/ui-egui/src/menus/workspace_reset_captured_toolbar_tests.rs b/crates/ui-egui/src/menus/workspace_reset_captured_toolbar_tests.rs new file mode 100644 index 0000000000..9dcfcaf624 --- /dev/null +++ b/crates/ui-egui/src/menus/workspace_reset_captured_toolbar_tests.rs @@ -0,0 +1,84 @@ +use std::sync::Arc; + +use craft::settings::testing::MemoryFiles; +use craft::settings::{Location, OpenOptions, SettingsStore}; +use photocraft_engine::Session; +use photocraft_engine::prefs::SavedPrefs; +use serde_json::{Value, json}; + +use crate::{PhotocraftApp, Services, menus}; + +fn invoke(app: &mut PhotocraftApp, id: &str, params: Value) { + let ctx = app.ctx().clone(); + menus::invoke(app, &ctx, id, params).unwrap(); +} + +fn customizations(app: &mut PhotocraftApp) -> [Value; 3] { + ["toolbar", "shortcuts", "menus"].map(|path| app.run("prefs.get", json!({"path": path})).unwrap()) +} + +fn set_customizations(app: &mut PhotocraftApp, extra_tool: &str, brush_key: &str, fill_color: &str) { + app.run("edit.toolbar", json!({"reset": true, "extras": [[extra_tool]]})).unwrap(); + app.run("prefs.set", json!({"values": {"shortcuts.tools.select.brush": brush_key, "menus.colors.edit.fill": fill_color}})).unwrap(); +} + +#[test] +fn reset_restores_and_saves_all_captured_customizations() { + let files = Arc::new(MemoryFiles::new()); + let open_app = || { + let options = OpenOptions::new(Location::Dir("/memory/photocraft".into())).files(files.clone()); + let services = Services { settings: Some(SettingsStore::::open_with(options)), ..Default::default() }; + PhotocraftApp::new(Session::new(), services) + }; + let mut app = open_app(); + set_customizations(&mut app, "Frame", "F8", "red"); + let captured = customizations(&mut app); + invoke(&mut app, "workspace.new", json!({"name": "Retouch", "toolbar": true, "keyboardShortcuts": true, "menus": true})); + + set_customizations(&mut app, "Crop", "F9", "blue"); + let changed = customizations(&mut app); + for (before, after) in captured.iter().zip(&changed) { + assert_ne!(before, after); + } + invoke(&mut app, "workspace.reset", json!({})); + assert_eq!(customizations(&mut app), captured); + + crate::prefs_ui::save_preferences(&mut app).unwrap(); + drop(app); + let mut restarted = open_app(); + assert_eq!(customizations(&mut restarted), captured); +} + +#[test] +fn reset_applies_each_capture_independently() { + for toolbar in [true, false] { + let mut app = PhotocraftApp::new(Session::new(), Services::default()); + set_customizations(&mut app, "Frame", "F8", "red"); + let captured = customizations(&mut app); + invoke(&mut app, "workspace.new", json!({"name": "Retouch", "toolbar": toolbar, "keyboardShortcuts": !toolbar, "menus": !toolbar})); + + set_customizations(&mut app, "Crop", "F9", "blue"); + let changed = customizations(&mut app); + invoke(&mut app, "workspace.reset", json!({})); + let restored = customizations(&mut app); + for (index, captured_by_workspace) in [toolbar, !toolbar, !toolbar].into_iter().enumerate() { + let expected = if captured_by_workspace { &captured[index] } else { &changed[index] }; + assert_eq!(&restored[index], expected); + } + } +} + +#[test] +fn reset_keeps_live_customizations_without_captures() { + let mut app = PhotocraftApp::new(Session::new(), Services::default()); + set_customizations(&mut app, "Frame", "F8", "red"); + let live = customizations(&mut app); + invoke(&mut app, "workspace.reset", json!({})); + assert_eq!(customizations(&mut app), live, "built-in workspace"); + + invoke(&mut app, "workspace.new", json!({"name": "Panels Only"})); + set_customizations(&mut app, "Crop", "F9", "blue"); + let live = customizations(&mut app); + invoke(&mut app, "workspace.reset", json!({})); + assert_eq!(customizations(&mut app), live, "saved workspace without captures"); +} diff --git a/crates/ui-egui/src/menus/workspace_ui.rs b/crates/ui-egui/src/menus/workspace_ui.rs index fce826ac76..8877dbf5d6 100644 --- a/crates/ui-egui/src/menus/workspace_ui.rs +++ b/crates/ui-egui/src/menus/workspace_ui.rs @@ -270,6 +270,8 @@ pub fn run(app: &mut PhotocraftApp, _ctx: &egui::Context, command: WorkspaceComm Some(_) | None => {} } if command == WorkspaceCommands::Reset { + let current = app.workspaces.set.current.clone(); + restore_extras(app, ¤t); crate::dock::persist(app); } store(app); @@ -560,6 +562,10 @@ fn extras_options() -> [(&'static str, &'static str); 13] { ] } +#[cfg(test)] +#[path = "workspace_reset_captured_toolbar_tests.rs"] +mod workspace_reset_captured_toolbar_tests; + #[cfg(test)] mod tests { use super::*; diff --git a/crates/ui-egui/src/paint_test_support.rs b/crates/ui-egui/src/paint_test_support.rs new file mode 100644 index 0000000000..b00b9525ea --- /dev/null +++ b/crates/ui-egui/src/paint_test_support.rs @@ -0,0 +1,18 @@ +//! Paint inspection shared by unit and integration UI tests. + +/// Every text shape drawn this frame, including nested lists and retained paint chunks. +pub(crate) fn drawn_text(h: &egui_kittest::Harness<'_, State>) -> Vec { + fn collect(shape: &egui::Shape, text: &mut Vec) { + match shape { + egui::Shape::Text(shape) => text.push(shape.galley.job.text.clone()), + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| collect(shape, text)), + egui::Shape::PaintChunk(shapes) => shapes.iter().for_each(|clipped| collect(&clipped.shape, text)), + _ => {} + } + } + let mut text = Vec::new(); + for clipped in &h.output().shapes { + collect(&clipped.shape, &mut text); + } + text +} diff --git a/crates/ui-egui/src/panels/brush_panel/tests.rs b/crates/ui-egui/src/panels/brush_panel/tests.rs index 9ecee23ee1..c5784e928e 100644 --- a/crates/ui-egui/src/panels/brush_panel/tests.rs +++ b/crates/ui-egui/src/panels/brush_panel/tests.rs @@ -633,7 +633,7 @@ fn collect_text(shape: &egui::Shape, out: &mut Vec) { match shape { egui::Shape::Text(text) => out.push(text.galley.job.text.clone()), egui::Shape::Vec(shapes) => shapes.iter().for_each(|s| collect_text(s, out)), - egui::Shape::PaintChunk(chunk) => chunk.iter().for_each(|clipped| collect_text(&clipped.shape, out)), + egui::Shape::PaintChunk(shapes) => shapes.iter().map(|clipped| &clipped.shape).for_each(|s| collect_text(s, out)), _ => {} } } diff --git a/crates/ui-egui/src/panels/info.rs b/crates/ui-egui/src/panels/info.rs index 4bd9e0b9af..17b35899a8 100644 --- a/crates/ui-egui/src/panels/info.rs +++ b/crates/ui-egui/src/panels/info.rs @@ -229,6 +229,63 @@ mod tests { app.run("view.colorSamplers.add", json!({"x": 8, "y": 8})).unwrap(); assert_eq!(sampler_readouts(&mut app).len(), 2, "so does a new sampler"); } + + /// Hovering the canvas or dragging the Eyedropper updates `hover_doc` and the Info panel's + /// colour and position readouts; leaving the canvas clears them (#16654). + #[test] + fn canvas_hover_and_eyedropper_drag_update_info_readings() { + use egui::{Event, Modifiers, PointerButton, Pos2, RawInput, Rect, pos2, vec2}; + + use crate::canvas::document_display::CanvasHost; + use crate::state::{Tool, View}; + + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + let ctx = app.ctx().clone(); + app.run("file.new", json!({"width": 100, "height": 100, "background": "white"})).unwrap(); + app.run("prefs.set", json!({"path": "unitsAndRulers.rulers", "value": "pixels"})).unwrap(); + app.run("edit.fill", json!({"color": "#ff0000"})).unwrap(); + app.session + .edit("blue half", |doc, active| { + let id = active.unwrap(); + let surf = doc.layer_mut(id).unwrap().surface_mut().unwrap(); + surf.fill_rect(photocraft_geom::Rect::new(50, 0, 100, 100), &[0.0, 0.0, 1.0, 1.0]); + Ok(()) + }) + .unwrap(); + let mut view = View { zoom: 1.0, center: [50.0, 50.0], doc_size: [100, 100], ..Default::default() }; + view.clear_pending(); + let rect = Rect::from_min_size(Pos2::ZERO, vec2(100.0, 100.0)); + let step = |app: &mut PhotocraftApp, events: Vec| { + let input = RawInput { screen_rect: Some(rect), events, ..Default::default() }; + let mut out = ctx.run_ui(input, |ui| { + crate::canvas::canvas_view(app, ui, CanvasHost::main(0), rect, view.clone(), true); + }); + out.textures_delta.clear(); + }; + + // Hover over the red half: Info reports red and (20, 30). + step(&mut app, vec![Event::PointerMoved(pos2(20.5, 30.5))]); + let r = readings(&mut app, &[]); + assert_eq!(r.color.map(|c| c.rgb), Some([255, 0, 0]), "hovered red pixel"); + let pos = r.position.expect("hovered position"); + assert!(pos[0].as_str().starts_with("20") && pos[1].as_str().starts_with("30"), "got {pos:?}"); + + // Dragging the Eyedropper into the blue half keeps updating the Info readout. + app.ui.tool = Tool::Eyedropper; + step(&mut app, vec![Event::PointerButton { pos: pos2(20.5, 30.5), button: PointerButton::Primary, pressed: true, modifiers: Modifiers::NONE }]); + step(&mut app, vec![Event::PointerMoved(pos2(75.5, 40.5))]); + let r = readings(&mut app, &[]); + assert_eq!(r.color.map(|c| c.rgb), Some([0, 0, 255]), "dragged blue pixel"); + let pos = r.position.expect("dragged position"); + assert!(pos[0].as_str().starts_with("75") && pos[1].as_str().starts_with("40"), "got {pos:?}"); + + // Releasing and leaving the canvas clears the readings. + step(&mut app, vec![Event::PointerButton { pos: pos2(75.5, 40.5), button: PointerButton::Primary, pressed: false, modifiers: Modifiers::NONE }]); + step(&mut app, vec![Event::PointerGone]); + let r = readings(&mut app, &[]); + assert_eq!(r.color, None, "cleared after leaving canvas"); + assert_eq!(r.position, None, "position cleared after leaving canvas"); + } } #[cfg(test)] diff --git a/crates/ui-egui/src/panels/title_bar/tests.rs b/crates/ui-egui/src/panels/title_bar/tests.rs index b3d313fc97..1b7006f688 100644 --- a/crates/ui-egui/src/panels/title_bar/tests.rs +++ b/crates/ui-egui/src/panels/title_bar/tests.rs @@ -105,7 +105,7 @@ fn painted(h: &Harness<'static, Box>, text: &str) -> Option<(egui match shape { egui::Shape::Text(shape) if shape.galley.text() == text => Some((shape.visual_bounding_rect(), shape.galley.elided)), egui::Shape::Vec(shapes) => shapes.iter().find_map(|shape| find(shape, text)), - egui::Shape::PaintChunk(chunk) => chunk.iter().find_map(|clipped| find(&clipped.shape, text)), + egui::Shape::PaintChunk(shapes) => shapes.iter().map(|clipped| &clipped.shape).find_map(|shape| find(shape, text)), _ => None, } } diff --git a/crates/ui-egui/src/panels/toolbar_flyout_mark_tests.rs b/crates/ui-egui/src/panels/toolbar_flyout_mark_tests.rs index 6e964a90d4..50e444c7bd 100644 --- a/crates/ui-egui/src/panels/toolbar_flyout_mark_tests.rs +++ b/crates/ui-egui/src/panels/toolbar_flyout_mark_tests.rs @@ -35,6 +35,15 @@ fn open_shape_flyout(h: &mut Harness<'static, Box>) { h.run_steps(4); } +/// Inspect leaf paint shapes whether built directly or retained as a chunk. +fn leaf_shapes<'a>(shape: &'a egui::Shape, out: &mut Vec<&'a egui::Shape>) { + match shape { + egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| leaf_shapes(shape, out)), + egui::Shape::PaintChunk(shapes) => shapes.iter().for_each(|clipped| leaf_shapes(&clipped.shape, out)), + shape => out.push(shape), + } +} + #[test] fn the_shape_flyout_checks_the_shown_tool_and_marks_no_other() { let mut h = harness(); @@ -49,8 +58,10 @@ fn the_shape_flyout_checks_the_shown_tool_and_marks_no_other() { // What each row paints in its mark column, the room before its tool icon (the row's image): the shown tool's // check (a stroked path), nothing at all for the others. The accessible state alone would not catch a row that // paints a mark it does not report. - let output = h.output(); - let shapes = painted(&output.shapes); + let mut shapes = Vec::new(); + for clipped in &h.output().shapes { + leaf_shapes(&clipped.shape, &mut shapes); + } for (name, _, row) in &rows { let inside: Vec<&egui::Shape> = shapes.iter().copied().filter(|shape| row.contains(shape.visual_bounding_rect().center())).collect(); let icon = inside.iter().find(|shape| matches!(shape, egui::Shape::Mesh(_))).map(|shape| shape.visual_bounding_rect()); @@ -74,17 +85,3 @@ fn the_shape_flyout_checks_the_shown_tool_and_marks_no_other() { .count(); assert_eq!(rings, 0, "no row of the flyout draws an empty ring"); } - -/// The shapes a frame painted, with shape lists and retained paint chunks opened. -fn painted(shapes: &[egui::epaint::ClippedShape]) -> Vec<&egui::Shape> { - fn open<'a>(shape: &'a egui::Shape, into: &mut Vec<&'a egui::Shape>) { - match shape { - egui::Shape::Vec(list) => list.iter().for_each(|shape| open(shape, into)), - egui::Shape::PaintChunk(chunk) => chunk.iter().for_each(|clipped| open(&clipped.shape, into)), - shape => into.push(shape), - } - } - let mut out = Vec::new(); - shapes.iter().for_each(|clipped| open(&clipped.shape, &mut out)); - out -} diff --git a/crates/ui-egui/src/prefs/prefs_ui/fields.rs b/crates/ui-egui/src/prefs/prefs_ui/fields.rs index 3ec167fe52..6f6d636e8e 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/fields.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/fields.rs @@ -169,8 +169,7 @@ pub(super) fn rules(ctx: &egui::Context) -> Vec { tweak(&mut rules, path, |r| r.custom()); } // Rows that draw their own label or heading, so the window adds none: the Appearance page (Appearance Mode, the - // themes), Rendering Mode's select, the Memory Usage block and Memory Usage Percent's check box, which shows its - // label after the box as a check box in a row does. + // themes), Rendering Mode's select, the Memory Usage block and its labelled percent checkbox. for path in ["interface.appearanceMode", "performance.renderingMode", "performance.memoryUsageMb", "performance.memoryUsagePercent"] { tweak(&mut rules, path, |r| r.custom_rows()); } diff --git a/crates/ui-egui/src/prefs/prefs_ui/tests.rs b/crates/ui-egui/src/prefs/prefs_ui/tests.rs index ca25aab1d2..75a2e81c55 100644 --- a/crates/ui-egui/src/prefs/prefs_ui/tests.rs +++ b/crates/ui-egui/src/prefs/prefs_ui/tests.rs @@ -1802,7 +1802,7 @@ fn painted_texts(h: &egui_kittest::Harness<'static, Box>) -> Vec< match shape { egui::Shape::Text(text) => out.push((text.galley.text().trim_end_matches(':').to_owned(), text.galley.rect.translate(text.pos.to_vec2()))), egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| collect(shape, out)), - egui::Shape::PaintChunk(chunk) => chunk.iter().for_each(|clipped| collect(&clipped.shape, out)), + egui::Shape::PaintChunk(shapes) => shapes.iter().map(|clipped| &clipped.shape).for_each(|shape| collect(shape, out)), _ => {} } } @@ -1837,8 +1837,8 @@ fn the_interface_page_lists_appearance_presentation_then_options_on_one_label_co } /// The rows of Preferences › Performance that draw their own label or heading show it once: the window adds no second -/// "Rendering mode" beside the select's own, no "Memory usage (MB)" beside the Memory Usage heading, and no "Memory Usage -/// Percent" beside the check box's own. +/// "Rendering mode" beside the select's own, and no "Memory usage (MB)" beside the Memory Usage heading. Memory Usage +/// Percent's check box supplies its label, so the window adds none. #[test] fn self_labelled_performance_rows_show_their_label_once() { let (_, files) = app_with_store(); diff --git a/crates/ui-egui/src/tools/analysis/mod.rs b/crates/ui-egui/src/tools/analysis/mod.rs index 488d9499f8..fce2102caa 100644 --- a/crates/ui-egui/src/tools/analysis/mod.rs +++ b/crates/ui-egui/src/tools/analysis/mod.rs @@ -8,6 +8,8 @@ //! [`note_alerts`]. use craft::behavior::Selection; +use craft::ui::dialog::{PromptAnswer, PromptChoice, StandardPrompt}; +use photocraft_engine::analysis_cmds; use photocraft_engine::color_cmds::ColorExt; use serde::{Deserialize, Serialize}; use serde_json::{Value, json}; @@ -172,8 +174,12 @@ pub fn menu(app: &mut PhotocraftApp, id: &str, params: &Value) -> Option "auto", }; let r = app.run(id, json!({"source": source})); - if r.is_ok() { - let _ = crate::panel_docking::show_panel(app, MEASUREMENT_LOG, Some(true)); + match &r { + Ok(_) => { + let _ = crate::panel_docking::show_panel(app, MEASUREMENT_LOG, Some(true)); + } + Err(e) if e.starts_with(analysis_cmds::NO_DATA_POINTS) => no_data_points_alert(app, e), + Err(_) => {} } r } @@ -199,6 +205,43 @@ pub fn menu(app: &mut PhotocraftApp, id: &str, params: &Value) -> Option tl!("Ruler Tool"), + "Count Tool" => tl!("Count Tool"), + _ => tl!("Selection"), + }; + let message = crate::i18n::fmt(tl!("There are no measurement data points currently enabled for the {source}."), &[("source", name)]); + let prompt = StandardPrompt::custom(message) + .title(tl!("PhotoCraft")) + .paragraph(tl!("Data points must be set before measurements can be recorded.")) + .icon(craft::behavior::IconId::new("warning")) + .button(PromptChoice::Proceed, tl!("OK")) + .button(PromptChoice::Alternate, tl!("Set Data Points…")) + .escape(PromptChoice::Proceed) + .tag(NoDataPoints); + let _ = crate::dialogs::alerts::open_prompt(app, prompt); +} + +/// The `PROMPTS` entry of that alert: Set Data Points… opens Select Data Points, whose OK only stores the set. +pub(crate) fn no_data_points_answer(app: &mut PhotocraftApp, _ctx: &egui::Context, answer: &mut PromptAnswer) -> bool { + if answer.take_tag::().is_none() { + return false; + } + if answer.choice == PromptChoice::Alternate + && let Err(error) = dialogs::open(app, dialogs::Kind::DataPoints) + { + crate::dialogs::alerts::report_error(app, error); + } + true +} + /// Export the Measurement Log (or the given rows) as CSV through the save picker. pub(crate) fn export_log(app: &mut PhotocraftApp, rows: Option>) -> Result { let p = rows.map_or(json!({}), |r| json!({"rows": r})); @@ -251,3 +294,7 @@ pub(super) fn status_on_err(app: &mut PhotocraftApp, r: Result) { app.ui.status_error = false; } } + +#[cfg(test)] +#[path = "record_no_data_points_alert_tests.rs"] +mod record_no_data_points_alert_tests; diff --git a/crates/ui-egui/src/tools/analysis/record_no_data_points_alert_tests.rs b/crates/ui-egui/src/tools/analysis/record_no_data_points_alert_tests.rs new file mode 100644 index 0000000000..fffc0f5f7e --- /dev/null +++ b/crates/ui-egui/src/tools/analysis/record_no_data_points_alert_tests.rs @@ -0,0 +1,76 @@ +//! #17407: Image › Analysis › Record Measurements with no data point enabled for the source shows the warning with +//! OK and Set Data Points…; the latter opens Select Data Points with the current set, whose OK only stores the set. + +use craft::ui::dialog::{DialogId, StandardPrompt}; +use craft::ui::patterns::form_dialogs::HostedParamDialog; +use serde_json::json; + +use super::NoDataPoints; +use crate::PhotocraftApp; + +const RECORD: &str = "image.analysis.recordMeasurements"; + +fn app() -> (Box, egui::Context) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 120})).unwrap(); + app.run("image.analysis.selectDataPoints", json!({"selection": [], "ruler": ["length", "angle"], "count": []})).unwrap(); + app.run("select.rect", json!({"x": 10, "y": 10, "width": 100, "height": 50})).unwrap(); + let ctx = app.ctx().clone(); + (app, ctx) +} + +fn rows(app: &mut PhotocraftApp) -> usize { + app.run("measurementLog.list", json!({})).unwrap()["rows"].as_array().map_or(0, Vec::len) +} + +/// The open alert: its id, and its message, paragraphs and buttons as shown. +fn alert(app: &PhotocraftApp) -> Option<(DialogId, String, Vec, Vec)> { + let id = crate::dialogs::alerts::prompt_tagged::(app)?; + let prompt = app.framework.dialogs.get::()?; + let host = app.framework.host(); + let buttons = prompt.shown_buttons(host).into_iter().map(|(_, label)| label).collect(); + Some((id, prompt.shown_message(host), prompt.shown_paragraphs(host), buttons)) +} + +#[test] +fn record_measurements_shows_the_warning_with_ok_and_set_data_points() { + let (mut app, ctx) = app(); + assert!(crate::menus::invoke(&mut app, &ctx, RECORD, json!({})).is_err()); + let (id, message, paragraphs, buttons) = alert(&app).expect("the warning is open"); + assert_eq!(message, "There are no measurement data points currently enabled for the Selection."); + assert_eq!(paragraphs, ["Data points must be set before measurements can be recorded."]); + assert_eq!(buttons, ["OK", "Set Data Points…"]); + assert_eq!(rows(&mut app), 0, "nothing is recorded"); + + crate::dialogs::confirm(&mut app, &ctx, id).unwrap(); + assert!(alert(&app).is_none(), "OK closes it"); + assert!(app.framework.dialogs.get::().is_none(), "OK opens nothing"); +} + +#[test] +fn set_data_points_opens_select_data_points_whose_ok_only_stores_the_set() { + let (mut app, ctx) = app(); + let _ = crate::menus::invoke(&mut app, &ctx, RECORD, json!({})); + let (id, ..) = alert(&app).unwrap(); + app.framework.dialogs.set_json_field(&ctx, id, "choice", json!("alternate")).unwrap(); + crate::dialogs::confirm(&mut app, &ctx, id).unwrap(); + assert!(alert(&app).is_none()); + + let dialog = app.framework.dialogs.get::().map(craft::ui::dialog::StackDialog::id).expect("Select Data Points is open"); + // The current set: Ruler Length is ticked, Selection Area is not. + let fields = serde_json::to_value(app.framework.dialogs.get_by_id::(dialog).unwrap().fields()).unwrap(); + assert_eq!(fields["ruler:length"], json!(true), "{fields}"); + assert_ne!(fields["selection:area"], json!(true), "{fields}"); + + crate::dialogs::confirm(&mut app, &ctx, dialog).unwrap(); + assert_eq!(rows(&mut app), 0, "its OK records nothing"); + assert!(alert(&app).is_none(), "its OK does not record, so it does not warn again"); + let points = app.run("image.analysis.selectDataPoints", json!({})).unwrap(); + assert_eq!(points["dataPoints"]["ruler"], json!(["length", "angle"]), "its OK stores the set it shows: {points}"); + + app.run("image.analysis.selectDataPoints", json!({"selection": ["area"], "ruler": [], "count": []})).unwrap(); + // Now Record Measurements records, as "Measurement 1". + crate::menus::invoke(&mut app, &ctx, RECORD, json!({})).unwrap(); + assert_eq!(rows(&mut app), 1); + assert!(alert(&app).is_none()); +} diff --git a/crates/ui-egui/src/tools/analysis/tests.rs b/crates/ui-egui/src/tools/analysis/tests.rs index 48a025c118..e106c702c5 100644 --- a/crates/ui-egui/src/tools/analysis/tests.rs +++ b/crates/ui-egui/src/tools/analysis/tests.rs @@ -454,7 +454,7 @@ fn count_number_height(label_size: u32) -> f32 { while let Some(shape) = stack.pop() { match shape { Shape::Vec(v) => stack.extend(v.iter()), - Shape::PaintChunk(chunk) => stack.extend(chunk.iter().map(|clipped| &clipped.shape)), + Shape::PaintChunk(v) => stack.extend(v.iter().map(|clipped| &clipped.shape)), Shape::Text(t) if t.galley.text() == "1" => heights.push(t.galley.size().y), _ => {} } diff --git a/crates/ui-egui/src/tools/frame_tool/labels_tests.rs b/crates/ui-egui/src/tools/frame_tool/labels_tests.rs index 95932c8918..8a37f0c81f 100644 --- a/crates/ui-egui/src/tools/frame_tool/labels_tests.rs +++ b/crates/ui-egui/src/tools/frame_tool/labels_tests.rs @@ -1,5 +1,6 @@ //! #13877: the Frame shape buttons use the measured tooltips, and Polygon shows a `#` caption. +use crate::paint_test_support::drawn_text as drawn; use egui::accesskit::Role; use egui_kittest::Harness; use egui_kittest::kittest::Queryable; @@ -33,22 +34,6 @@ fn bar() -> Harness<'static, Box> { h } -fn drawn(h: &Harness<'_, Box>) -> Vec { - fn collect(shape: &egui::Shape, text: &mut Vec) { - match shape { - egui::Shape::Text(shape) => text.push(shape.galley.job.text.clone()), - egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| collect(shape, text)), - egui::Shape::PaintChunk(chunk) => chunk.iter().for_each(|clipped| collect(&clipped.shape, text)), - _ => {} - } - } - let mut text = Vec::new(); - for shape in &h.output().shapes { - collect(&shape.shape, &mut text); - } - text -} - #[test] fn shape_buttons_show_the_exact_tooltips_in_order_and_still_select_their_shapes() { let mut h = bar(); diff --git a/crates/ui-egui/src/transform_undo_tests.rs b/crates/ui-egui/src/transform_undo_tests.rs index 20b546cef9..ab5d98c3ad 100644 --- a/crates/ui-egui/src/transform_undo_tests.rs +++ b/crates/ui-egui/src/transform_undo_tests.rs @@ -252,7 +252,7 @@ fn transform_preview_stays_visible_while_panning() { fn shows(shape: &egui::epaint::Shape, texture: egui::TextureId) -> bool { match shape { egui::epaint::Shape::Vec(list) => list.iter().any(|shape| shows(shape, texture)), - egui::epaint::Shape::PaintChunk(chunk) => chunk.iter().any(|clipped| shows(&clipped.shape, texture)), + egui::epaint::Shape::PaintChunk(list) => list.iter().map(|clipped| &clipped.shape).any(|shape| shows(shape, texture)), egui::epaint::Shape::Mesh(mesh) => mesh.texture_id == texture, _ => false, } diff --git a/crates/ui-egui/tests/it/crop_options_bar_chrome.rs b/crates/ui-egui/tests/it/crop_options_bar_chrome.rs index a1f1a47147..47240f938a 100644 --- a/crates/ui-egui/tests/it/crop_options_bar_chrome.rs +++ b/crates/ui-egui/tests/it/crop_options_bar_chrome.rs @@ -1,6 +1,7 @@ //! #10888: the Crop options bar's Fill help. The help is a hosted alert; Escape closes it and must //! not reach the pending crop underneath. +use crate::paint_test_support::drawn_text as drawn; use egui_kittest::Harness; use egui_kittest::kittest::Queryable; use photocraft_ui_egui::PhotocraftApp; @@ -41,23 +42,6 @@ fn request(h: &mut App, method: &str, params: serde_json::Value) { h.run_steps(6); } -/// Every text shape the harness drew this frame, tooltips and modals included. -fn drawn(h: &Harness<'_, State>) -> Vec { - fn collect(shape: &egui::Shape, text: &mut Vec) { - match shape { - egui::Shape::Text(shape) => text.push(shape.galley.job.text.clone()), - egui::Shape::Vec(shapes) => shapes.iter().for_each(|shape| collect(shape, text)), - egui::Shape::PaintChunk(chunk) => chunk.iter().for_each(|clipped| collect(&clipped.shape, text)), - _ => {} - } - } - let mut text = Vec::new(); - for shape in &h.output().shapes { - collect(&shape.shape, &mut text); - } - text -} - fn help_open(h: &App) -> bool { drawn(h).iter().any(|t| t == "Fill options") } diff --git a/crates/ui-egui/tests/it/main.rs b/crates/ui-egui/tests/it/main.rs index 5315c28e74..3fb958ce40 100644 --- a/crates/ui-egui/tests/it/main.rs +++ b/crates/ui-egui/tests/it/main.rs @@ -1,5 +1,8 @@ //! The crate's integration tests, linked into one test binary. +#[path = "../../src/paint_test_support.rs"] +mod paint_test_support; + mod actions_duplicate; mod actions_panel_menu; mod apply_data_set_dialog; diff --git a/crates/ui-egui/tests/it/mixer_reset_defaults.rs b/crates/ui-egui/tests/it/mixer_reset_defaults.rs index df275e321a..d111be89d6 100644 --- a/crates/ui-egui/tests/it/mixer_reset_defaults.rs +++ b/crates/ui-egui/tests/it/mixer_reset_defaults.rs @@ -69,7 +69,7 @@ fn assert_chip(app: &mut PhotocraftApp, label: &str) { match shape { Shape::Text(text) => text.galley.text() == label && rect.contains(text.pos), Shape::Vec(shapes) => shapes.iter().any(|shape| has_text(shape, rect, label)), - Shape::PaintChunk(chunk) => chunk.iter().any(|clipped| has_text(&clipped.shape, rect, label)), + Shape::PaintChunk(shapes) => shapes.iter().map(|clipped| &clipped.shape).any(|shape| has_text(shape, rect, label)), _ => false, } } diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 088570f226..dc3daef554 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -559,7 +559,7 @@ stdio, and a value that is not a port is a usage error naming the variable. Impl | `doc.open` / `doc.new` | `{path, approveHighMemory? (false)}` / `file.new` params (`approveHighMemory` is the same one-shot PSD/PSB consent as the `file.openAs` command; see [development.md](development.md) for the structured refusal fields) | | `doc.place` | `{path, scale? (percent), fit? (true), center? ([x, y]), approveHighMemory? (false), index?}`: places a file as a Smart Object layer above the active one and returns `{layer, scale, bounds}`. `path` resolves beneath the read root, so this is the capability-scoped `file.placeEmbedded` — that command itself still refuses an ambient path. `approveHighMemory` is refused unless it is a boolean | | `doc.replaceSmartObject` | `{path, layer? (id or name; default the active layer), index?}` → the command's `{layer, instances}`: replaces a Smart Object's contents (one history step, transform and filters kept). `path` resolves beneath the read root, so this is the capability-scoped `layer.smartObjects.replaceContents`, which itself still refuses an ambient path (#8061) | -| `doc.exportLayers` | `{dir, format? (png), prefix?, visibleOnly? (true), quality?, index?}` → `{files, skipped}` (plus `count` for workspace exports): one file per exported layer, named like `file.export.layersToFiles` names them: `__` at the top level and `_s__` inside a group (one `s_` per group level), art layers and groups counted separately at each level. `count` is present only for workspace exports and counts written files only. `skipped` is always an array (empty when nothing is omitted), in top-to-bottom order, of `{layer, name, reason}`: the session layer id, original unsanitized name, and `"hidden by visibleOnly"` or `"adjustment layer has no pixels of its own"`. Visibility takes precedence for hidden adjustments; `visibleOnly:false` exports hidden non-adjustment layers. Groups are walked: a group gets no file, each layer in it does (inside its groups in the file), and with `visibleOnly` the layers of a hidden group are skipped as `"hidden by visibleOnly"`. `dir` resolves beneath the write root, so the ambient command stays refused. The bytes come from the command's own core, so both paths write the same files; the write capability refuses to overwrite an existing file. Encode/write failures are errors, not skips | +| `doc.exportLayers` | `{dir, format? (png), prefix?, visibleOnly? (true), quality?, index?}` → `{files, skipped}` (plus `count` for workspace exports): one file per exported layer, named like `file.export.layersToFiles` names them: `__` at the top level and `_s__` inside a group (one `s_` per group level), art layers and groups counted separately at each level. `count` is present only for workspace exports and counts written files only. `skipped` is always an array (empty when nothing is omitted), in top-to-bottom order, of `{layer, name, reason}`: the session layer id, original unsanitized name, and `"hidden by visibleOnly"` or, for formats other than PNG and JPEG, `"adjustment layer has no pixels of its own"`. Visibility takes precedence for hidden adjustments; `visibleOnly:false` exports hidden layers. For PNG and JPEG a top-level adjustment layer whose mask hides nothing is exported like an empty layer; one with a mask that hides something, a vector mask, or inside a group is still skipped. Groups are walked: a group gets no file, each layer in it does (inside its groups in the file), and with `visibleOnly` the layers of a hidden group are skipped as `"hidden by visibleOnly"`. `dir` resolves beneath the write root, so the ambient command stays refused. The bytes come from the command's own core, so both paths write the same files; the write capability refuses to overwrite an existing file. Encode/write failures are errors, not skips | | `doc.exportDataSets` | `{dir, format? (png), dataSets? (all), naming? ("{name}\|{index}\|{document}"), index?}` → `{files, count}`: the capability-scoped `file.export.dataSetsAsFiles`. The batch is planned first and colliding names are refused before any file is written, as in the command | | `doc.importDataSets` | `{path, delimiter? (,), index?}` → `{imported}`: the capability-scoped `file.import.variableDataSets`; the CSV is read beneath the read root | | `doc.save` | `{path?, format?, quality?, index?, tiffLayers?, tiffCompression?, tiffTransparency?, tiffPyramid?, tgaBits?, dpxBits?, ddsCompression?, ddsMipmaps?, pdfSpotPlates?, pcraftFullComposite?, maximizeCompatibility?}` (`.pcraft` native, else export by extension; set `tiffLayers: true` to preserve TIFF layers rather than exporting a flattened TIFF; `tiffCompression` (`none`, `lzw`, `zip`), `tiffTransparency` (bool: Save Transparency; unset, kept unless the document has alpha or spot channels) and `tiffPyramid` (bool) are TIFF Options; `dpxBits` selects 8, 10, 12 or 16 bits per sample for DPX (unset: 8 for an 8-bit document, otherwise 16); `tgaBits` 24 or 32 sets a TGA's bits per pixel, `ddsCompression`/`ddsMipmaps` a DDS texture's compression and mip chain, and `maximizeCompatibility: false` writes a layered PSD/PSB with Photoshop's placeholder instead of the merged image, except for Bitmap, Indexed Color and Duotone documents, as `app.save` does; `pdfSpotPlates: false` leaves a PDF's spot plates out, which are written by default, and refuses a Multichannel document, which has no image to write without them; `pcraftFullComposite: true` also writes the flattened document at its canvas size into a `.pcraft` file as `composite/full.png`; the save may leave it out in the cases listed in [the format guide](../book/src/formats/pcraft.md), and the manifest's `full_composite` member names it when written). Without `path` only a PSD, PSB or `.pcraft` document is written back to its own file, in its own format; anything else is an error and the file is left unchanged. A successful layered save (PSD, PSB or `.pcraft`) records the current revision as saved and makes the file the document's path, so `session.list` reports `dirty: false`; a flat export is a copy and leaves the document dirty |