diff --git a/crates/engine/src/cmd/atn_cmds.rs b/crates/engine/src/cmd/atn_cmds.rs index 4b50abfcf5..feb8a1a3dd 100644 --- a/crates/engine/src/cmd/atn_cmds.rs +++ b/crates/engine/src/cmd/atn_cmds.rs @@ -214,3 +214,6 @@ mod recorded_tools_tests; #[cfg(test)] mod artboard_section_tests; + +#[cfg(test)] +mod fade_step_tests; diff --git a/crates/engine/src/cmd/atn_cmds/fade_step_tests.rs b/crates/engine/src/cmd/atn_cmds/fade_step_tests.rs new file mode 100644 index 0000000000..83c82f078f --- /dev/null +++ b/crates/engine/src/cmd/atn_cmds/fade_step_tests.rs @@ -0,0 +1,99 @@ +use super::*; + +/// One action with a single recorded Fade step. +fn fade_file(descriptor: Descriptor) -> Vec { + atn::write(&AtnFile { + name: UnicodeString::new_nul("Fade"), + actions: vec![AtnAction { + name: UnicodeString::new_nul("Step"), + items: vec![AtnItem { event: AtnEvent::Code(*b"Fade"), dictionary: b"Fade".to_vec(), descriptor: Some(descriptor), ..Default::default() }], + ..Default::default() + }], + ..Default::default() + }) + .unwrap() +} + +/// The command, opacity and mode a recorded Fade step imports as. +fn imported(descriptor: Descriptor) -> (String, f64, String) { + let loaded = import(&fade_file(descriptor)).unwrap(); + assert!(loaded.unsupported.is_empty()); + let (id, params) = &loaded.actions[0].steps[0]; + (id.clone(), params["opacity"].as_f64().unwrap(), params["mode"].as_str().unwrap().to_owned()) +} + +/// An 8 x 8 image, inverted so there is an edit to fade. +fn inverted(depth: u8) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width":8,"height":8,"depth":depth,"background":"transparent"})).unwrap(); + s.execute("edit.fill", json!({"contents":"color","color":"#4080c0"})).unwrap(); + s.execute("image.adjustments.invert", json!({})).unwrap(); + s +} + +/// The pixel a recorded Fade step leaves after the Invert it fades. +fn played(depth: u8, descriptor: Descriptor) -> Value { + let mut s = inverted(depth); + let loaded = s.execute("actions.load", json!({"data":photocraft_paint::tile::b64_encode(&fade_file(descriptor))})).unwrap(); + assert_eq!(loaded["unsupported"], json!([])); + let result = s.execute("actions.play", json!({"action":loaded["actions"][0]})).unwrap(); + assert!(result.get("failed").is_none(), "{result}"); + s.execute("document.pixel", json!({"x":3,"y":3})).unwrap() +} + +/// The pixel `edit.fade` leaves when run directly with these params. +fn faded(depth: u8, params: Value) -> Value { + let mut s = inverted(depth); + s.execute("edit.fade", params).unwrap(); + s.execute("document.pixel", json!({"x":3,"y":3})).unwrap() +} + +/// A step with no keys plays at 100 % Normal; with one key, the other takes its default. +#[test] +fn fade_step_missing_keys_take_fixed_defaults() { + assert_eq!(imported(desc("null")), ("edit.fade".into(), 100.0, "Normal".into())); + assert_eq!(imported(desc("null").with("Opct", pct(40.0))), ("edit.fade".into(), 40.0, "Normal".into())); + assert_eq!(imported(desc("null").with("Md ", enm("BlnM", "Mltp"))), ("edit.fade".into(), 100.0, "Multiply".into())); + for depth in [8, 16, 32] { + assert_eq!(played(depth, desc("null")), faded(depth, json!({"opacity":100,"mode":"normal"}))); + assert_eq!(played(depth, desc("null").with("Md ", enm("BlnM", "Mltp"))), faded(depth, json!({"opacity":100,"mode":"multiply"}))); + } +} + +/// Opacity less than 100 out of range wraps modulo 100 and fractions round; whole values in range +/// are unchanged, and unmeasured values further out keep the clamp. +#[test] +fn fade_step_opacity_wraps_and_rounds() { + for (recorded, expected) in [ + (150.0, 50.0), + (-5.0, 95.0), + (50.5, 51.0), + (0.0, 0.0), + (37.0, 37.0), + (100.0, 100.0), + (-0.4, 0.0), + (199.0, 99.0), + (200.0, 100.0), + (1e9, 100.0), + (-100.0, 0.0), + (-105.0, 0.0), + ] { + let (id, opacity, _) = imported(desc("null").with("Opct", pct(recorded)).with("Md ", enm("BlnM", "Nrml"))); + assert_eq!(id, "edit.fade"); + assert_eq!(opacity, expected, "{recorded}"); + assert!(opacity.is_sign_positive(), "{recorded}"); + } + for depth in [8, 16, 32] { + let recorded = desc("null").with("Opct", pct(150.0)).with("Md ", enm("BlnM", "Nrml")); + assert_eq!(played(depth, recorded), faded(depth, json!({"opacity":50,"mode":"normal"}))); + } +} + +/// Recording still writes both keys, so a step imported without them saves them explicitly. +#[test] +fn fade_step_saves_both_keys() { + let loaded = import(&fade_file(desc("null"))).unwrap(); + let saved = export("Fade", &[&loaded.actions[0]], &[], false).unwrap().0; + let d = atn::parse(&saved).unwrap().actions[0].items[0].descriptor.clone().unwrap(); + assert_eq!(d, desc("null").with("Opct", pct(100.0)).with("Md ", enm("BlnM", "Nrml"))); +} diff --git a/crates/engine/src/cmd/atn_cmds/selection_tests.rs b/crates/engine/src/cmd/atn_cmds/selection_tests.rs index 66c99248c6..7611baae17 100644 --- a/crates/engine/src/cmd/atn_cmds/selection_tests.rs +++ b/crates/engine/src/cmd/atn_cmds/selection_tests.rs @@ -56,7 +56,7 @@ fn fixtures() -> Vec<(&'static str, Option<&'static str>, Descriptor)> { ellipse.items.last_mut().unwrap().1 = D::Boolean(false); cases.push(("AddT", Some("addTo"), ellipse)); for mode in ["Scrn", "H", "linearDodge"] { - cases.push(("Fade", Some("fade"), desc("null").with("Opct", pct(25.5)).with("Md ", enm("BlnM", mode)))); + cases.push(("Fade", Some("fade"), desc("null").with("Opct", pct(25.0)).with("Md ", enm("BlnM", mode)))); } for edge in ["AdCH", "AdRg", "AdTp", "AdCV", "AdBt"] { cases.push(("Dstr", Some("distribute"), desc("null").with("null", target_ref("Lyr ")).with("Usng", enm("ADSt", edge)))); @@ -262,12 +262,12 @@ fn noncanonical_group_f_enums_keep_their_bytes_and_flags() { } } -/// Fade writes native defaults and clamps only its documented opacity range. +/// Fade writes native defaults; a recorded opacity just outside 0..=100 wraps modulo 100 on import. #[test] fn fade_defaults_and_opacity_limits_are_explicit() { let native = export_item("edit.fade", &json!({}), "S").unwrap().descriptor.unwrap(); assert_eq!(native, desc("null").with("Opct", pct(100.0)).with("Md ", enm("BlnM", "Nrml"))); - for (opacity, expected) in [(-5.0, 0.0), (0.0, 0.0), (100.0, 100.0), (105.0, 100.0)] { + for (opacity, expected) in [(-5.0, 95.0), (0.0, 0.0), (100.0, 100.0), (105.0, 5.0), (250.0, 100.0)] { let bytes = file(AtnEvent::Code(*b"Fade"), desc("null").with("Opct", pct(opacity)).with("Md ", enm("BlnM", "Nrml"))); let loaded = import(&bytes).unwrap(); assert!(loaded.unsupported.is_empty()); @@ -302,7 +302,6 @@ fn group_f_unsupported_settings_are_not_silently_replaced() { (*b"AddT", wrong_ref), (*b"PstI", desc("null").with("AntA", enm("Annt", "Unknown")).with("As ", D::Class(class("Pxel")))), (*b"PstO", desc("null").with("AntA", enm("Annt", "Anno")).with("As ", D::Class(class("Other")))), - (*b"Fade", desc("null").with("Opct", pct(50.0))), (*b"Fade", desc("null").with("Opct", px(50.0)).with("Md ", enm("BlnM", "Nrml"))), (*b"Dstr", desc("null").with("null", target_ref("Lyr ")).with("Usng", enm("ADSt", "Unknown"))), (*b"RmvL", desc("null").with("apply", D::Boolean(true))), diff --git a/crates/engine/src/cmd/atn_cmds/steps_selection.rs b/crates/engine/src/cmd/atn_cmds/steps_selection.rs index 1c30dc93ab..4755ce94fb 100644 --- a/crates/engine/src/cmd/atn_cmds/steps_selection.rs +++ b/crates/engine/src/cmd/atn_cmds/steps_selection.rs @@ -151,22 +151,49 @@ pub(super) fn paste_to(_: &str, p: &Value) -> Option { Some(desc("null").with("AntA", enm("Annt", "Anno")).with("As ", D::Class(class("Pxel")))) } -/// Fade requires the settings recorded after the edit it fades, not guessed factory values. +/// Fade plays the recorded settings; a missing key takes the reference application's fixed default +/// (100 % opacity, Normal mode), not the dialog's last values. Opacity is rounded to a whole percent. pub(super) fn fade_from(d: &Descriptor) -> Mapped { let mapped = || { if !keys(d, &["Opct", "Md "]) { return None; } - let mode = blend_label(&enumeration(d, "Md ", "BlnM")?)?; - // An accepted alias would be rewritten to the exporter's preferred blend identifier. - if d.get("Md ") != Some(&enm("BlnM", blend_ps(mode)?)) { - return None; - } - Some(json!({"opacity":unit(d,"Opct",b"#Prc")?.clamp(0.0,100.0),"mode":mode})) + let mode = match d.get("Md ") { + None => "Normal", + Some(recorded) => { + let mode = blend_label(&enumeration(d, "Md ", "BlnM")?)?; + // An accepted alias would be rewritten to the exporter's preferred blend identifier. + if *recorded != enm("BlnM", blend_ps(mode)?) { + return None; + } + mode + } + }; + let opacity = match d.get("Opct") { + None => 100.0, + Some(_) => fade_opacity(unit(d, "Opct", b"#Prc")?), + }; + Some(json!({"opacity":opacity,"mode":mode})) }; mapped().map_or(Mapped::Unsupported { harmless: false }, |p| step("edit.fade", p)) } +/// A recorded Fade opacity less than 100 past either end wraps modulo 100 (150 plays as 50, -5 as +/// 95), as measured in the reference application. Values further out (200, -100, -105) were not +/// measured and keep the clamp to 0..=100. +fn fade_opacity(recorded: f64) -> f64 { + let rounded = recorded.round(); + let played = if rounded > 100.0 && rounded < 200.0 { + rounded - 100.0 + } else if rounded < 0.0 && rounded > -100.0 { + rounded + 100.0 + } else { + rounded.clamp(0.0, 100.0) + }; + // -0.4 rounds to -0.0; adding zero stores it as 0. + played + 0.0 +} + /// Native omitted Fade settings retain the command's 100% Normal behavior. pub(super) fn fade_to(_: &str, p: &Value) -> Option { if !params(p, &["opacity", "mode"]) { diff --git a/crates/engine/src/cmd/direct_select_history_names_tests.rs b/crates/engine/src/cmd/direct_select_history_names_tests.rs new file mode 100644 index 0000000000..09d9082862 --- /dev/null +++ b/crates/engine/src/cmd/direct_select_history_names_tests.rs @@ -0,0 +1,88 @@ +//! #13205: the History names of Direct Selection's path edits, as in the reference: "Drag Anchor +//! Point" for one anchor, "Drag Anchor Points" for two or more, "Drag Control Point" for a +//! handle and "Drag Segment" for a segment. The Convert Point and Curvature Pen names stay. + +use serde_json::{Value, json}; + +use crate::Session; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 200, "height": 200, "background": "white"})).unwrap(); + // Knot 1 at (120, 40) is smooth, with handles at (100, 40) and (140, 40). + let path = json!({"subpaths": [{"closed": true, "knots": [ + [40, 40], + {"anchor": [120, 40], "in": [100, 40], "out": [140, 40], "smooth": true}, + [120, 120], + [40, 120], + ]}]}); + s.execute("path.set", json!({"path": path})).unwrap(); + s +} + +/// The History step `id` with `params` adds. +fn step(s: &mut Session, id: &str, params: Value) -> String { + let n = s.active().unwrap().history.entries().len(); + s.execute(id, params).unwrap(); + let names = s.active().unwrap().history.entries(); + assert_eq!(names.len(), n + 1, "{id} adds one step: {names:?}"); + names[n].clone() +} + +#[test] +fn one_anchor_is_drag_anchor_point_and_more_are_drag_anchor_points() { + let mut s = session(); + let one = json!({"anchors": [[0, 2]], "move": [5, 0], "stepName": "Drag Anchor Point"}); + assert_eq!(step(&mut s, "path.moveAnchors", one), "Drag Anchor Point"); + assert_eq!(step(&mut s, "path.moveAnchors", json!({"anchors": [[0, 2], [0, 3]], "move": [5, 0]})), "Drag Anchor Points"); +} + +#[test] +fn a_handle_drag_is_drag_control_point() { + let mut s = session(); + for independent in [false, true] { + let p = json!({"subpath": 0, "knot": 1, "handle": "out", "to": [150, 60], "independent": independent}); + assert_eq!(step(&mut s, "path.moveHandle", p), "Drag Control Point", "independent: {independent}"); + } +} + +#[test] +fn a_segment_drag_stays_drag_segment() { + let mut s = session(); + assert_eq!(step(&mut s, "path.bendSegment", json!({"subpath": 0, "knot": 2, "move": [0, 10]})), "Drag Segment"); +} + +#[test] +fn other_tools_keep_their_names() { + let mut s = session(); + let corner = json!({"subpath": 0, "knot": 1, "handle": "out", "to": [150, 60], "independent": true, "stepName": "Corner Drag"}); + assert_eq!(step(&mut s, "path.moveHandle", corner), "Corner Drag"); + assert_eq!(step(&mut s, "path.convertPoint", json!({"subpath": 0, "knot": 2, "stepName": "Change Anchor Point"})), "Change Anchor Point"); + let whole = json!({"anchors": [[0, 0], [0, 1], [0, 2], [0, 3]], "move": [1, 1], "stepName": "Drag Path"}); + assert_eq!(step(&mut s, "path.moveAnchors", whole), "Drag Path"); + // The Curvature Pen's drag, and a one-anchor move that names no step (an arrow-key nudge). + assert_eq!(step(&mut s, "path.moveAnchors", json!({"anchors": [[0, 1]], "move": [0, 5], "curvature": true})), "Drag Anchor Points"); + assert_eq!(step(&mut s, "path.moveAnchors", json!({"anchors": [[0, 1]], "move": [1, 0]})), "Drag Anchor Points"); +} + +#[test] +fn an_unknown_step_name_is_refused_and_changes_nothing() { + let mut s = session(); + let before = (s.active().unwrap().doc.work_path.clone(), s.active().unwrap().history.entries()); + for bad in [json!("Drag Anchor Points"), json!("Drag Control Point"), json!("drag anchor point"), json!(""), json!(1), json!(["Drag Path"])] { + let e = s.execute("path.moveAnchors", json!({"anchors": [[0, 1]], "move": [1, 0], "stepName": bad})).unwrap_err().to_string(); + assert!(e.contains("\"Drag Path\" or \"Drag Anchor Point\""), "{bad}: {e}"); + let e = s.execute("path.moveHandle", json!({"subpath": 0, "knot": 1, "handle": "out", "to": [150, 60], "stepName": bad})).unwrap_err().to_string(); + assert!(e.contains("stepName") && e.contains("\"Corner Drag\""), "{bad}: {e}"); + } + assert_eq!((s.active().unwrap().doc.work_path.clone(), s.active().unwrap().history.entries()), before); +} + +#[test] +fn the_command_list_says_the_new_names() { + let specs = crate::command_specs(); + let spec = |id: &str| specs.iter().find(|c| c.id == id).unwrap(); + assert_eq!(spec("path.moveHandle").label, "Drag Control Point"); + assert!(spec("path.moveHandle").params.contains("default \"Drag Control Point\"")); + assert!(spec("path.moveAnchors").params.contains("\"Drag Anchor Point\" when it drags one anchor")); +} diff --git a/crates/engine/src/cmd/edit_menu_cmds.rs b/crates/engine/src/cmd/edit_menu_cmds.rs index e2502c72fa..b021ce0cc5 100644 --- a/crates/engine/src/cmd/edit_menu_cmds.rs +++ b/crates/engine/src/cmd/edit_menu_cmds.rs @@ -363,7 +363,7 @@ pub fn specs() -> Vec { "Fade…", ["Edit"], Some("Cmd+Shift+F"), - r##"{"opacity":0..100=100,"mode":"normal|multiply|screen|overlay|softLight|hardLight|darken|lighten|difference|color|luminosity"}"##, + r##"{"opacity":0..100=100,"mode":"normal|dissolve|darken|multiply|colorBurn|linearBurn|darkerColor|lighten|screen|colorDodge|linearDodge|lighterColor|overlay|softLight|hardLight|vividLight|linearLight|pinLight|hardMix|difference|exclusion|subtract|divide|hue|saturation|color|luminosity"}"##, can_fade, fade ), diff --git a/crates/engine/src/cmd/frame_cmds.rs b/crates/engine/src/cmd/frame_cmds.rs index e48f337246..9888b601dd 100644 --- a/crates/engine/src/cmd/frame_cmds.rs +++ b/crates/engine/src/cmd/frame_cmds.rs @@ -109,7 +109,9 @@ fn new_frame(s: &mut Session, p: &Value) -> Result { Some(child) } }; - let mut g = Layer::group(name.unwrap_or_else(|| doc.next_layer_name("Frame")), vec![]); + // A frame drawn around a layer is named after it ("Red Frame"); an empty one is "Frame N". + let name = name.unwrap_or_else(|| child.as_ref().map_or_else(|| doc.next_layer_name("Frame"), |c| format!("{} Frame", c.name))); + let mut g = Layer::group(name, vec![]); g.blend = BlendMode::Normal; g.frame = Some(Box::new(f)); refresh(&mut g); @@ -184,8 +186,14 @@ fn set(s: &mut Session, p: &Value) -> Result { if !["transform", "stroke", "name"].iter().any(|key| p.get(key).is_some()) { return Err(bad("supply transform, stroke or name")); } + // The Frame tool moves a frame as a "Move" step (#13880); every other change is "Frame Properties". + let step = match p.get("historyName") { + None | Some(Value::Null) => "Frame Properties", + Some(v) if v.as_str() == Some("Move") => "Move", + Some(_) => return Err(bad("`historyName` must be \"Move\" or null")), + }; let id = frame_id(s, p)?; - s.edit("Frame Properties", |doc, _| { + s.edit(step, |doc, _| { check_lock(doc, id)?; let l = doc.layer_mut(id).ok_or(EngineError::NoLayer(id))?; let f = l.frame.as_mut().ok_or_else(|| bad("not a frame"))?; @@ -366,7 +374,13 @@ pub fn specs() -> Vec { menu: &["Layer", "New"], ..spec("layer.new.frameFromLayers", "Frame from Layers", r#"{"layer":id?,"name":str?}"#, has_layer, frame_from_layers) }, - spec("layer.frame.set", "Frame Properties", r#"{"layer":id?,"transform":[a,b,c,d,x,y]?,"stroke":object|null?,"name":str?}"#, has_doc, set), + spec( + "layer.frame.set", + "Frame Properties", + r#"{"layer":id?,"transform":[a,b,c,d,x,y]?,"stroke":object|null?,"name":str?,"historyName":"Move"?}"#, + has_doc, + set, + ), CommandSpec { journal: false, ..spec("layer.frame.info", "Frame Info", r#"{"layer":id?}"#, has_doc, query) }, spec("layer.frame.convert", "Convert to Frame", r#"{"layer":id?,"name":str?,"width":px?,"height":px?}"#, has_doc, convert), spec( @@ -380,4 +394,6 @@ pub fn specs() -> Vec { ] } #[cfg(test)] +mod content_name_tests; +#[cfg(test)] mod tests; diff --git a/crates/engine/src/cmd/frame_cmds/content_name_tests.rs b/crates/engine/src/cmd/frame_cmds/content_name_tests.rs new file mode 100644 index 0000000000..70d28d988a --- /dev/null +++ b/crates/engine/src/cmd/frame_cmds/content_name_tests.rs @@ -0,0 +1,72 @@ +//! #13862: a frame made around a layer is named " Frame"; an empty frame keeps +//! "Frame N", and an explicit `name` wins over both. +use super::*; +use photocraft_doc::Layer; +use photocraft_geom::Rect; + +/// The issue's document: 600 x 400 px with a white Background, pixel layers Red (100 x 80 at +/// 50,50) and Blue, and an empty pixel layer on top. +fn session() -> (Session, LayerId, LayerId) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 600, "height": 400})).unwrap(); + let (red, blue) = s + .edit("setup", |doc, _| { + let fmt = doc.pixel_format(); + let mut red = Layer::raster("Red", fmt); + red.surface_mut().unwrap().fill_rect(Rect::new(50, 50, 150, 130), &photocraft_raster::from_rgba(&fmt, [1.0, 0.0, 0.0, 1.0])); + let mut blue = Layer::raster("Blue", fmt); + blue.surface_mut().unwrap().fill_rect(Rect::new(300, 200, 400, 280), &photocraft_raster::from_rgba(&fmt, [0.0, 0.0, 1.0, 1.0])); + let (r, b) = (red.id, blue.id); + doc.layers.push(red); + doc.layers.push(blue); + doc.layers.push(Layer::raster("Layer 1", fmt)); + Ok((r, b)) + }) + .unwrap(); + (s, red, blue) +} + +fn frame(s: &mut Session, params: Value) -> (String, Vec) { + let r = s.execute("layer.new.frame", params).unwrap(); + let g = s.active().unwrap().doc.layer(LayerId(r["layer"].as_u64().unwrap())).unwrap(); + (g.name.clone(), g.children().unwrap().iter().map(|l| l.name.clone()).collect()) +} + +#[test] +fn a_frame_around_a_layer_is_named_after_it() { + let (mut s, red, blue) = session(); + let (name, content) = frame(&mut s, json!({"x": 40, "y": 40, "width": 120, "height": 100, "layer": red.0})); + assert_eq!((name.as_str(), content), ("Red Frame", vec!["Red".to_string()]), "the content layer keeps its own name"); + let (name, _) = frame(&mut s, json!({"x": 290, "y": 190, "width": 120, "height": 100, "shape": "ellipse", "layer": blue.0})); + assert_eq!(name, "Blue Frame"); +} + +#[test] +fn empty_frames_keep_the_frame_counter() { + let (mut s, _, _) = session(); + let (first, content) = frame(&mut s, json!({"x": 10, "y": 10, "width": 30, "height": 30})); + assert_eq!((first.as_str(), content.len()), ("Frame 1", 0)); + let (second, _) = frame(&mut s, json!({"x": 500, "y": 300, "width": 30, "height": 30})); + assert_eq!(second, "Frame 2"); +} + +#[test] +fn an_explicit_name_wins_over_the_content_name() { + let (mut s, red, _) = session(); + let (name, content) = frame(&mut s, json!({"x": 40, "y": 40, "width": 120, "height": 100, "layer": red.0, "name": "Hero"})); + assert_eq!((name.as_str(), content), ("Hero", vec!["Red".to_string()])); + let (name, _) = frame(&mut s, json!({"x": 10, "y": 10, "width": 30, "height": 30, "name": "Empty"})); + assert_eq!(name, "Empty"); +} + +#[test] +fn undo_and_redo_keep_the_content_name() { + let (mut s, red, _) = session(); + let (name, _) = frame(&mut s, json!({"x": 40, "y": 40, "width": 120, "height": 100, "layer": red.0})); + assert_eq!(name, "Red Frame"); + assert!(s.undo()); + let names = |s: &Session| s.active().unwrap().doc.walk().into_iter().map(|(_, _, l)| l.name.clone()).collect::>(); + assert!(!names(&s).contains(&"Red Frame".to_string()) && names(&s).contains(&"Red".to_string()), "undo takes the frame away and gives Red back"); + assert!(s.redo()); + assert!(names(&s).contains(&"Red Frame".to_string())); +} diff --git a/crates/engine/src/cmd/path_edit_cmds.rs b/crates/engine/src/cmd/path_edit_cmds.rs index 1312347662..7a8a2b3de5 100644 --- a/crates/engine/src/cmd/path_edit_cmds.rs +++ b/crates/engine/src/cmd/path_edit_cmds.rs @@ -46,16 +46,22 @@ fn knot(cmd: &str, p: &Value) -> Result<[usize; 2]> { Ok([index(cmd, p, "subpath")?, index(cmd, p, "knot")?]) } -/// The History step name: `default`, or `named` when `stepName` asks for it (the Convert Point -/// tool names its steps as the reference does, #12736). Any other value is refused. -fn step_name(cmd: &str, p: &Value, default: &'static str, named: &'static str) -> Result<&'static str> { +/// The History step name: `default`, or one of `named` when `stepName` asks for it (the Convert +/// Point tool names its steps as the reference does, #12736; Direct Selection names a one-anchor +/// drag, #13205). Any other value is refused. +fn step_name(cmd: &str, p: &Value, default: &'static str, named: &[&'static str]) -> Result<&'static str> { match p.get("stepName") { None | Some(Value::Null) => Ok(default), - Some(Value::String(n)) if n == named => Ok(named), - Some(_) => Err(bad(cmd, format!("`stepName` must be \"{named}\""))), + Some(Value::String(n)) => named.iter().copied().find(|m| *m == n.as_str()).ok_or_else(|| bad(cmd, step_names_error(named))), + Some(_) => Err(bad(cmd, step_names_error(named))), } } +fn step_names_error(named: &[&str]) -> String { + let names: Vec = named.iter().map(|n| format!("\"{n}\"")).collect(); + format!("`stepName` must be {}", names.join(" or ")) +} + /// Applies `f` to the targeted path in one undoable step labelled `label`. fn edit_path(s: &mut Session, cmd: &str, p: &Value, label: &str, f: impl FnOnce(&mut Path) -> std::result::Result<(), String>) -> Result { // A malformed target is an error, never a silent edit of the Work Path or the active layer. @@ -116,7 +122,7 @@ fn move_anchors(s: &mut Session, p: &Value) -> Result { }) .collect::>()?; let d = offset(CMD, p)?; - let label = step_name(CMD, p, "Drag Anchor Points", "Drag Path")?; + let label = step_name(CMD, p, "Drag Anchor Points", &["Drag Path", "Drag Anchor Point"])?; if p.get("curvature").and_then(Value::as_bool).unwrap_or(false) { return edit_path(s, CMD, p, label, |path| edit::move_anchors_curvature(path, &anchors, d)); } @@ -129,7 +135,7 @@ fn move_handle(s: &mut Session, p: &Value) -> Result { let h = p.get("handle").and_then(Value::as_str).and_then(Handle::parse).ok_or_else(|| bad(CMD, "`handle` must be \"in\" or \"out\""))?; let to = point(CMD, p, "to")?.ok_or_else(|| bad(CMD, "missing `to`"))?; let independent = p.get("independent").and_then(Value::as_bool).unwrap_or(false); - let label = step_name(CMD, p, "Drag Direction Point", "Corner Drag")?; + let label = step_name(CMD, p, "Drag Control Point", &["Corner Drag"])?; edit_path(s, CMD, p, label, |path| edit::move_handle(path, k, h, to, independent)) } @@ -147,7 +153,7 @@ fn bend_segment(s: &mut Session, p: &Value) -> Result { fn convert_point(s: &mut Session, p: &Value) -> Result { const CMD: &str = "path.convertPoint"; let k = knot(CMD, p)?; - let label = step_name(CMD, p, "Convert Point", "Change Anchor Point")?; + let label = step_name(CMD, p, "Convert Point", &["Change Anchor Point"])?; if p.get("curvature").and_then(Value::as_bool).unwrap_or(false) { return edit_path(s, CMD, p, label, |path| edit::toggle_curvature_point(path, k)); } @@ -284,11 +290,11 @@ pub fn specs() -> Vec { journal: true, }; vec![ - spec("path.moveAnchors", "Drag Anchor Points", r#""anchors":[[subpath,knot],…],"move":[dx,dy],"curvature":bool=false (anchors move with their handles; Direct Selection drag. curvature = the Curvature Pen's drag: every smooth knot of the touched subpaths gets its handles recomputed so the curve flows through the anchors),"stepName":"Drag Path"? (History step name; the Convert Point tool sends it when it drags a whole path; default "Drag Anchor Points"; any other value is refused)"#.into(), move_anchors), + spec("path.moveAnchors", "Drag Anchor Points", r#""anchors":[[subpath,knot],…],"move":[dx,dy],"curvature":bool=false (anchors move with their handles; Direct Selection drag. curvature = the Curvature Pen's drag: every smooth knot of the touched subpaths gets its handles recomputed so the curve flows through the anchors),"stepName":"Drag Path"|"Drag Anchor Point"? (History step name; the Convert Point tool sends "Drag Path" when it drags a whole path, Direct Selection "Drag Anchor Point" when it drags one anchor; default "Drag Anchor Points"; any other value is refused)"#.into(), move_anchors), spec( "path.moveHandle", - "Drag Direction Point", - r#""subpath":i,"knot":j,"handle":"in|out","to":[x,y],"independent":bool=false (a smooth point turns its other handle to stay collinear; independent = ⌥ / Convert Point, makes a corner),"stepName":"Corner Drag"? (History step name; the Convert Point tool sends it; default "Drag Direction Point"; any other value is refused)"#.into(), + "Drag Control Point", + r#""subpath":i,"knot":j,"handle":"in|out","to":[x,y],"independent":bool=false (a smooth point turns its other handle to stay collinear; independent = ⌥ / Convert Point, makes a corner),"stepName":"Corner Drag"? (History step name; the Convert Point tool sends it; default "Drag Control Point"; any other value is refused)"#.into(), move_handle, ), spec( @@ -797,3 +803,7 @@ mod tests { #[cfg(test)] #[path = "path_delete_last_anchor_tests.rs"] mod path_delete_last_anchor_tests; + +#[cfg(test)] +#[path = "direct_select_history_names_tests.rs"] +mod direct_select_history_names_tests; diff --git a/crates/engine/src/cmd/web_cmds/optimizer.rs b/crates/engine/src/cmd/web_cmds/optimizer.rs index 2186f3b70a..73ac0325f8 100644 --- a/crates/engine/src/cmd/web_cmds/optimizer.rs +++ b/crates/engine/src/cmd/web_cmds/optimizer.rs @@ -155,6 +155,9 @@ pub fn optimize( if preview { look = rgba(&data, layout); } + // The profile only with Embed Color Profile on, as the WebP and JPEG branches do: Quick + // Export, which never sets it, writes no iCCP chunk (#13798). + let icc = icc.filter(|_| st.embed_icc); let img = photocraft_codecs::Image::from_u8(ww, hh, layout, data).map_err(e)?.with_icc(icc.map(<[u8]>::to_vec)).with_meta(meta()); let opts = photocraft_codecs::EncodeOptions { png_interlaced: st.interlaced, @@ -428,3 +431,7 @@ fn quantize_rows(px: &mut [[f32; 4]], w: usize, pal: &[[u8; 3]], dither: Dither, #[cfg(target_arch = "wasm32")] quantize_band(px, w, 0, pal, dither, amount, t) } + +#[cfg(test)] +#[path = "png_embed_icc_tests.rs"] +mod png_embed_icc_tests; diff --git a/crates/engine/src/cmd/web_cmds/png_embed_icc_tests.rs b/crates/engine/src/cmd/web_cmds/png_embed_icc_tests.rs new file mode 100644 index 0000000000..f295d8409a --- /dev/null +++ b/crates/engine/src/cmd/web_cmds/png_embed_icc_tests.rs @@ -0,0 +1,67 @@ +//! #13798: a Quick Export PNG carries no ICC profile, with Convert to sRGB on or off, and Save for +//! Web's PNG-24 embeds one only with Embed Color Profile on. The pixels are as before. + +use serde_json::json; + +use crate::Session; + +fn tmp(name: &str) -> String { + let d = std::env::temp_dir().join(format!("photocraft-png-icc-{}-{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 red document with a wide-gamut profile (Adobe RGB) assigned. +fn tagged() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 20, "height": 10, "background": "#c81e1e"})).unwrap(); + s.execute("edit.assignProfile", json!({"profile": "adobe-rgb-compat"})).unwrap(); + assert!(s.active().unwrap().doc.icc_profile.is_some(), "the document has a profile"); + s +} + +/// The PNG's chunk types, in order. +fn chunks(bytes: &[u8]) -> Vec { + assert_eq!(bytes.get(..8), Some(b"\x89PNG\r\n\x1a\n".as_slice()), "a PNG"); + let mut out = Vec::new(); + let mut at = 8; + while let Some(head) = bytes.get(at..at + 8) { + let len = u32::from_be_bytes([head[0], head[1], head[2], head[3]]) as usize; + out.push(String::from_utf8_lossy(&head[4..8]).into_owned()); + at += 12 + len; + } + out +} + +fn pixels(path: &str) -> Vec { + let img = photocraft_codecs::decode(&std::fs::read(path).unwrap()).unwrap(); + img.convert(photocraft_codecs::ChannelLayout::Rgba, photocraft_codecs::SampleType::U8).data().to_vec() +} + +#[test] +fn a_quick_export_png_embeds_no_profile_with_convert_to_srgb_on_or_off() { + let dir = tmp("quick"); + let mut s = tagged(); + for convert in [true, false] { + s.execute("file.export.exportPreferences", json!({"quickExportFormat": "png", "metadata": "none", "convertToSrgb": convert})).unwrap(); + let path = format!("{dir}/convert-{convert}.png"); + s.execute("file.export.quickExport", json!({"path": path})).unwrap(); + let found = chunks(&std::fs::read(&path).unwrap()); + assert!(!found.iter().any(|c| c == "iCCP"), "convert {convert}: {found:?}"); + assert!(photocraft_codecs::decode(&std::fs::read(&path).unwrap()).unwrap().icc.is_none(), "convert {convert}"); + } + s.execute("prefs.reset", json!({"path": "export"})).unwrap(); +} + +#[test] +fn save_for_web_png24_embeds_the_profile_only_when_asked_and_keeps_its_pixels() { + let dir = tmp("sfw"); + let mut s = tagged(); + let (on, off) = (format!("{dir}/on.png"), format!("{dir}/off.png")); + s.execute("file.export.saveForWebLegacy", json!({"format": "png24", "embedIcc": true, "path": on})).unwrap(); + s.execute("file.export.saveForWebLegacy", json!({"format": "png24", "embedIcc": false, "path": off})).unwrap(); + assert!(chunks(&std::fs::read(&on).unwrap()).iter().any(|c| c == "iCCP"), "Embed Color Profile on"); + assert!(!chunks(&std::fs::read(&off).unwrap()).iter().any(|c| c == "iCCP"), "Embed Color Profile off"); + assert_eq!(pixels(&on), pixels(&off), "only the profile differs"); +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index 85154567db..e6207b5cad 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -635,6 +635,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { let mut close_clicked = false; let mut sizing = false; let mut processor_alert = None; + let mut fit_image_alert = None; let area = match start { Some(offset) => egui::Modal::default_area(id).anchor(egui::Align2::LEFT_TOP, offset), None => egui::Modal::default_area(id), @@ -729,8 +730,10 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { crate::field_tab::begin(ui.ctx()); if image_processor_ui::owns(&fields) { processor_alert = image_processor_ui::body(ui, &mut fields); - } else if let Some(done) = dialog_body(app, ui, &d, &mut fields, id, interactive) { - outcome = Some(done); + } else if fit_image_range::owns(&fields) { + fit_image_alert = fit_image_range::body(ui, &mut fields); + } else { + outcome = dialog_body(app, ui, &d, &mut fields, id, interactive); } crate::field_tab::end(ui.ctx(), tab); if let Some(Value::String(key)) = fields.remove(BROWSE_FIELD) { @@ -797,6 +800,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { outcome = Some(false); } outcome = image_processor_ui::finish(&mut app.ui, interactive, processor_alert, outcome); + outcome = fit_image_range::finish(&mut app.ui, interactive, fit_image_alert, outcome); if let Some(dm) = app.ui.dialog_mut(d.id) { dm.fields = fields; } @@ -1178,6 +1182,7 @@ fn confirm_command_more(app: &mut PhotocraftApp, d: Dialog) -> Result Result { confirm_preflight(app, id)?; image_processor_ui::preflight(&mut app.ui, id)?; + fit_image_range::preflight(&mut app.ui, id)?; let d = app.ui.close_dialog(id).ok_or_else(|| format!("no dialog {id}"))?; match d.kind { DialogKind::NewDocument => { @@ -1319,12 +1324,16 @@ pub mod duplicate_layer_ui; pub mod edit_history; pub mod equalize_ui; pub mod export_dialog; +pub(crate) mod fade_modes; pub mod file_ui; pub mod fill_ui; pub mod filter_dialog; pub(super) mod filter_preview_ui; #[cfg(not(target_arch = "wasm32"))] pub(super) mod filter_preview_worker; +mod fit_image_range; +#[cfg(test)] +mod fit_image_range_tests; pub mod gallery_ui; pub(crate) mod guide_edit; pub mod guide_layout_ui; diff --git a/crates/ui-egui/src/dialogs/export_dialog.rs b/crates/ui-egui/src/dialogs/export_dialog.rs index 75235cf362..3da56a5860 100644 --- a/crates/ui-egui/src/dialogs/export_dialog.rs +++ b/crates/ui-egui/src/dialogs/export_dialog.rs @@ -482,6 +482,9 @@ fn settings(f: &Map) -> ExportSettings { // Metadata: None drops EXIF and resolution as well as XMP. A missing key keeps them, // which is what Export As wrote before the choice existed. embed_metadata: metadata != "none", + // Export As's JPGs are progressive (SOF2) in the reference application, measured at its + // default quality; the scan layout is one setting for the whole dialog. + jpeg_format: photocraft_codecs::JpegFormat::Progressive, ..Default::default() } } @@ -1185,6 +1188,9 @@ mod tests; #[cfg(test)] mod enter_key_tests; +#[cfg(test)] +mod jpg_progressive_tests; + #[cfg(all(test, unix))] mod batch_name_tests { use super::*; diff --git a/crates/ui-egui/src/dialogs/export_dialog/jpg_progressive_tests.rs b/crates/ui-egui/src/dialogs/export_dialog/jpg_progressive_tests.rs new file mode 100644 index 0000000000..1ec9a486fa --- /dev/null +++ b/crates/ui-egui/src/dialogs/export_dialog/jpg_progressive_tests.rs @@ -0,0 +1,82 @@ +//! #13724: Export As writes JPGs with a progressive scan layout (SOF2) at every quality. + +use super::*; + +/// A 32 x 24 document of solid colour blocks, so JPEG error stays small away from the edges. +fn blocks_doc() -> Document { + use photocraft_doc::{Color, ColorMode, SampleType, Size}; + use photocraft_geom::Rect; + let mut doc = Document::with_background("blocks", Size::new(32, 24), ColorMode::Rgb, SampleType::U8, Color::WHITE); + let surf = doc.layers[0].surface_mut().unwrap(); + surf.fill_rect(Rect::new(0, 0, 16, 16), &[1.0, 0.0, 0.0, 1.0]); + surf.fill_rect(Rect::new(16, 0, 32, 16), &[0.0, 1.0, 0.0, 1.0]); + surf.fill_rect(Rect::new(0, 16, 16, 24), &[0.0, 0.0, 1.0, 1.0]); + doc +} + +fn export_jpg(doc: &Document, quality: u32) -> Vec { + let f = json!({"format": "jpg", "quality": quality, "scale": 100, "embedProfile": false}).as_object().unwrap().clone(); + let out = super::export_document(doc, &f, None, &photocraft_engine::color_cmds::document_profile(doc)).unwrap(); + photocraft_io::export(&out, "x.jpg", &settings(&f).io_options()).unwrap().bytes +} + +/// The main frame's marker and component sampling factors, skipping whole segments. +fn frame(bytes: &[u8]) -> (u8, [u8; 3]) { + assert_eq!(bytes.get(..2), Some([0xff, 0xd8].as_slice()), "JPEG SOI"); + let mut offset = 2; + loop { + assert_eq!(bytes.get(offset), Some(&0xff), "marker prefix"); + while bytes.get(offset) == Some(&0xff) { + offset += 1; + } + let marker = *bytes.get(offset).expect("marker"); + offset += 1; + assert!(!matches!(marker, 0xd9 | 0xda), "no frame before scan"); + let len = usize::from(u16::from_be_bytes([bytes[offset], bytes[offset + 1]])); + let segment = &bytes[offset + 2..offset + len]; + if matches!(marker, 0xc0..=0xc3) { + assert_eq!(segment[5], 3, "three components"); + return (marker, std::array::from_fn(|i| segment[6 + 3 * i + 1])); + } + offset += len; + } +} + +#[test] +fn export_as_jpg_is_progressive_at_every_quality() { + let doc = blocks_doc(); + for (quality, sampling) in [(85, [0x11; 3]), (20, [0x22, 0x11, 0x11])] { + let bytes = export_jpg(&doc, quality); + let (marker, factors) = frame(&bytes); + assert_eq!(marker, 0xc2, "quality {quality}: SOF2 (progressive), not SOF0"); + assert_eq!(factors, sampling, "quality {quality}: chroma sampling"); + } +} + +#[test] +fn progressive_export_decodes_back_to_the_source() { + let doc = blocks_doc(); + // Every pixel within 2 levels at the dialog default. Quality 20 quantises saturated flat + // colours and their edges coarsely, so there only the block centres are held to the colour. + for (quality, tolerance) in [(85, 2), (20, 64)] { + let decoded = + photocraft_codecs::decode(&export_jpg(&doc, quality)).unwrap().convert(photocraft_codecs::ChannelLayout::Rgb, photocraft_codecs::SampleType::U8); + assert_eq!(decoded.dimensions(), (32, 24)); + for (i, px) in decoded.data().as_chunks::<3>().0.iter().enumerate() { + let (x, y) = (i % 32, i / 32); + if quality == 20 && !matches!((x, y), (7 | 23, 7) | (7, 20) | (23, 20)) { + continue; + } + let want: [u8; 3] = match (x < 16, y < 16) { + (true, true) => [255, 0, 0], + (false, true) => [0, 255, 0], + (true, false) => [0, 0, 255], + (false, false) => [255, 255, 255], + }; + // The block interiors; the colour edges fall on 16 x 16 MCU boundaries. + for (a, b) in px.iter().zip(want) { + assert!(a.abs_diff(b) <= tolerance, "quality {quality}, pixel ({x}, {y}): {px:?} vs {want:?}"); + } + } + } +} diff --git a/crates/ui-egui/src/dialogs/fade_mode_list_tests.rs b/crates/ui-egui/src/dialogs/fade_mode_list_tests.rs new file mode 100644 index 0000000000..ceba62232f --- /dev/null +++ b/crates/ui-egui/src/dialogs/fade_mode_list_tests.rs @@ -0,0 +1,168 @@ +//! #13806: Edit › Fade's Mode list holds the 27 layer blend modes in the reference order, in six +//! groups, and greys the modes a Grayscale 8-bit, Lab 8-bit or RGB 32-bit document can't fade with. + +use photocraft_color::{BlendMode, ColorMode, SampleType}; +use serde_json::{Value, json}; + +use super::{COMMAND, greyed, step_past}; +use crate::PhotocraftApp; +use crate::dialogs::dialog_blend_ui::mode_key; +use crate::filter_dialog::{Kind, parse_spec}; + +/// The reference application's Fade Mode list, a group per row. +const GROUPS: [&[&str]; 6] = [ + &["Normal", "Dissolve"], + &["Darken", "Multiply", "Color Burn", "Linear Burn", "Darker Color"], + &["Lighten", "Screen", "Color Dodge", "Linear Dodge (Add)", "Lighter Color"], + &["Overlay", "Soft Light", "Hard Light", "Vivid Light", "Linear Light", "Pin Light", "Hard Mix"], + &["Difference", "Exclusion", "Subtract", "Divide"], + &["Hue", "Saturation", "Color", "Luminosity"], +]; + +fn app(mode: &str, depth: u32) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 16, "height": 12, "mode": mode, "depth": depth})).unwrap(); + app +} + +fn labels(modes: &[BlendMode]) -> Vec<&'static str> { + modes.iter().map(|m| m.label()).collect() +} + +fn mode_options() -> Vec { + let spec = photocraft_engine::commands::find(COMMAND).unwrap(); + let p = parse_spec(spec.params).into_iter().find(|p| p.key == "mode").unwrap(); + let Kind::Choice { options, .. } = p.kind else { panic!("mode is not a choice") }; + options +} + +#[test] +fn the_list_is_the_27_modes_in_six_groups() { + let shown = labels(&BlendMode::LAYER_MODES); + assert_eq!(shown, GROUPS.concat()); + // A line above the first mode of every group but the first. + let mut groups: Vec> = Vec::new(); + for m in BlendMode::LAYER_MODES { + match groups.last_mut() { + Some(g) if !crate::panels::starts_blend_group(m) => g.push(m.label()), + _ => groups.push(vec![m.label()]), + } + } + assert_eq!(groups, GROUPS.map(<[&str]>::to_vec)); +} + +#[test] +fn the_params_doc_lists_all_27_modes_and_the_old_names_still_work() { + let options = mode_options(); + let modes: Vec> = options.iter().map(|o| photocraft_engine::commands::blend_from_str(o)).collect(); + assert_eq!(modes, BlendMode::LAYER_MODES.map(Some).to_vec()); + assert_eq!(options, BlendMode::LAYER_MODES.map(mode_key).to_vec(), "the keys the dialog writes"); + for old in ["normal", "multiply", "screen", "overlay", "softLight", "hardLight", "darken", "lighten", "difference", "color", "luminosity"] { + assert!(options.iter().any(|o| o == old), "{old} is still listed"); + } +} + +#[test] +fn every_listed_mode_fades() { + for key in mode_options() { + let mut s = photocraft_engine::Session::new(); + s.execute("file.new", json!({"width": 8, "height": 8, "background": "white"})).unwrap(); + s.execute("edit.fill", json!({"color": "#336699"})).unwrap(); + let out = s.execute(COMMAND, json!({"opacity": 50, "mode": key})).unwrap(); + assert_eq!(out["mode"], json!(photocraft_engine::commands::blend_from_str(&key).unwrap().label()), "{key}"); + } +} + +#[test] +fn greyed_modes_follow_the_measured_colour_modes_and_depths() { + use SampleType::*; + assert_eq!(labels(greyed(ColorMode::Grayscale, U8)), ["Darker Color", "Lighter Color", "Hue", "Saturation", "Color", "Luminosity"]); + assert_eq!(labels(greyed(ColorMode::Lab, U8)), ["Darken", "Color Burn", "Lighten", "Color Dodge", "Difference", "Exclusion", "Subtract", "Divide"]); + assert_eq!( + labels(greyed(ColorMode::Rgb, F32)), + [ + "Color Burn", + "Linear Burn", + "Screen", + "Color Dodge", + "Overlay", + "Soft Light", + "Hard Light", + "Vivid Light", + "Linear Light", + "Pin Light", + "Hard Mix", + "Exclusion" + ] + ); + // Measured with none greyed, and the cases not measured keep the old list (none greyed). + for (mode, depth) in + [(ColorMode::Rgb, U16), (ColorMode::Cmyk, U8), (ColorMode::Rgb, U8), (ColorMode::Grayscale, U16), (ColorMode::Lab, U16), (ColorMode::Cmyk, U16)] + { + assert!(greyed(mode, depth).is_empty(), "{mode:?} {depth:?}"); + } +} + +#[test] +fn opening_the_dialog_notes_the_documents_greyed_modes() { + for (mode, depth, want) in [("lab", 8, greyed(ColorMode::Lab, SampleType::U8)), ("rgb", 32, greyed(ColorMode::Rgb, SampleType::F32)), ("rgb", 16, &[][..])] + { + let mut app = app(mode, depth); + let id = crate::filter_dialog::open(&mut app, COMMAND).unwrap(); + let fields = &app.ui.dialog_mut(id).unwrap().fields; + let noted: Vec<&str> = fields["__fadeGreyed"].as_array().unwrap().iter().filter_map(Value::as_str).collect(); + assert_eq!(noted, want.iter().map(|m| mode_key(*m)).collect::>(), "{mode} {depth}"); + assert_eq!(fields["mode"], json!("normal")); + } +} + +#[test] +fn a_remembered_mode_the_document_greys_opens_as_normal() { + let mut app = app("lab", 8); + app.session.prefs.edit(|p| p.dialogs.insert(COMMAND.into(), json!({"mode": "darken", "opacity": 40}))); + let id = crate::filter_dialog::open(&mut app, COMMAND).unwrap(); + let fields = &app.ui.dialog_mut(id).unwrap().fields; + assert_eq!((fields["mode"].clone(), fields["opacity"].clone()), (json!("normal"), json!(40))); + + // In a document that can fade with it, the remembered mode stays. + let mut app = self::app("rgb", 8); + app.session.prefs.edit(|p| p.dialogs.insert(COMMAND.into(), json!({"mode": "darken"}))); + let id = crate::filter_dialog::open(&mut app, COMMAND).unwrap(); + assert_eq!(app.ui.dialog_mut(id).unwrap().fields["mode"], json!("darken")); +} + +#[test] +fn the_keys_step_past_greyed_modes() { + use BlendMode::*; + let lab = greyed(ColorMode::Lab, SampleType::U8); + assert_eq!(step_past(Normal, Multiply, lab), Multiply, "not greyed"); + // Down from Dissolve lands on Darken, greyed: Multiply is the next one. + assert_eq!(step_past(Dissolve, Darken, lab), Multiply); + // Up from Multiply: Dissolve. + assert_eq!(step_past(Multiply, Darken, lab), Dissolve); + // Down from Hard Mix past Difference, Exclusion, Subtract and Divide. + assert_eq!(step_past(HardMix, Difference, lab), Hue); + // Nothing open past it: stay. + let all = BlendMode::LAYER_MODES; + assert_eq!(step_past(Normal, Dissolve, &all[1..]), Normal); +} + +#[test] +fn the_row_keeps_an_open_mode_and_writes_its_key() { + let ctx = egui::Context::default(); + PhotocraftApp::setup_context(&ctx, crate::theme::ThemeKind::ALL[0]); + let mut app = app("rgb", 32); + let id = crate::filter_dialog::open(&mut app, COMMAND).unwrap(); + let mut fields = app.ui.dialog_mut(id).unwrap().fields.clone(); + fields.insert("mode".into(), json!("Linear Dodge (Add)")); + ctx.run_ui(egui::RawInput::default(), |ui| crate::filter_dialog::body(ui, &mut fields)).drop_without_applying_deltas(); + assert_eq!(fields["mode"], json!("linearDodge")); + // A greyed mode an agent wrote isn't chosen from the list: the row leaves it to the command. + fields.insert("mode".into(), json!("screen")); + ctx.run_ui(egui::RawInput::default(), |ui| crate::filter_dialog::body(ui, &mut fields)).drop_without_applying_deltas(); + assert_eq!(fields["mode"], json!("screen")); + // Nor is a mode no list names: OK reports it instead of fading in Normal. + fields.insert("mode".into(), json!("nonsense")); + ctx.run_ui(egui::RawInput::default(), |ui| crate::filter_dialog::body(ui, &mut fields)).drop_without_applying_deltas(); + assert_eq!(fields["mode"], json!("nonsense")); +} diff --git a/crates/ui-egui/src/dialogs/fade_modes.rs b/crates/ui-egui/src/dialogs/fade_modes.rs new file mode 100644 index 0000000000..0caeefae46 --- /dev/null +++ b/crates/ui-egui/src/dialogs/fade_modes.rs @@ -0,0 +1,100 @@ +//! Edit › Fade's Mode list (#13806): the 27 layer blend modes in the reference application's order +//! and groups, a line between the groups, with the modes the document's colour mode and depth can't +//! fade with greyed (listed, never chosen). + +use photocraft_color::{BlendMode, ColorMode, SampleType}; +use serde_json::{Map, Value, json}; + +use super::dialog_blend_ui::mode_key; +use crate::PhotocraftApp; + +pub(crate) const COMMAND: &str = "edit.fade"; +/// The `mode` keys greyed for the document the dialog opened on. +const GREYED: &str = "__fadeGreyed"; + +/// The modes the reference application greys in its Fade dialog for a document of `mode` at +/// `depth`. Combinations it wasn't measured in (Grayscale 16/32, Lab 16, CMYK 16, Multichannel, +/// Duotone…) grey none, as before. +pub(crate) fn greyed(mode: ColorMode, depth: SampleType) -> &'static [BlendMode] { + use BlendMode::*; + match (mode, depth) { + (ColorMode::Grayscale, SampleType::U8) => &[DarkerColor, LighterColor, Hue, Saturation, Color, Luminosity], + (ColorMode::Lab, SampleType::U8) => &[Darken, ColorBurn, Lighten, ColorDodge, Difference, Exclusion, Subtract, Divide], + (ColorMode::Rgb, SampleType::F32) => { + &[ColorBurn, LinearBurn, Screen, ColorDodge, Overlay, SoftLight, HardLight, VividLight, LinearLight, PinLight, HardMix, Exclusion] + } + _ => &[], + } +} + +/// Opening (and Alt+Reset): note the active document's greyed modes for the list. A remembered +/// mode this document greys starts the dialog at Normal instead, since it can't be chosen. +pub(crate) fn defaults(app: &PhotocraftApp, fields: &mut Map) { + let greyed = app.session.active().map_or(&[][..], |st| greyed(st.doc.mode, st.doc.depth)); + if mode_of(fields).is_some_and(|m| greyed.contains(&m)) { + fields.insert("mode".into(), json!(mode_key(BlendMode::Normal))); + } + fields.insert(GREYED.into(), json!(greyed.iter().map(|m| mode_key(*m)).collect::>())); +} + +fn mode_of(fields: &Map) -> Option { + fields.get("mode").and_then(Value::as_str).and_then(photocraft_engine::commands::blend_from_str) +} + +fn greyed_of(fields: &Map) -> Vec { + fields + .get(GREYED) + .and_then(Value::as_array) + .into_iter() + .flatten() + .filter_map(Value::as_str) + .filter_map(photocraft_engine::commands::blend_from_str) + .collect() +} + +/// The mode to keep after the list's keys or type-ahead moved from `from` to `to`: `to` unless it +/// is greyed, else the next mode past it the same way that isn't, else `from`. A greyed mode the +/// list didn't move to (written by an agent) stays: the command decides about it. +pub(crate) fn step_past(from: BlendMode, to: BlendMode, greyed: &[BlendMode]) -> BlendMode { + if to == from || !greyed.contains(&to) { + return to; + } + let list = BlendMode::LAYER_MODES; + let at = |m: BlendMode| list.iter().position(|l| *l == m); + let (Some(a), Some(b)) = (at(from), at(to)) else { return from }; + let open = |m: &&BlendMode| !greyed.contains(m); + let next = if b < a { list.get(..b).and_then(|l| l.iter().rev().find(open)) } else { list.get(b + 1..).and_then(|l| l.iter().find(open)) }; + next.copied().unwrap_or(from) +} + +/// The Mode row of the Fade dialog, its label `label` in the schema dialog's style. +pub(crate) fn row(ui: &mut egui::Ui, f: &mut Map, label: &str) { + let t = crate::theme::Tokens::get(ui.ctx()); + let greyed = greyed_of(f); + let known = mode_of(f); + let before = known.unwrap_or(BlendMode::Normal); + let mut mode = before; + let opts: Vec<(BlendMode, &str)> = BlendMode::LAYER_MODES.iter().map(|m| (*m, m.label())).collect(); + ui.horizontal(|ui| { + ui.label(egui::RichText::new(label).color(t.text_dim)); + crate::widgets::dropdown_wheel_grouped_enabled( + ui, + "flt-edit.fade-mode", + label, + &mut mode, + &opts, + 170.0, + |m| crate::panels::starts_blend_group(*m), + |m| !greyed.contains(m), + ); + }); + let mode = step_past(before, mode, &greyed); + // A mode no list names (an agent's typo) stays until one is picked: the command reports it. + if known.is_some() || mode != before { + f.insert("mode".into(), json!(mode_key(mode))); + } +} + +#[cfg(test)] +#[path = "fade_mode_list_tests.rs"] +mod tests; diff --git a/crates/ui-egui/src/dialogs/filter_dialog.rs b/crates/ui-egui/src/dialogs/filter_dialog.rs index 4cf9edc9ca..e69ba917e1 100644 --- a/crates/ui-egui/src/dialogs/filter_dialog.rs +++ b/crates/ui-egui/src/dialogs/filter_dialog.rs @@ -469,6 +469,9 @@ fn apply_command_defaults(app: &PhotocraftApp, command: &str, fields: &mut Map) { indexed_matte_row(ui, f); continue; } + if cmd == super::fade_modes::COMMAND && p.key == "mode" { + super::fade_modes::row(ui, f, &label(&p.key)); + continue; + } if zoom_center::owns(&cmd, f) && matches!(p.key.as_str(), "centerX" | "centerY") { if p.key == "centerX" { zoom_center::row(ui, f); diff --git a/crates/ui-egui/src/dialogs/fit_image_range.rs b/crates/ui-egui/src/dialogs/fit_image_range.rs new file mode 100644 index 0000000000..087bd8c55e --- /dev/null +++ b/crates/ui-egui/src/dialogs/fit_image_range.rs @@ -0,0 +1,133 @@ +//! Fit Image's bounds belong to its dialog. The engine still accepts an unconstrained side. + +use std::cell::Cell; + +use serde_json::{Value, json}; + +use super::Fields; +use crate::panels::options_bar::range_alert; +use crate::state::UiState; + +const COMMAND: &str = "file.automate.fitImage"; +const RANGE: std::ops::RangeInclusive = 1.0..=300_000.0; +const WIDTH: (&str, &str) = ("width", "__fitImageWidth"); +const HEIGHT: (&str, &str) = ("height", "__fitImageHeight"); +const SIDES: [(&str, &str); 2] = [WIDTH, HEIGHT]; + +#[derive(Clone, Copy, PartialEq, Eq)] +pub(super) enum Alert { + Closest, + Invalid, +} + +impl Alert { + pub(super) fn message(self) -> &'static str { + match self { + Self::Closest => "A value between 1 and 300000 is required. Closest value inserted.", + Self::Invalid => "Invalid numeric entry. A value between 1 and 300000 is required. Previous value inserted.", + } + } +} + +pub(super) fn owns(fields: &Fields) -> bool { + fields.contains_key("__form") && fields.get("__command").and_then(Value::as_str) == Some(COMMAND) +} + +fn bounded(number: Option, alert: &Cell>) -> Option { + let Some(number) = number.filter(|value| value.is_finite()) else { + alert.set(Some(Alert::Invalid)); + return None; + }; + if !RANGE.contains(&number) { + alert.set(Some(Alert::Closest)); + } + Some(number.clamp(*RANGE.start(), *RANGE.end())) +} + +/// Covers dialog confirmation when automation supplies values without rendering the fields. +pub(super) fn preflight(ui: &mut UiState, id: u64) -> Result<(), String> { + if let Some(dialog) = ui.dialog_mut(id).filter(|dialog| owns(&dialog.fields)) + && let Some(alert) = validate(&mut dialog.fields) + { + range_alert(ui, alert.message()); + if alert == Alert::Invalid { + return Err(tl!(alert.message()).into()); + } + } + Ok(()) +} + +fn validate(fields: &mut Fields) -> Option { + let mut result = None; + for (key, accepted) in SIDES { + let alert = Cell::new(None); + let number = fields.get(key).and_then(|value| value.as_f64().or_else(|| value.as_str().and_then(crate::widgets::parse_num))); + let value = bounded(number, &alert) + .or_else(|| fields.get(accepted).and_then(Value::as_f64)) + .or_else(|| fields.get("__formOrig")?.get(key)?.as_f64()) + .unwrap_or(*RANGE.start()) + .clamp(*RANGE.start(), *RANGE.end()) as i64; + fields.insert(key.into(), json!(value)); + fields.insert(accepted.into(), json!(value)); + // An invalid entry needs acknowledgment before the dialog can run. + if result != Some(Alert::Invalid) { + result = alert.get().or(result); + } + } + result +} + +pub(super) fn finish(ui: &mut UiState, interactive: bool, alert: Option, outcome: Option) -> Option { + if interactive + && outcome != Some(false) + && let Some(alert) = alert + { + range_alert(ui, alert.message()); + if alert == Alert::Invalid { + return None; + } + } + outcome +} + +pub(super) fn body(ui: &mut egui::Ui, fields: &mut Fields) -> Option { + let mut alert = None; + egui::Grid::new("form-dialog").num_columns(2).spacing([12.0, 6.0]).show(ui, |ui| { + for key in crate::view_cmds::form_keys(fields) { + match key.as_str() { + "width" => alert = side(ui, fields, WIDTH, tl!("Width")).or(alert), + "height" => alert = side(ui, fields, HEIGHT, tl!("Height")).or(alert), + "dontEnlarge" => { + ui.label(""); + let mut enabled = fields.get(&key).and_then(Value::as_bool).unwrap_or(false); + ui.checkbox(&mut enabled, tl!("Dont enlarge")); + fields.insert(key, json!(enabled)); + } + _ => continue, + } + ui.end_row(); + } + }); + alert +} + +fn side(ui: &mut egui::Ui, fields: &mut Fields, (key, accepted): (&str, &str), label: &str) -> Option { + let input = fields.get(key).and_then(Value::as_i64); + let mut value = input.or_else(|| fields.get(accepted).and_then(Value::as_i64)).or_else(|| fields.get("__formOrig")?.get(key)?.as_i64()).unwrap_or(1); + let alert = Cell::new(None); + let parsed = Cell::new(false); + ui.label(label); + crate::field_tab::register(ui.ctx(), ui.next_auto_id()); + let response = ui + .add(egui::DragValue::new(&mut value).range(RANGE).clamp_existing_to_range(false).update_while_editing(false).custom_parser(|text| { + parsed.set(true); + bounded(crate::widgets::parse_num(text), &alert) + })) + .accessible_name(label); + if response.changed() || parsed.get() || input.is_some_and(|input| RANGE.contains(&(input as f64))) { + let value = value.clamp(*RANGE.start() as i64, *RANGE.end() as i64); + fields.insert(key.into(), json!(value)); + fields.insert(accepted.into(), json!(value)); + } + alert.get() +} diff --git a/crates/ui-egui/src/dialogs/fit_image_range_tests.rs b/crates/ui-egui/src/dialogs/fit_image_range_tests.rs new file mode 100644 index 0000000000..7e582361b6 --- /dev/null +++ b/crates/ui-egui/src/dialogs/fit_image_range_tests.rs @@ -0,0 +1,176 @@ +use egui::{Event, Key, Modifiers, accesskit::Role}; +use egui_kittest::{ + Harness, + kittest::{NodeT, Queryable}, +}; +use serde_json::{Value, json}; + +use super::{fit_image_range::Alert, show}; +use crate::{PhotocraftApp, Services, state::DialogKind}; + +const FIT_IMAGE: &str = "file.automate.fitImage"; + +fn open() -> (Harness<'static, PhotocraftApp>, u64) { + open_with_renderer(false) +} + +fn open_with_renderer(gpu: bool) -> (Harness<'static, PhotocraftApp>, u64) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), Services::default()); + app.run("file.new", json!({"width": 400, "height": 300})).unwrap(); + let builder = Harness::builder().with_size(egui::vec2(1000.0, 700.0)); + let builder = if gpu { builder.wgpu() } else { builder }; + let mut h = builder.build_ui_state(|ui, app| show(app, ui.ctx()), app); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + let ctx = h.ctx.clone(); + let id = crate::menus::invoke(h.state_mut(), &ctx, FIT_IMAGE, json!({})).unwrap()["dialog"].as_u64().unwrap(); + h.run_steps(4); + (h, id) +} + +fn type_side(h: &mut Harness<'static, PhotocraftApp>, label: &str, input: &str) { + let field = h.query_all_by_role(Role::SpinButton).find(|node| node.accesskit_node().label().as_deref() == Some(label)).unwrap(); + field.click(); + h.run_steps(2); + h.key_press_modifiers(Modifiers::COMMAND, Key::A); + if input.is_empty() { + h.key_press(Key::Backspace); + } else { + h.event(Event::Text(input.into())); + } + h.run_steps(1); +} + +fn field(h: &Harness<'_, PhotocraftApp>, id: u64, key: &str) -> Value { + h.state().ui.dialogs.iter().find(|dialog| dialog.id == id).unwrap().fields[key].clone() +} + +fn alert(h: &Harness<'_, PhotocraftApp>, expected: Alert) { + let top = h.state().ui.dialogs.last().unwrap(); + assert_eq!(top.kind, DialogKind::Error); + assert_eq!(top.fields["message"], expected.message()); +} + +fn dimensions(h: &Harness<'_, PhotocraftApp>) -> (u32, u32) { + let size = h.state().session.active().unwrap().doc.size; + (size.width, size.height) +} + +#[test] +fn tab_clamps_both_sides_and_the_next_tab_accepts_each_boundary() { + let (mut h, id) = open(); + for (label, key, input, boundary) in [("Width", "width", "-50", 1), ("Height", "height", "300001", 300_000)] { + type_side(&mut h, label, input); + h.key_press(Key::Tab); + h.run_steps(4); + alert(&h, Alert::Closest); + assert_eq!(field(&h, id, key), boundary); + h.key_press(Key::Enter); + h.run_steps(3); + + type_side(&mut h, label, &boundary.to_string()); + h.key_press(Key::Tab); + h.run_steps(4); + assert_eq!(h.state().ui.dialogs.len(), 1); + assert_eq!(field(&h, id, key), boundary); + } + assert_eq!(dimensions(&h), (400, 300)); +} + +#[test] +fn invalid_and_empty_entries_restore_the_last_accepted_value() { + let (mut h, id) = open(); + type_side(&mut h, "Width", "600/2"); + h.key_press(Key::Tab); + h.run_steps(4); + assert_eq!(field(&h, id, "width"), 300); + for input in ["abc", "", "NaN", "1/0", "1e999", &"9".repeat(1100)] { + type_side(&mut h, "Width", input); + h.key_press(Key::Tab); + h.run_steps(4); + alert(&h, Alert::Invalid); + assert_eq!(field(&h, id, "width"), 300, "{input}"); + assert_eq!(field(&h, id, "height"), 300); + h.key_press(Key::Enter); + h.run_steps(3); + } +} + +#[test] +fn zero_on_submit_resizes_once_using_one_pixel() { + for click in [false, true] { + let (mut h, id) = open(); + h.state_mut().ui.dialog_mut(id).unwrap().fields.insert("height".into(), json!(1000)); + h.run_steps(2); + let past = h.state().session.active().unwrap().history.past_len(); + type_side(&mut h, "Width", "0"); + if click { + h.get_by_label("OK").click(); + } else { + h.key_press(Key::Enter); + } + h.run_steps(4); + assert_eq!(dimensions(&h), (1, 1)); + let history = &h.state().session.active().unwrap().history; + assert_eq!(history.past_len(), past + 1); + assert_eq!(history.entries().last().map(String::as_str), Some("Image Size")); + assert!(h.state().ui.dialogs.iter().all(|dialog| dialog.id != id)); + alert(&h, Alert::Closest); + h.state_mut().run("edit.undo", json!({})).unwrap(); + assert_eq!(dimensions(&h), (400, 300)); + } +} + +#[test] +fn invalid_submit_keeps_the_dialog_open_without_resizing() { + let (mut h, id) = open(); + type_side(&mut h, "Width", "abc"); + h.key_press(Key::Enter); + h.run_steps(4); + alert(&h, Alert::Invalid); + assert_eq!(field(&h, id, "width"), 400); + assert_eq!(dimensions(&h), (400, 300)); +} + +#[test] +fn programmatic_dialog_confirmation_validates_both_sides() { + let (mut h, id) = open(); + type_side(&mut h, "Width", "350"); + h.key_press(Key::Tab); + h.run_steps(4); + let fields = &mut h.state_mut().ui.dialog_mut(id).unwrap().fields; + fields.insert("width".into(), json!("abc")); + fields.insert("height".into(), json!(-1)); + assert!(super::confirm(h.state_mut(), id).is_err()); + alert(&h, Alert::Invalid); + assert_eq!(field(&h, id, "width"), 350); + assert_eq!(field(&h, id, "height"), 1); + assert_eq!(dimensions(&h), (400, 300)); +} + +#[test] +fn cancel_discards_an_uncommitted_entry() { + let (mut h, _) = open(); + type_side(&mut h, "Width", "abc"); + h.get_by_label("Cancel").click(); + h.run_steps(4); + assert!(h.state().ui.dialogs.is_empty()); + assert_eq!(dimensions(&h), (400, 300)); +} + +#[test] +fn fit_image_range_gpu_snapshots() { + let Some(directory) = std::env::var_os("PHOTOCRAFT_FIT_IMAGE_SNAPSHOTS") else { return }; + let directory = std::path::PathBuf::from(directory); + let _gpu = photocraft_testkit::gpu_lock(); + let (mut h, _) = open_with_renderer(true); + h.render().unwrap().save(directory.join("dialog.png")).unwrap(); + for (input, expected, name) in [("-50", Alert::Closest, "range"), ("abc", Alert::Invalid, "invalid")] { + type_side(&mut h, "Width", input); + h.key_press(Key::Tab); + h.run_steps(4); + alert(&h, expected); + h.render().unwrap().save(directory.join(format!("{name}.png"))).unwrap(); + h.key_press(Key::Enter); + h.run_steps(3); + } +} diff --git a/crates/ui-egui/src/input/shortcuts.rs b/crates/ui-egui/src/input/shortcuts.rs index a64f710f14..0628aa94f8 100644 --- a/crates/ui-egui/src/input/shortcuts.rs +++ b/crates/ui-egui/src/input/shortcuts.rs @@ -853,7 +853,7 @@ fn handle_registry_and_tool_keys(app: &mut PhotocraftApp, ctx: &egui::Context, f } } if app.ui.frame_tool.drag.is_some() && pressed(Key::Escape) { - crate::frame_tool::cancel(app); + crate::frame_tool::escape(app); return true; } // Enter / Escape commit or cancel in-progress tool state (polygonal lasso, crop). diff --git a/crates/ui-egui/src/tools/direct_select.rs b/crates/ui-egui/src/tools/direct_select.rs index 3ee51b3862..1673ee9fbd 100644 --- a/crates/ui-egui/src/tools/direct_select.rs +++ b/crates/ui-egui/src/tools/direct_select.rs @@ -292,6 +292,9 @@ impl Edit { fn command(&self, start: [f64; 2], end: [f64; 2]) -> (&'static str, Value) { let d = [end[0] - start[0], end[1] - start[1]]; match self { + // One anchor is "Drag Anchor Point" in History, two or more the default "Drag Anchor + // Points", as in Photoshop (#13205). + Edit::Anchors(a) if a.len() == 1 => ("path.moveAnchors", json!({"anchors": a, "move": d, "stepName": "Drag Anchor Point"})), Edit::Anchors(a) => ("path.moveAnchors", json!({"anchors": a, "move": d})), Edit::Curvature(a) => ("path.moveAnchors", json!({"anchors": a, "move": d, "curvature": true})), Edit::Handle([s, k], h, from, independent) => { @@ -1007,6 +1010,9 @@ mod convert_point_tolerance_tests; #[cfg(test)] mod convert_point_drag_segment_tests; +#[cfg(test)] +mod history_names_tests; + #[cfg(test)] mod shift_angle_tests; diff --git a/crates/ui-egui/src/tools/direct_select/convert_point_history_tests.rs b/crates/ui-egui/src/tools/direct_select/convert_point_history_tests.rs index 7539f7aa6f..a9e3752975 100644 --- a/crates/ui-egui/src/tools/direct_select/convert_point_history_tests.rs +++ b/crates/ui-egui/src/tools/direct_select/convert_point_history_tests.rs @@ -128,7 +128,7 @@ fn mask_corner(app: &PhotocraftApp) -> photocraft_doc::Knot { #[test] fn other_tools_keep_their_step_names() { - let direct = vec!["Drag Direction Point".to_string()]; + let direct = vec!["Drag Control Point".to_string()]; for mods in [Modifiers::NONE, Modifiers::ALT] { let mut ds = with_shown_handles(Tool::DirectSelection); assert_eq!(added(&mut ds, |a| drag(a, [140.0, 40.0], [140.0, 70.0], mods)), direct, "Direct Selection {mods:?}"); @@ -157,7 +157,7 @@ fn the_commands_take_the_step_name_and_refuse_any_other() { let handle = json!({"subpath": 0, "knot": 1, "handle": "out", "to": [150, 60], "independent": true}); let mut run = |id: &str, params: &serde_json::Value| added(&mut app, |a| a.run(id, params.clone()).map(|_| ()).unwrap()); assert_eq!(run("path.convertPoint", &convert), ["Convert Point"]); - assert_eq!(run("path.moveHandle", &handle), ["Drag Direction Point"]); + assert_eq!(run("path.moveHandle", &handle), ["Drag Control Point"]); let named = |p: &serde_json::Value, n: &str| { let mut p = p.clone(); p["stepName"] = json!(n); @@ -179,7 +179,7 @@ fn a_bad_step_name_is_an_error_and_changes_nothing() { let e = app.run("path.convertPoint", json!({"subpath": 0, "knot": 1, "stepName": bad})).unwrap_err(); assert!(e.contains("stepName"), "{bad}: {e}"); } - for bad in [json!("Change Anchor Point"), json!("Drag Direction Point"), json!(0), json!({})] { + for bad in [json!("Change Anchor Point"), json!("Drag Control Point"), json!(0), json!({})] { let e = app.run("path.moveHandle", json!({"subpath": 0, "knot": 1, "handle": "out", "to": [150, 60], "stepName": bad})).unwrap_err(); assert!(e.contains("stepName"), "{bad}: {e}"); } diff --git a/crates/ui-egui/src/tools/direct_select/history_names_tests.rs b/crates/ui-egui/src/tools/direct_select/history_names_tests.rs new file mode 100644 index 0000000000..9c7b98bfad --- /dev/null +++ b/crates/ui-egui/src/tools/direct_select/history_names_tests.rs @@ -0,0 +1,57 @@ +//! #13205: a Direct Selection drag of one anchor is one History step "Drag Anchor Point", of two +//! or more "Drag Anchor Points"; a handle drag (with or without ⌥) is "Drag Control Point" and a +//! segment drag "Drag Segment". An arrow-key nudge of one anchor keeps today's name. + +use egui::Modifiers; +use serde_json::json; + +use super::convert_point_history_tests::{added, click, drag}; +use crate::PhotocraftApp; +use crate::state::Tool; + +/// A square work path; knot 1 at (120, 40) is smooth with handles at (100, 40) and (140, 40). +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 200, "height": 200})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::DirectSelection; + let path = json!({"subpaths": [{"closed": true, "knots": [ + [40, 40], + {"anchor": [120, 40], "in": [100, 40], "out": [140, 40], "smooth": true}, + [120, 120], + [40, 120], + ]}]}); + app.run("path.set", json!({"name": "work", "path": path})).unwrap(); + app +} + +#[test] +fn a_one_anchor_drag_is_drag_anchor_point() { + let mut app = app(); + assert_eq!(added(&mut app, |a| drag(a, [120.0, 120.0], [130.0, 130.0], Modifiers::NONE)), ["Drag Anchor Point"]); + assert_eq!(app.ui.direct_selection.anchors, vec![[0, 2]]); +} + +#[test] +fn a_drag_of_two_anchors_is_drag_anchor_points() { + let mut app = app(); + click(&mut app, [40.0, 120.0], Modifiers::NONE); + click(&mut app, [120.0, 120.0], Modifiers::SHIFT); + assert_eq!(app.ui.direct_selection.anchors, vec![[0, 3], [0, 2]]); + assert_eq!(added(&mut app, |a| drag(a, [120.0, 120.0], [120.0, 140.0], Modifiers::NONE)), ["Drag Anchor Points"]); +} + +#[test] +fn a_handle_drag_is_drag_control_point() { + for mods in [Modifiers::NONE, Modifiers::ALT] { + let mut app = app(); + click(&mut app, [120.0, 40.0], Modifiers::NONE); + assert_eq!(added(&mut app, |a| drag(a, [140.0, 40.0], [140.0, 70.0], mods)), ["Drag Control Point"], "{mods:?}"); + } +} + +#[test] +fn a_segment_drag_stays_drag_segment() { + let mut app = app(); + assert_eq!(added(&mut app, |a| drag(a, [80.0, 120.0], [80.0, 150.0], Modifiers::NONE)), ["Drag Segment"]); +} diff --git a/crates/ui-egui/src/tools/frame_tool.rs b/crates/ui-egui/src/tools/frame_tool.rs index 190b0509c2..d5639b9af5 100644 --- a/crates/ui-egui/src/tools/frame_tool.rs +++ b/crates/ui-egui/src/tools/frame_tool.rs @@ -63,13 +63,16 @@ fn drawn(start: [f64; 2], cur: [f64; 2], square: bool, centred: bool) -> [i64; 4 let [x, y] = cur; let (mut dx, mut dy) = (x - sx, y - sy); if square { - let side = dx.abs().max(dy.abs()); + // Shift squares from the drag's shorter side, as the reference application does (#13865). + let side = dx.abs().min(dy.abs()); dx = side.copysign(dx); dy = side.copysign(dy); } let (a, b) = if centred { ([sx - dx, sy - dy], [sx + dx, sy + dy]) } else { (start, [sx + dx, sy + dy]) }; [a[0].min(b[0]), a[1].min(b[1]), a[0].max(b[0]), a[1].max(b[1])].map(|v| v.round() as i64) } +#[cfg(test)] +mod shift_square_tests; pub fn selected(app: &PhotocraftApp) -> Option<&Layer> { let st = app.session.active()?; let id = photocraft_engine::frame_cmds::frame_of(&st.doc, st.active_layer?)?; @@ -340,6 +343,43 @@ pub fn cancel(app: &mut PhotocraftApp) { app.ui.frame_tool.drag = None; app.frame_preview = None; } +/// Escape during a drag. A frame being drawn is made at the pointer, as the reference application +/// does (#13866); the mouse movement and release after it change nothing. Moving, resizing or +/// rotating an existing frame is cancelled. +pub fn escape(app: &mut PhotocraftApp) { + let Some(FrameDrag::New { start, cur, square, centred, doc, revision }) = app.ui.frame_tool.drag.clone() else { + cancel(app); + return; + }; + cancel(app); + if app.session.active().is_some_and(|st| st.doc.id == doc && st.revision == revision) { + commit_new(app, start, cur, square, centred); + } +} +/// Make the frame drawn from `start` to `cur`, unless the drag was a click or drew nothing. +fn commit_new(app: &mut PhotocraftApp, start: [f64; 2], cur: [f64; 2], square: bool, centred: bool) { + if (cur[0] - start[0]).hypot(cur[1] - start[1]) * f64::from(app.point_zoom()) < CLICK_PX { + return; + } + let r = drawn(start, cur, square, centred); + if r[2] <= r[0] || r[3] <= r[1] { + return; + } + let mut p = shape_params(app, r); + if let Some(id) = content_layer(app, r) { + p["layer"] = json!(id); + } + match app.run("layer.new.frame", p) { + Ok(v) => { + if let Some(id) = v.get("layer").and_then(Value::as_u64) { + select(app, LayerId(id), Target::Frame); + } + } + Err(e) => report(app, Err(e)), + } +} +#[cfg(test)] +mod escape_commit_tests; /// A native double click (also driven by ui.click count=2) toggles content-only selection. pub fn double_click(app: &mut PhotocraftApp, p: [f64; 2]) { let Some(id) = frame_at(app, p) else { return }; @@ -463,31 +503,18 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> return true; } match d { - FrameDrag::New { start, .. } => { - if (x - start[0]).hypot(y - start[1]) * f64::from(app.point_zoom()) < CLICK_PX { - return true; - } - let r = drawn(start, [x, y], mods.shift, mods.alt); - if r[2] <= r[0] || r[3] <= r[1] { - return true; - } - let mut p = shape_params(app, r); - if let Some(id) = content_layer(app, r) { - p["layer"] = json!(id); - } - match app.run("layer.new.frame", p) { - Ok(v) => { - if let Some(id) = v.get("layer").and_then(Value::as_u64) { - select(app, LayerId(id), Target::Frame); - } - } - Err(e) => report(app, Err(e)), - } - } + FrameDrag::New { start, .. } => commit_new(app, start, [x, y], mods.shift, mods.alt), FrameDrag::Edit { layer, original, start, mode, .. } => { let transform = edit_transform(&original, mode, start, [x, y], mods); if transform != original.transform { - let r = app.run("layer.frame.set", json!({"layer":layer.0,"transform":transform.m})); + let mut p = json!({"layer":layer.0,"transform":transform.m}); + // Moving an empty frame is a "Move" step (#13880). Handle drags, and a + // frame with an image (not measured yet), keep "Frame Properties". + let empty = app.session.active().and_then(|st| st.doc.layer(layer)).is_some_and(|l| l.children().is_none_or(<[Layer]>::is_empty)); + if mode == EditMode::Move && empty { + p["historyName"] = json!("Move"); + } + let r = app.run("layer.frame.set", p); report(app, r); } } @@ -868,3 +895,5 @@ pub fn keys(app: &mut PhotocraftApp, ctx: &egui::Context) -> bool { } false } +#[cfg(test)] +mod move_history_tests; diff --git a/crates/ui-egui/src/tools/frame_tool/escape_commit_tests.rs b/crates/ui-egui/src/tools/frame_tool/escape_commit_tests.rs new file mode 100644 index 0000000000..f89988ba2f --- /dev/null +++ b/crates/ui-egui/src/tools/frame_tool/escape_commit_tests.rs @@ -0,0 +1,75 @@ +//! Escape during a frame drag makes the frame at the pointer (#13866). +use super::*; +use crate::canvas::tool_event; + +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width":600,"height":400})).unwrap(); + app.sync_views(); + app.ui.extras.snap = false; + app.ui.tool = Tool::Frame; + app +} + +fn escape(app: &mut PhotocraftApp) { + let ctx = egui::Context::default(); + ctx.begin_pass(egui::RawInput { + events: vec![egui::Event::Key { key: egui::Key::Escape, physical_key: None, pressed: true, repeat: false, modifiers: egui::Modifiers::NONE }], + ..Default::default() + }); + crate::shortcuts::handle(app, &ctx); + ctx.end_pass().textures_delta.clear(); +} + +fn entries(app: &PhotocraftApp) -> Vec { + app.session.active().unwrap().history.entries() +} + +fn frames(app: &PhotocraftApp) -> Vec<[f64; 6]> { + let st = app.session.active().unwrap(); + st.doc.walk().into_iter().filter_map(|(_, _, l)| l.frame.as_ref().map(|f| f.transform.m)).collect() +} + +#[test] +fn escape_during_a_drag_makes_the_frame_at_the_pointer_in_one_new_frame_step() { + let mut app = app(); + let before = entries(&app); + let m = egui::Modifiers::NONE; + tool_event(&mut app, ToolEvent::Down { x: 50., y: 50., pressure: 1.0 }, m); + tool_event(&mut app, ToolEvent::Move { x: 122., y: 120., pressure: 1.0 }, m); + escape(&mut app); + assert!(app.ui.frame_tool.drag.is_none()); + assert_eq!(frames(&app), vec![[72., 0., 0., 70., 50., 50.]], "50..122 x 50..120"); + let after = entries(&app); + assert_eq!(after.len(), before.len() + 1); + assert_eq!(after.last().map(String::as_str), Some("New Frame")); + + // The movement and release after Escape change nothing more. + tool_event(&mut app, ToolEvent::Move { x: 300., y: 250., pressure: 1.0 }, m); + tool_event(&mut app, ToolEvent::Up { x: 300., y: 250. }, m); + assert_eq!(frames(&app), vec![[72., 0., 0., 70., 50., 50.]]); + assert_eq!(entries(&app), after); +} + +#[test] +fn escape_after_a_click_sized_drag_makes_nothing() { + let mut app = app(); + let before = entries(&app); + tool_event(&mut app, ToolEvent::Down { x: 50., y: 50., pressure: 1.0 }, egui::Modifiers::NONE); + tool_event(&mut app, ToolEvent::Move { x: 51., y: 51., pressure: 1.0 }, egui::Modifiers::NONE); + escape(&mut app); + assert!(app.ui.frame_tool.drag.is_none()); + assert!(frames(&app).is_empty()); + assert_eq!(entries(&app), before); +} + +#[test] +fn escape_with_no_frame_drag_changes_nothing() { + let mut app = app(); + tool_event(&mut app, ToolEvent::Down { x: 50., y: 50., pressure: 1.0 }, egui::Modifiers::NONE); + tool_event(&mut app, ToolEvent::Up { x: 122., y: 120. }, egui::Modifiers::NONE); + let (before, made) = (entries(&app), frames(&app)); + escape(&mut app); + assert_eq!(entries(&app), before); + assert_eq!(frames(&app), made); +} diff --git a/crates/ui-egui/src/tools/frame_tool/move_history_tests.rs b/crates/ui-egui/src/tools/frame_tool/move_history_tests.rs new file mode 100644 index 0000000000..a632c5f3c6 --- /dev/null +++ b/crates/ui-egui/src/tools/frame_tool/move_history_tests.rs @@ -0,0 +1,102 @@ +//! Moving an empty frame with the Frame tool records "Move" (#13880). +use super::*; +use crate::canvas::tool_event; + +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width":600,"height":400})).unwrap(); + app.sync_views(); + app.ui.extras.snap = false; + app.ui.tool = Tool::Frame; + app +} + +fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2]) { + let m = egui::Modifiers::NONE; + tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, m); + tool_event(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, m); + tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, m); +} + +fn entries(app: &PhotocraftApp) -> Vec { + app.session.active().unwrap().history.entries() +} + +fn transform(app: &PhotocraftApp, id: LayerId) -> [f64; 6] { + app.session.active().unwrap().doc.layer(id).unwrap().frame.as_ref().unwrap().transform.m +} + +/// An empty 100 x 80 frame at 20,30, drawn with the Frame tool. +fn empty_frame(app: &mut PhotocraftApp) -> LayerId { + drag(app, [20., 30.], [120., 110.]); + selected(app).unwrap().id +} + +#[test] +fn dragging_an_empty_frame_records_one_move_step_that_undoes_in_one() { + let mut app = app(); + let id = empty_frame(&mut app); + let before = entries(&app); + drag(&mut app, [70., 70.], [90., 80.]); + assert_eq!(transform(&app, id), [100., 0., 0., 80., 40., 40.], "moved +20,+10"); + let after = entries(&app); + assert_eq!(after.len(), before.len() + 1); + assert_eq!(after.last().map(String::as_str), Some("Move")); + app.run("edit.undo", json!({})).unwrap(); + assert_eq!(transform(&app, id), [100., 0., 0., 80., 20., 30.]); + assert_eq!(entries(&app), before); +} + +#[test] +fn property_changes_and_handle_drags_keep_frame_properties() { + let mut app = app(); + let id = empty_frame(&mut app); + app.run("layer.frame.set", json!({"layer":id.0,"stroke":{"color":"#ff0000","width":2}})).unwrap(); + assert_eq!(entries(&app).last().map(String::as_str), Some("Frame Properties")); + app.run("layer.frame.set", json!({"layer":id.0,"transform":[120,0,0,80,20,30]})).unwrap(); + assert_eq!(entries(&app).last().map(String::as_str), Some("Frame Properties")); + let steps = entries(&app).len(); + // The bottom-right resize handle. + drag(&mut app, [140., 110.], [160., 130.]); + assert_eq!(transform(&app, id).map(f64::round), [140., 0., 0., 100., 20., 30.], "resized, not moved"); + assert_eq!(entries(&app).len(), steps + 1); + assert_eq!(entries(&app).last().map(String::as_str), Some("Frame Properties")); +} + +#[test] +fn a_bad_history_name_is_refused_and_changes_nothing() { + let mut app = app(); + let id = empty_frame(&mut app); + let before = entries(&app); + for bad in [json!(5), json!("Rotate"), json!(""), json!(["Move"]), json!({"name":"Move"}), json!("move")] { + assert!(app.run("layer.frame.set", json!({"layer":id.0,"transform":[100,0,0,80,40,40],"historyName":bad})).is_err(), "{bad}"); + assert_eq!(entries(&app), before); + assert_eq!(transform(&app, id), [100., 0., 0., 80., 20., 30.]); + } + app.run("layer.frame.set", json!({"layer":id.0,"transform":[100,0,0,80,40,40],"historyName":null})).unwrap(); + assert_eq!(entries(&app).last().map(String::as_str), Some("Frame Properties")); + app.run("layer.frame.set", json!({"layer":id.0,"transform":[100,0,0,80,20,30],"historyName":"Move"})).unwrap(); + assert_eq!(entries(&app).last().map(String::as_str), Some("Move")); +} + +/// A frame with an image is not what #13880 measured: its border drag keeps today's step name. +#[test] +fn dragging_the_border_of_a_frame_with_an_image_keeps_frame_properties() { + let mut app = app(); + let id = empty_frame(&mut app); + let content = app + .session + .edit("Image", |doc, _| { + let mut l = Layer::raster("Photo", doc.pixel_format()); + l.surface_mut().unwrap().fill_rect(Rect::new(20, 30, 120, 110), &[1., 0., 0., 1.]); + let id = l.id; + doc.layers.push(l); + Ok(id) + }) + .unwrap(); + app.run("layer.frame.setContent", json!({"layer":id.0,"content":content.0})).unwrap(); + select(&mut app, id, Target::Frame); + drag(&mut app, [45., 30.], [65., 40.]); + assert_eq!(transform(&app, id), [100., 0., 0., 80., 40., 40.]); + assert_eq!(entries(&app).last().map(String::as_str), Some("Frame Properties")); +} diff --git a/crates/ui-egui/src/tools/frame_tool/shift_square_tests.rs b/crates/ui-egui/src/tools/frame_tool/shift_square_tests.rs new file mode 100644 index 0000000000..2007331e36 --- /dev/null +++ b/crates/ui-egui/src/tools/frame_tool/shift_square_tests.rs @@ -0,0 +1,61 @@ +//! Shift while drawing a frame squares from the drag's shorter side (#13865). +use super::*; +use crate::canvas::tool_event; + +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width":600,"height":400})).unwrap(); + app.sync_views(); + app.ui.extras.snap = false; + app.ui.tool = Tool::Frame; + app +} + +const SHIFT: egui::Modifiers = egui::Modifiers { shift: true, ..egui::Modifiers::NONE }; +const ALT: egui::Modifiers = egui::Modifiers { alt: true, ..egui::Modifiers::NONE }; +const SHIFT_ALT: egui::Modifiers = egui::Modifiers { shift: true, alt: true, ..egui::Modifiers::NONE }; + +/// Press at `from` with `down`, move to `to` with `held`, and return the outline being drawn +/// (`left, top, right, bottom`) before releasing there and returning the new frame's transform. +fn draw(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2], down: egui::Modifiers, held: egui::Modifiers) -> ([i64; 4], [f64; 6]) { + tool_event(app, ToolEvent::Down { x: from[0], y: from[1], pressure: 1.0 }, down); + tool_event(app, ToolEvent::Move { x: to[0], y: to[1], pressure: 1.0 }, held); + let Some(FrameDrag::New { start, cur, square, centred, .. }) = app.ui.frame_tool.drag.clone() else { panic!("a frame is being drawn") }; + let live = drawn(start, cur, square, centred); + tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, held); + (live, selected(app).unwrap().frame.as_ref().unwrap().transform.m) +} + +#[test] +fn shift_squares_a_rectangle_from_the_shorter_side_at_the_start_corner() { + let mut app = app(); + let (live, m) = draw(&mut app, [400., 50.], [500., 110.], SHIFT, SHIFT); + assert_eq!(m, [60., 0., 0., 60., 400., 50.], "400..460 x 50..110"); + assert_eq!(live, [400, 50, 460, 110], "the live outline shows the committed square"); + assert_eq!(app.session.active().unwrap().history.entries().last().map(String::as_str), Some("New Frame")); +} + +#[test] +fn shift_squares_a_polygon_from_the_shorter_side() { + let mut app = app(); + app.ui.frame_tool.shape = "polygon".into(); + let (live, m) = draw(&mut app, [100., 100.], [260., 180.], SHIFT, SHIFT); + assert_eq!(m, [80., 0., 0., 80., 100., 100.], "a 160 x 80 drag gives 80 x 80"); + assert_eq!(live, [100, 100, 180, 180]); +} + +#[test] +fn shift_alt_squares_the_shorter_half_extent_around_the_start() { + let mut app = app(); + let (live, m) = draw(&mut app, [150., 300.], [210., 330.], SHIFT_ALT, SHIFT_ALT); + assert_eq!(m, [60., 0., 0., 60., 120., 270.], "120..180 x 270..330"); + assert_eq!(live, [120, 270, 180, 330]); +} + +#[test] +fn alt_alone_draws_from_the_centre_without_squaring() { + let mut app = app(); + let (live, m) = draw(&mut app, [450., 300.], [500., 330.], egui::Modifiers::NONE, ALT); + assert_eq!(m, [100., 0., 0., 60., 400., 270.], "400..500 x 270..330"); + assert_eq!(live, [400, 270, 500, 330]); +} diff --git a/crates/ui-egui/src/tools/frame_tool/tests.rs b/crates/ui-egui/src/tools/frame_tool/tests.rs index f0be9a649f..7fa4778347 100644 --- a/crates/ui-egui/src/tools/frame_tool/tests.rs +++ b/crates/ui-egui/src/tools/frame_tool/tests.rs @@ -174,8 +174,9 @@ fn modifiers_shape_selection_and_invalid_control_params_are_consistent() { pointer(&mut app, ToolEvent::Down { x: 100., y: 100., pressure: 1. }, mods); pointer(&mut app, ToolEvent::Up { x: 130., y: 120. }, mods); let f = selected(&app).unwrap().frame.as_ref().unwrap(); - assert_eq!(f.bounds(), Rect::new(70, 70, 130, 130)); - assert_eq!(TestMask(f.outline()).value(70, 70), 0.0, "triangle rather than bounding rectangle"); + // Shift squares from the shorter side (#13865): 20 px each way around the start. + assert_eq!(f.bounds(), Rect::new(80, 80, 120, 120)); + assert_eq!(TestMask(f.outline()).value(80, 80), 0.0, "triangle rather than bounding rectangle"); let frame = selected(&app).unwrap().id; let content = app .session diff --git a/crates/ui-egui/src/tools/vector_ui.rs b/crates/ui-egui/src/tools/vector_ui.rs index 877a957dac..6dbfb9fa81 100644 --- a/crates/ui-egui/src/tools/vector_ui.rs +++ b/crates/ui-egui/src/tools/vector_ui.rs @@ -225,6 +225,8 @@ mod paint_tests; #[cfg(test)] mod triangle_box_geometry_tests; +#[cfg(test)] +mod triangle_properties_fields_tests; #[cfg(test)] mod pen_resume_tests; @@ -253,6 +255,9 @@ mod ellipse_path_menus_tests; #[cfg(test)] mod triangle_align_edges_tests; +#[cfg(test)] +mod triangle_shift_equilateral_tests; + pub(crate) use pen::freeform_locked_shape; #[cfg(test)] use pen_resume::pen_finish_on_redo; diff --git a/crates/ui-egui/src/tools/vector_ui/triangle_properties_fields_tests.rs b/crates/ui-egui/src/tools/vector_ui/triangle_properties_fields_tests.rs new file mode 100644 index 0000000000..49bdedc7b1 --- /dev/null +++ b/crates/ui-egui/src/tools/vector_ui/triangle_properties_fields_tests.rs @@ -0,0 +1,162 @@ +//! #13360: a triangle's Properties Shape section shows one Corner radius field and no Sides and no +//! Star ratio field; Polygon tool (even with 3 sides) and Star tool shapes keep theirs. The +//! behaviour landed with the live triangle kind (#13578); these cases pin the issue's Done-when. + +use egui::accesskit::Role; +use egui::{Modifiers, vec2}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use photocraft_doc::{LayerContent, LayerId, LiveShape}; +use serde_json::{Value, json}; + +use super::{finish_shape, shape_properties}; +use crate::PhotocraftApp; +use crate::state::Tool; + +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 800, "height": 600})).unwrap(); + app.sync_views(); + app +} + +fn active_id(app: &PhotocraftApp) -> LayerId { + app.session.active().unwrap().active_layer.unwrap() +} + +fn fonts_ready(ui: &egui::Ui) -> bool { + ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) +} + +fn harness(app: PhotocraftApp, id: LayerId) -> Harness<'static, PhotocraftApp> { + let mut h = Harness::builder().with_size(vec2(400.0, 900.0)).build_ui_state( + move |ui, app| { + if fonts_ready(ui) { + shape_properties(app, ui, id); + } + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + h.run_steps(4); + h +} + +fn labels(h: &Harness<'static, PhotocraftApp>) -> Vec { + h.query_all_by_role(Role::SpinButton).filter_map(|n| n.accesskit_node().label()).map(|l| l.to_string()).collect() +} + +fn only_corner_radius(h: &Harness<'static, PhotocraftApp>) { + let l = labels(h); + assert!(l.iter().any(|s| s == "Corner radius"), "{l:?}"); + assert!(!l.iter().any(|s| s == "Sides" || s == "Star ratio"), "{l:?}"); +} + +fn drag(tool: Tool, sides: u32) -> (PhotocraftApp, LayerId) { + let mut app = app(); + app.ui.tool = tool; + app.ui.tool_options.polygon_sides = sides; + finish_shape(&mut app, tool, [400.0, 300.0], [600.0, 400.0], Modifiers::NONE); + let id = active_id(&app); + (app, id) +} + +fn info(app: &mut PhotocraftApp) -> Value { + let id = active_id(app).0; + app.session.execute("shape.info", json!({"layer": id})).unwrap() +} + +fn knots(v: &Value) -> usize { + v["path"]["subpaths"][0]["knots"].as_array().unwrap().len() +} + +fn live(app: &PhotocraftApp, id: LayerId) -> LiveShape { + match &app.session.active().unwrap().doc.layer(id).unwrap().content { + LayerContent::Shape(sh) => sh.live.clone().expect("a live shape"), + _ => panic!("a shape layer"), + } +} + +fn corner_radius(app: &PhotocraftApp, id: LayerId) -> f64 { + match live(app, id) { + LiveShape::Triangle { corner_radius, .. } => corner_radius, + other => panic!("a live triangle, got {other:?}"), + } +} + +fn type_radius(h: &mut Harness<'static, PhotocraftApp>, text: &str) { + h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().label().as_deref() == Some("Corner radius")).expect("the Corner radius field").click(); + h.run_steps(1); + h.key_press_modifiers(Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text(text.into())); + h.run_steps(1); + h.key_press(egui::Key::Tab); + h.run_steps(3); +} + +#[test] +fn a_dragged_triangle_shows_only_corner_radius() { + let (app, id) = drag(Tool::Triangle, 5); + assert!(matches!(live(&app, id), LiveShape::Triangle { .. })); + only_corner_radius(&harness(app, id)); +} + +#[test] +fn a_create_triangle_shape_shows_only_corner_radius() { + // Runs the command Create Triangle, OK sends (same geometry as the dialog, see + // triangle_box_geometry_tests) rather than driving the dialog. + let mut app = app(); + let fields = json!({"__createShape": "triangle", "__at": [400.0, 300.0], "width": 100.0, "height": 100.0, "fromCenter": false}); + let Value::Object(fields) = fields else { panic!("an object") }; + let geometry = crate::shape_dialog::geometry(&fields).unwrap(); + app.run("shape.create", geometry).unwrap(); + let id = active_id(&app); + assert!(matches!(live(&app, id), LiveShape::Triangle { .. })); + only_corner_radius(&harness(app, id)); +} + +#[test] +fn editing_corner_radius_rounds_the_triangle() { + let (mut app, id) = drag(Tool::Triangle, 5); + let before = knots(&info(&mut app)); + let mut h = harness(app, id); + type_radius(&mut h, "10"); + assert_eq!(corner_radius(h.state(), id), 10.0); + let after = knots(&info(h.state_mut())); + assert!(after > before, "{before} -> {after}"); + only_corner_radius(&h); +} + +#[test] +fn polygon_with_three_sides_and_star_keep_sides_and_star_ratio() { + for (tool, sides) in [(Tool::Polygon, 3), (Tool::Polygon, 6), (Tool::Star, 5)] { + let (app, id) = drag(tool, sides); + let h = harness(app, id); + let l = labels(&h); + assert!(l.iter().any(|s| s == "Sides") && l.iter().any(|s| s == "Star ratio") && l.iter().any(|s| s == "Corner radius"), "{tool:?} {sides}: {l:?}"); + } +} + +#[test] +fn the_triangle_stays_a_triangle_after_undo_redo_and_a_pcraft_round_trip() { + let (app, id) = drag(Tool::Triangle, 5); + let mut h = harness(app, id); + type_radius(&mut h, "10"); + h.state_mut().run("edit.undo", json!({})).unwrap(); + h.run_steps(3); + assert_eq!(corner_radius(h.state(), id), 0.0); + only_corner_radius(&h); + h.state_mut().run("edit.redo", json!({})).unwrap(); + h.run_steps(3); + assert_eq!(corner_radius(h.state(), id), 10.0); + only_corner_radius(&h); + + // Document-level round trip with the format crate. + let bytes = photocraft_format::save_to_bytes(&h.state().session.active().unwrap().doc, &Default::default()).unwrap(); + let doc = photocraft_format::load_from_bytes(&bytes).unwrap(); + let loaded = match &doc.layer(id).unwrap().content { + LayerContent::Shape(sh) => sh.live.clone(), + _ => panic!("a shape layer"), + }; + assert!(matches!(loaded, Some(LiveShape::Triangle { corner_radius, .. }) if corner_radius == 10.0), "{loaded:?}"); +} diff --git a/crates/ui-egui/src/tools/vector_ui/triangle_shift_equilateral_tests.rs b/crates/ui-egui/src/tools/vector_ui/triangle_shift_equilateral_tests.rs new file mode 100644 index 0000000000..cf0a4db092 --- /dev/null +++ b/crates/ui-egui/src/tools/vector_ui/triangle_shift_equilateral_tests.rs @@ -0,0 +1,84 @@ +//! #13351: Shift with the Triangle tool draws an equilateral triangle in the circle of the square +//! on the drag's shorter side, apex up; Shift+Alt centres the circle on the press. The preview +//! (`shape_bounds`) shows the same triangle, and a plain drag still fills its box (#13350). + +use egui::Modifiers; +use serde_json::{Value, json}; + +use super::{finish_shape, shape_bounds}; +use crate::PhotocraftApp; +use crate::state::Tool; + +fn app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 1000, "height": 800})).unwrap(); + app.sync_views(); + app.ui.tool = Tool::Triangle; + app +} + +/// `shape.info` of the active layer. +fn info(app: &mut PhotocraftApp) -> Value { + let id = app.session.active().unwrap().active_layer.unwrap().0; + app.session.execute("shape.info", json!({"layer": id})).unwrap() +} + +fn anchors(v: &Value) -> Vec<(f64, f64)> { + let knots = v["path"]["subpaths"][0]["knots"].as_array().unwrap(); + knots.iter().map(|k| (k["anchor"][0].as_f64().unwrap(), k["anchor"][1].as_f64().unwrap())).collect() +} + +fn close(got: &[(f64, f64)], want: &[(f64, f64)]) { + assert_eq!(got.len(), want.len(), "{got:?}"); + for (g, w) in got.iter().zip(want) { + assert!((g.0 - w.0).abs() <= 0.05 && (g.1 - w.1).abs() <= 0.05, "{got:?} vs {want:?}"); + } +} + +fn drag(start: [f64; 2], end: [f64; 2], mods: Modifiers) -> Vec<(f64, f64)> { + let mut app = app(); + finish_shape(&mut app, Tool::Triangle, start, end, mods); + anchors(&info(&mut app)) +} + +#[test] +fn shift_sizes_the_circle_from_the_shorter_side() { + close(&drag([400.0, 300.0], [600.0, 400.0], Modifiers::SHIFT), &[(450.0, 300.0), (493.3, 375.0), (406.7, 375.0)]); +} + +#[test] +fn shift_alt_centres_the_circle_on_the_press() { + let got = drag([400.0, 300.0], [600.0, 400.0], Modifiers::SHIFT | Modifiers::ALT); + close(&got, &[(400.0, 200.0), (486.6, 350.0), (313.4, 350.0)]); +} + +#[test] +fn a_tall_narrow_drag_uses_its_width() { + let got = drag([400.0, 300.0], [450.0, 500.0], Modifiers::SHIFT); + close(&got, &[(425.0, 300.0), (446.65, 337.5), (403.35, 337.5)]); +} + +#[test] +fn the_preview_shows_the_result_triangle() { + let app = app(); + let b = shape_bounds(&app.ui.tool_options, Tool::Triangle, [400.0, 300.0], [600.0, 400.0], Modifiers::SHIFT).unwrap(); + for (g, w) in b.iter().zip([406.7, 300.0, 493.3, 375.0]) { + assert!((g - w).abs() <= 0.05, "{b:?}"); + } + let mut app = app; + finish_shape(&mut app, Tool::Triangle, [400.0, 300.0], [600.0, 400.0], Modifiers::SHIFT); + let got = anchors(&info(&mut app)); + let xs = got.iter().map(|p| p.0); + let (x0, x1) = (xs.clone().fold(f64::MAX, f64::min), xs.fold(f64::MIN, f64::max)); + let ys = got.iter().map(|p| p.1); + let (y0, y1) = (ys.clone().fold(f64::MAX, f64::min), ys.fold(f64::MIN, f64::max)); + for (g, w) in [x0, y0, x1, y1].iter().zip(b) { + assert!((g - w).abs() <= 1e-9, "{got:?} vs {b:?}"); + } +} + +#[test] +fn a_plain_drag_still_fills_its_box() { + let got = drag([400.0, 300.0], [600.0, 400.0], Modifiers::NONE); + close(&got, &[(500.0, 300.0), (600.0, 400.0), (400.0, 400.0)]); +} diff --git a/docs/control-protocol.md b/docs/control-protocol.md index 6db4685f2e..ecf603fe9a 100644 --- a/docs/control-protocol.md +++ b/docs/control-protocol.md @@ -113,7 +113,7 @@ The transport is `apps/photocraft/src/control_server.rs`, and the handlers are i Both source overlays honor Pattern Preview. Unsupported cross-document mask/alpha-channel gestures have no source overlay. Healing Brush excludes absent source pixels from its solve and paint coverage, independently of alpha reconstructed by the solver. - Clone Source X/Y are signed document-pixel offsets, using the existing `source - destination` convention. The panel derives the current preview/stroke pairing without anchoring it on hover. `cloneSource.list` exposes `anchor` (persistent Aligned pairing), `lastAnchor` (most recently used successful pairing), and `offset` (source minus that last reference). Unaligned strokes update the readout while restarting at the sample point each time; failed or canceled strokes do not commit a pairing. To edit the offset shown for a preview, use `cloneSource.set {"offset":[dx,dy],"anchor":[destinationX,destinationY]}`; without an explicit anchor an edit uses the last reported reference, then the existing aligned reference or sample point. Source picking clears both anchors; resetTransform retains them. Null optional coordinates are omitted consistently in mapping and source-document selection. Invalid coordinates, slot indexes, and oversized transformed sampling windows return errors without painting. - Brush Pose's `pose.overrideTiltX` and `pose.overrideTiltY` are independent booleans. For example, `engine.execute {"command":"tools.setBrush","params":{"pose":{"enabled":true,"tiltX":45,"overrideTiltX":true,"overrideTiltY":false}}}` fixes X at 45° while Y follows the stylus. Pose tilts are degrees (±90); the Brush Settings panel displays percentages (±100). Old stored `overrideTilt` values migrate to both axes. In command patches, `overrideTilt` sets both axes unless an explicit axis field in the same patch overrides it. `brush.get` includes both axis flags and the legacy combined readback (`overrideTilt` is true only when both flags are true). Axis-only journals omit that derived combined key so replay retains the other axis. Present flag values must be booleans; null and other types return an error. -- `ui.set` also accepts the Eyedropper options bar (#1649): `eyedropperSampleSize` (`"point"` or 1, 3, 5, 11, 31, 51, 101: the side of the averaged square, shared by the Eyedropper, a painting tool's Alt-click eyedropper, the Curves/Color Picker eyedroppers and the Info panel), `eyedropperSample` (`current`, `currentAndBelow`, `all`, `allNoAdjustments`, `currentAndBelowNoAdjustments`) and `eyedropperRing` (boolean, Show Sampling Ring). `ui.inspect` reports them under `toolOptions` (`eyedropper_size`, `eyedropper_sample`, `eyedropper_ring`). The engine command `document.sampleColor {x, y, size, sampleLayer}` returns the colour such a sample picks, as four floats 0..1 (not 0..255). +- `ui.set` also accepts the Eyedropper options bar (#1649): `eyedropperSampleSize` (`"point"` or 1, 3, 5, 11, 31, 51, 101: the side of the averaged square, shared by the Eyedropper, a painting tool's Alt-click eyedropper, the Curves/Color Picker eyedroppers and the Info panel), `eyedropperSample` (`current`, `currentAndBelow`, `all`, `allNoAdjustments`, `currentAndBelowNoAdjustments`) and `eyedropperRing` (boolean, Show Sampling Ring). `ui.inspect` reports them under `toolOptions` (`eyedropper_size`, `eyedropper_sample`, `eyedropper_ring`). The engine command `document.sampleColor {x, y, size, sampleLayer, zoom}` returns the colour such a sample picks, as four floats 0..1 (not 0..255). `zoom` is optional: the view zoom in screen pixels per document pixel (1 = 100 %, a positive number). Without it, an N by N Average reads the N × N square centred on the pixel. With it, the sample matches the Eyedropper at that zoom (#11751): above 100 % it is still the centred square, and at 100 % and below an N by N Average covers (N+1) × (N+1) *screen* pixels, so at 100 % 3 by 3 reads 4 × 4 document pixels and at 50 % 8 × 8. The side in document pixels is (N+1) ÷ `zoom` rounded to the nearest whole pixel, at least N+1 and at most 4096 (at 75 % a 3 by 3 Average reads 5 × 5). The box starts ⌈side ÷ 2⌉ − 1 pixels left of and above the sampled pixel, so an odd side is centred on it and an even side has one pixel more after it than before (at 100 % 3 by 3 reads x−1 … x+2). Like every sample, the box is clipped to the canvas, and a point off the canvas reads transparent. Point Sample reads one pixel at every zoom. To get what the Eyedropper picks, pass its `eyedropperSampleSize` as `size`, its `eyedropperSample` as `sampleLayer` and the document's zoom as `zoom`: left out, `size` is Point Sample (1) and `sampleLayer` is `all`. - `ui.set` also accepts the Crop tool's overlay menu (#1919): `cropOverlay` (`thirds`, `grid`, `diagonal`, `triangle`, `goldenRatio`, `goldenSpiral`), `cropOverlayShow` (`always`: the whole time a crop is pending, the default, as in the reference application; `auto`: only while the crop box is dragged; `never`) and `cropOverlayOrientation` (0..3; Triangle has two orientations and Golden Spiral four, the others ignore it). `ui.inspect` reports them under `toolOptions` (`crop_overlay`, `crop_overlay_show`, `crop_overlay_orientation`). In the app, O cycles the overlay and ⇧O its orientation while the Crop tool shows a box. - `ui.set` also accepts the Pen tools' options bar (#1397): `penMode` (`path` or `shape`) and `penPathOp`, the Path Operations menu (`newLayer`, `combine`, `subtract`, `intersect`, `exclude`): how the next Pen, Freeform Pen or Curvature Pen path joins the selected shape layer (Shape mode; `newLayer` makes a new one) or the targeted vector mask, selected path or Work Path (Path mode, where `newLayer` combines). `ui.inspect` reports them under `toolOptions` (`vector_mode`, `pen_path_op`). Merge Shape Components is the engine command `path.mergeShapeComponents` (work, saved or `layer` path) or `layer.combineShapes.mergeShapeComponents` (shape layers). - `ui.set` also accepts `cropFill` (`background`, the Fill dropdown's first entry, which reads Background (default), or Transparent (default) with Delete Cropped Pixels off, or `contentAware`), the Crop tool's Fill dropdown (#3823, #10872): with `contentAware`, committing a turned or extending frame passes `contentAware: true` to `image.crop`, which fills the area the image doesn't cover from its surroundings. `ui.inspect` reports it as `toolOptions.crop_content_aware`.