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 98ea8b4619..b021ce0cc5 100644 --- a/crates/engine/src/cmd/edit_menu_cmds.rs +++ b/crates/engine/src/cmd/edit_menu_cmds.rs @@ -23,8 +23,12 @@ use crate::{EngineError, Result, Session}; #[derive(Clone, Debug, PartialEq)] pub struct FadeSource { pub doc: DocId, - /// Document revision right after the command; any later change disables Fade. + /// Document revision right after the command, or after a later step that only showed or hid + /// other layers (#13805); any other change disables Fade. pub revision: u64, + /// History id of the state before the command, which Fade blends back towards. Steps that only + /// showed or hid other layers can sit between that state and the current one. + pub before: Option, pub target: FadeTarget, pub label: String, } @@ -70,10 +74,12 @@ fn fadeable(id: &str) -> bool { /// Called after every successful command: remember a fadeable result. pub(crate) fn after_command(s: &mut Session, id: &str, params: &Value) { if !fadeable(id) { + keep_after_visibility(s, id, params); return; } let Some(st) = s.active() else { return }; let label = st.history.undo_label().unwrap_or(id).to_string(); + let before = st.history.past_len().checked_sub(1).and_then(|i| st.history.row_id(i)); let prev = st.history.state(st.history.past_len().wrapping_sub(1)); let prev = prev.as_deref(); let surf_eq = |a: Option<&Surface>, b: Option<&Surface>| match (a, b) { @@ -100,7 +106,7 @@ pub(crate) fn after_command(s: &mut Session, id: &str, params: &Value) { } let channel = channel.filter(|target| prev.is_none_or(|prev| !surf_eq(channel_surface(&st.doc, target), channel_surface(prev, target)))); if let Some(target) = channel { - s.edit_state.fade = Some(FadeSource { doc: st.doc.id, revision: st.revision, target, label }); + s.edit_state.fade = Some(FadeSource { doc: st.doc.id, revision: st.revision, before, target, label }); return; } let Some(layer) = st.active_layer else { return }; @@ -113,7 +119,35 @@ pub(crate) fn after_command(s: &mut Session, id: &str, params: &Value) { && !surf_eq(now.and_then(|l| l.mask.as_ref().map(|m| &m.surface)), was.and_then(|l| l.mask.as_ref().map(|m| &m.surface))) }); let target = if mask { FadeTarget::Mask(layer) } else { FadeTarget::Pixels(layer) }; - s.edit_state.fade = Some(FadeSource { doc: st.doc.id, revision: st.revision, target, label }); + s.edit_state.fade = Some(FadeSource { doc: st.doc.id, revision: st.revision, before, target, label }); +} + +/// Hiding or showing another layer right after a fadeable step keeps Fade available, as in +/// Photoshop (#13805): Fade still blends the step back towards the state before it. A step that +/// shows or hides the faded layer itself leaves Fade disabled. +fn keep_after_visibility(s: &mut Session, id: &str, params: &Value) { + let only_visibility = match id { + "layer.hideLayers" | "layer.showLayers" | "layer.showOnly" => true, + // The Layers panel's eye. + "layer.setProps" => { + params.as_object().is_some_and(|o| o.contains_key("visible") && o.keys().all(|k| matches!(k.as_str(), "layer" | "layers" | "visible" | "coalesce"))) + } + _ => false, + }; + let (Some(st), Some(f)) = (s.active(), s.edit_state.fade.as_ref()) else { return }; + let (FadeTarget::Pixels(layer) | FadeTarget::Mask(layer)) = f.target else { return }; + // Each of these commands changes the document once, so Fade was available right before it. + if !only_visibility || f.doc != st.doc.id || f.revision.checked_add(1) != Some(st.revision) { + return; + } + let visible = |doc: &Document| doc.layer(layer).map(|l| l.visible); + if fade::before_state(st, f).is_none_or(|before| visible(&before) != visible(&st.doc)) { + return; + } + let revision = st.revision; + if let Some(f) = s.edit_state.fade.as_mut() { + f.revision = revision; + } } /// Tile identity of a surface (pointer equality of its COW tiles). @@ -329,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 ), @@ -415,3 +449,7 @@ pub fn custom_shapes(s: &Session) -> &[CustomShape] { #[cfg(test)] #[path = "edit_menu_cmds/tests.rs"] mod tests; + +#[cfg(test)] +#[path = "edit_menu_cmds/fade_visibility_tests.rs"] +mod fade_visibility_tests; diff --git a/crates/engine/src/cmd/edit_menu_cmds/fade.rs b/crates/engine/src/cmd/edit_menu_cmds/fade.rs index ad767c584c..e8c797b212 100644 --- a/crates/engine/src/cmd/edit_menu_cmds/fade.rs +++ b/crates/engine/src/cmd/edit_menu_cmds/fade.rs @@ -1,6 +1,6 @@ use super::{ - BlendMode, Document, EngineError, FadeTarget, Rect, Result, Session, Surface, Value, bad, blend_from_str, f32_or, from_rgba_into, json, str_or, surface_of, - surface_of_mut, to_rgba, + BlendMode, Document, EngineError, FadeSource, FadeTarget, Rect, Result, Session, Surface, Value, bad, blend_from_str, f32_or, from_rgba_into, json, str_or, + surface_of, surface_of_mut, to_rgba, }; // ------------------------------------------------------------------ Fade @@ -8,7 +8,7 @@ use super::{ pub(super) fn can_fade(s: &Session) -> std::result::Result<(), String> { let st = s.active().ok_or("no document open")?; let f = s.edit_state.fade.as_ref().ok_or("nothing to fade")?; - if f.doc != st.doc.id || f.revision != st.revision || !st.history.can_undo() { + if f.doc != st.doc.id || f.revision != st.revision || before_state(st, f).is_none() { return Err("Fade is only available right after a filter, adjustment or painting step".into()); } if surface_of(&st.doc, f.target).is_none() { @@ -20,17 +20,38 @@ pub(super) fn can_fade(s: &Session) -> std::result::Result<(), String> { Ok(()) } +/// The state before the faded step, which Fade blends back towards, while the history holds it. +pub(super) fn before_state(st: &crate::DocState, f: &FadeSource) -> Option> { + let i = st.history.row_of(f.before?)?; + if i < st.history.past_len() { st.history.state(i) } else { None } +} + /// Blend `after` back towards `before` over `area`: `before + opacity × (B(before, after) − before)` -/// with blend mode `mode` (premultiplied, so alpha changes fade too). +/// with blend mode `mode` (premultiplied, so alpha changes fade too). Dissolve instead takes, per +/// pixel, `after` or `before` whole, with `opacity` as the odds of `after`. pub fn fade_surface(before: &Surface, after: &mut Surface, area: Rect, mode: BlendMode, opacity: f32) -> Result<()> { let fmt = after.format(); let n = fmt.channels(); - if area.is_empty() || n == 0 { + let k = opacity.clamp(0.0, 1.0); + // Dissolve at 100 % keeps every pixel of the step's result. + if area.is_empty() || n == 0 || (mode == BlendMode::Dissolve && k >= 1.0) { return Ok(()); } let b = crate::allocation::read_region(before, area, "fading pixels")?; let mut a = crate::allocation::read_region(after, area, "fading pixels")?; - let k = opacity.clamp(0.0, 1.0); + if mode == BlendMode::Dissolve { + // Dissolve: each pixel is the step's result or the pixel before it, alpha included, never + // a mix; the opacity is the odds of the result. The noise follows the pixel's position, + // so the pick is the same across tiles and between the preview and OK (#13809). + let at = (area.y0..area.y1).flat_map(|y| (area.x0..area.x1).map(move |x| (x, y))); + for ((pa, pb), (x, y)) in a.chunks_exact_mut(n).zip(b.chunks_exact(n)).zip(at) { + if photocraft_color::dither_noise(x, y) >= k { + pa.copy_from_slice(pb); + } + } + after.try_write_region(area, &a)?; + return Ok(()); + } let lerp_premul = |pb: &[f32], pa: &[f32], out: &mut [f32], alpha: bool| { let m = out.len(); if !alpha { @@ -84,7 +105,7 @@ fn fade_job(s: &Session, p: &Value) -> Result { let opacity = f32_or(p, "opacity", 100.0).clamp(0.0, 100.0) / 100.0; let mode = blend_from_str(str_or(p, "mode", "normal")).ok_or_else(|| bad(cmd, "unknown blend mode"))?; let st = s.active().ok_or(EngineError::NoDocument)?; - let prev = st.history.past_len().checked_sub(1).and_then(|i| st.history.state(i)).ok_or_else(|| bad(cmd, "no previous state"))?; + let prev = before_state(st, &src).ok_or_else(|| bad(cmd, "no previous state"))?; let before = surface_of(&prev, src.target).cloned().ok_or_else(|| EngineError::Other("the layer or channel did not exist before this step".into()))?; let now = surface_of(&st.doc, src.target).ok_or_else(|| EngineError::Other("the faded layer or channel no longer exists".into()))?; if now.format() != before.format() { @@ -135,3 +156,7 @@ pub fn fade_preview(s: &Session, p: &Value) -> Result { let doc = Document::clone(&s.active().ok_or(EngineError::NoDocument)?.doc); Ok(FadePreview { doc, job }) } + +#[cfg(test)] +#[path = "fade_dissolve_tests.rs"] +mod dissolve_tests; diff --git a/crates/engine/src/cmd/edit_menu_cmds/fade_dissolve_tests.rs b/crates/engine/src/cmd/edit_menu_cmds/fade_dissolve_tests.rs new file mode 100644 index 0000000000..012b7cbc8f --- /dev/null +++ b/crates/engine/src/cmd/edit_menu_cmds/fade_dissolve_tests.rs @@ -0,0 +1,130 @@ +//! #13809: Edit › Fade in Dissolve picks, per pixel, the pixel before the step or the step's +//! result, never a mix of the two; the opacity is the odds of the result. + +use super::*; + +const W: i32 = 400; +const H: i32 = 300; + +fn bounds() -> Rect { + Rect::new(0, 0, W, H) +} + +/// The issue's test document: white Background plus an opaque layer `Paint` of four blocks and a +/// yellow square. +fn blocks_session(depth: u32) -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": W, "height": H, "depth": depth, "background": "white"})).unwrap(); + s.execute("layer.new.layer", json!({"name": "Paint"})).unwrap(); + s.edit("paint", |doc, active| { + let surf = doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap(); + surf.fill_rect(Rect::new(0, 0, 200, 150), &[1.0, 0.0, 0.0, 1.0]); + surf.fill_rect(Rect::new(200, 0, 400, 150), &[0.0, 128.0 / 255.0, 1.0, 1.0]); + surf.fill_rect(Rect::new(0, 150, 200, 300), &[64.0 / 255.0, 200.0 / 255.0, 64.0 / 255.0, 1.0]); + surf.fill_rect(Rect::new(200, 150, 400, 300), &[128.0 / 255.0, 128.0 / 255.0, 128.0 / 255.0, 1.0]); + surf.fill_rect(Rect::new(50, 50, 150, 150), &[1.0, 1.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + s +} + +/// The active layer's pixels over the canvas, one `channels`-long run per pixel. +fn layer_pixels(doc: &Document, s: &Session) -> (Vec, usize) { + let surf = doc.layer(s.active().unwrap().active_layer.unwrap()).unwrap().surface().unwrap(); + let mut out = vec![0.0; (W * H) as usize * surf.channels()]; + surf.read_region_into(bounds(), &mut out); + (out, surf.channels()) +} + +fn active_pixels(s: &Session) -> (Vec, usize) { + layer_pixels(&s.active().unwrap().doc, s) +} + +/// How many pixels are exactly the step's result; panics on a pixel that is neither the base +/// nor the result. +fn count_picks(base: &[f32], top: &[f32], faded: &[f32], n: usize, what: &str) -> usize { + let mut picked = 0; + for (i, ((b, t), f)) in base.chunks_exact(n).zip(top.chunks_exact(n)).zip(faded.chunks_exact(n)).enumerate() { + if f == t { + picked += 1; + } else { + assert_eq!(f, b, "{what}: pixel ({}, {}) is a mix of {b:?} and {t:?}", i % W as usize, i / W as usize); + } + } + picked +} + +#[test] +fn dissolve_picks_the_base_or_the_inverted_pixel_at_every_depth() { + for depth in [8, 16, 32] { + let mut s = blocks_session(depth); + let (base, n) = active_pixels(&s); + s.execute("image.adjustments.invert", json!({})).unwrap(); + let (top, _) = active_pixels(&s); + s.execute("edit.fade", json!({"opacity": 37, "mode": "dissolve"})).unwrap(); + let (faded, _) = active_pixels(&s); + let picked = count_picks(&base, &top, &faded, n, &format!("depth {depth}")); + let share = picked as f64 / f64::from(W * H); + assert!((share - 0.37).abs() <= 0.03, "depth {depth}: {:.1} % of the pixels took the inverted value", share * 100.0); + assert_eq!(s.active().unwrap().history.undo_label(), Some("Fade Invert")); + } +} + +#[test] +fn dissolve_at_100_is_normal_at_100_and_at_0_leaves_the_base() { + for depth in [8, 16, 32] { + let faded = |opacity: u32, mode: &str| { + let mut s = blocks_session(depth); + let (base, _) = active_pixels(&s); + s.execute("image.adjustments.invert", json!({})).unwrap(); + let (top, _) = active_pixels(&s); + s.execute("edit.fade", json!({"opacity": opacity, "mode": mode})).unwrap(); + (base, top, active_pixels(&s).0) + }; + let (_, top, dissolve_full) = faded(100, "dissolve"); + assert!(dissolve_full == top, "depth {depth}: Dissolve 100 % is the step's result"); + assert!(dissolve_full == faded(100, "normal").2, "depth {depth}: Dissolve 100 % equals Normal 100 %"); + let (base, _, dissolve_none) = faded(0, "dissolve"); + assert!(dissolve_none == base, "depth {depth}: Dissolve 0 % leaves the base"); + } +} + +/// A blurred red square on a transparent layer: each pixel takes the blurred value, alpha +/// included, or keeps the one before the blur, so the soft edge never becomes half as opaque. +#[test] +fn dissolve_picks_alpha_with_the_colour() { + let mut s = Session::new(); + s.execute("file.new", json!({"width": W, "height": H, "depth": 8, "background": "white"})).unwrap(); + s.execute("layer.new.layer", json!({"name": "T"})).unwrap(); + s.edit("paint", |doc, active| { + doc.layer_mut(active.unwrap()).unwrap().surface_mut().unwrap().fill_rect(Rect::new(150, 100, 250, 200), &[1.0, 0.0, 0.0, 1.0]); + Ok(()) + }) + .unwrap(); + let (base, n) = active_pixels(&s); + s.execute("filter.blur.gaussianBlur", json!({"radius": 10})).unwrap(); + let (top, _) = active_pixels(&s); + s.execute("edit.fade", json!({"opacity": 50, "mode": "dissolve"})).unwrap(); + let (faded, _) = active_pixels(&s); + count_picks(&base, &top, &faded, n, "blurred square"); + // Along y = 150, outside the square's left edge: alpha 0 or the blur's, both seen. + let alpha = |px: &[f32], x: usize| px[(150 * W as usize + x) * n + n - 1]; + let row: Vec = (130..150).map(|x| alpha(&faded, x)).collect(); + assert!(row.iter().zip(130..150).all(|(&a, x)| a == 0.0 || a == alpha(&top, x)), "{row:?}"); + assert!(row.contains(&0.0) && row.iter().any(|&a| a > 0.0), "both picks along the edge: {row:?}"); +} + +/// The pick depends only on the pixel's position, so the dialog's preview is what OK applies +/// and the same params give the same pattern again. +#[test] +fn dissolve_preview_is_what_ok_applies() { + let mut s = blocks_session(8); + s.execute("image.adjustments.invert", json!({})).unwrap(); + let p = json!({"opacity": 37, "mode": "dissolve"}); + let preview = fade_preview(&s, &p).and_then(FadePreview::render).unwrap(); + let again = fade_preview(&s, &p).and_then(FadePreview::render).unwrap(); + assert!(layer_pixels(&preview, &s).0 == layer_pixels(&again, &s).0, "the same params give the same pattern"); + s.execute("edit.fade", p).unwrap(); + assert!(layer_pixels(&preview, &s).0 == active_pixels(&s).0, "the preview is what OK applies"); +} diff --git a/crates/engine/src/cmd/edit_menu_cmds/fade_visibility_tests.rs b/crates/engine/src/cmd/edit_menu_cmds/fade_visibility_tests.rs new file mode 100644 index 0000000000..a534a927e0 --- /dev/null +++ b/crates/engine/src/cmd/edit_menu_cmds/fade_visibility_tests.rs @@ -0,0 +1,119 @@ +//! #13805: hiding or showing another layer after a fadeable step keeps Edit › Fade available, as in +//! Photoshop; other steps in between still disable it. + +use super::*; +use photocraft_doc::LayerId; + +/// A command and its params, given the Background and the faded layer. +type Step = (&'static str, fn(LayerId, LayerId) -> Value); + +/// A white Background and a layer `Paint` with a black square, made active and blurred: +/// (session, Background, Paint, Paint's edge pixel before the blur). +fn blurred() -> (Session, LayerId, LayerId, Vec) { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 48, "depth": 8, "background": "white"})).unwrap(); + let bg = s.active().unwrap().active_layer.unwrap(); + let paint = LayerId(s.execute("layer.new.layer", json!({"name": "Paint"})).unwrap()["layer"].as_u64().unwrap()); + s.execute("select.rect", json!({"x": 16, "y": 16, "width": 16, "height": 16})).unwrap(); + s.execute("edit.fill", json!({"color": "#000000"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + let sharp = pixel(&s, paint); + s.execute("filter.blur.gaussianBlur", json!({"radius": 3})).unwrap(); + assert_ne!(pixel(&s, paint), sharp, "the blur changed the edge pixel"); + assert!(s.is_enabled("edit.fade"), "Fade follows the blur"); + (s, bg, paint, sharp) +} + +fn pixel(s: &Session, layer: LayerId) -> Vec { + s.active().unwrap().doc.layer(layer).unwrap().surface().unwrap().pixel(16, 20) +} + +fn visible(s: &Session, layer: LayerId) -> bool { + s.active().unwrap().doc.layer(layer).unwrap().visible +} + +/// Hiding the Background after the blur, by each way of hiding it, with visibility changes +/// recorded in History or not: Fade stays available and fades the blur towards the square as it +/// was before the blur, and the Background stays hidden. +#[test] +fn hiding_another_layer_keeps_fade() { + let hides: [Step; 3] = [ + ("layer.hideLayers", |bg, _| json!({"layer": bg.0})), + ("layer.setProps", |bg, _| json!({"layer": bg.0, "visible": false})), + ("layer.showOnly", |_, _| json!({})), + ]; + for undoable in [true, false] { + for (hide, params) in hides { + let (mut s, bg, paint, sharp) = blurred(); + s.execute("history.options", json!({"makeLayerVisibilityChangesUndoable": undoable})).unwrap(); + assert!(s.is_enabled("edit.fade"), "History Options don't touch the document"); + let steps = s.active().unwrap().history.past_len(); + + s.execute(hide, params(bg, paint)).unwrap(); + assert!(!visible(&s, bg), "{hide} undoable={undoable}: the Background is hidden"); + assert_eq!(s.active().unwrap().history.past_len(), steps + usize::from(undoable), "{hide} undoable={undoable}"); + assert!(s.is_enabled("edit.fade"), "{hide} undoable={undoable}: Fade stays available"); + let preview = fade_preview(&s, &json!({"opacity": 0})).and_then(FadePreview::render).unwrap(); + assert_eq!(preview.layer(paint).unwrap().surface().unwrap().pixel(16, 20), sharp, "{hide} undoable={undoable}: the preview fades the blur"); + + s.execute("edit.fade", json!({"opacity": 0})).unwrap(); + assert_eq!(pixel(&s, paint), sharp, "{hide} undoable={undoable}: 0 % fades the blur away"); + assert!(!visible(&s, bg), "{hide} undoable={undoable}: Fade leaves the Background hidden"); + assert_eq!(s.active().unwrap().history.undo_label(), Some("Fade Gaussian Blur")); + assert!(!s.is_enabled("edit.fade"), "{hide} undoable={undoable}: Fade can't repeat"); + } + } +} + +/// Showing the hidden layer again keeps Fade available too, and Fade at 50 % lands halfway +/// between the square before the blur and after it. +#[test] +fn hiding_and_showing_another_layer_keeps_fade() { + let (mut s, bg, paint, sharp) = blurred(); + let blurred_px = pixel(&s, paint); + s.execute("layer.hideLayers", json!({"layer": bg.0})).unwrap(); + s.execute("layer.showLayers", json!({"layer": bg.0})).unwrap(); + assert!(s.is_enabled("edit.fade")); + s.execute("edit.fade", json!({"opacity": 50})).unwrap(); + let half = pixel(&s, paint); + for c in 0..half.len() { + assert!((half[c] - (sharp[c] + blurred_px[c]) / 2.0).abs() < 0.01, "channel {c}: {half:?} between {sharp:?} and {blurred_px:?}"); + } +} + +/// Selecting another layer, or a step that is neither fadeable nor a visibility change, disables +/// Fade as before. +#[test] +fn other_steps_still_disable_fade() { + let steps: [Step; 4] = [ + ("layer.select", |bg, _| json!({"layer": bg.0})), + ("select.all", |_, _| json!({})), + ("view.colorSamplers.add", |_, _| json!({"x": 15, "y": 15})), + ("layer.setProps", |_, paint| json!({"layer": paint.0, "opacity": 0.5})), + ]; + for (step, params) in steps { + let (mut s, bg, paint, _) = blurred(); + s.execute(step, params(bg, paint)).unwrap(); + assert!(!s.is_enabled("edit.fade"), "{step}: Fade is disabled"); + assert!(s.execute("edit.fade", json!({})).is_err(), "{step}"); + // A visibility change afterwards doesn't bring it back. + s.execute("layer.hideLayers", json!({"layer": bg.0})).unwrap(); + assert!(!s.is_enabled("edit.fade"), "{step}, then a hide: Fade stays disabled"); + } + // A hide together with another property is not a visibility change only. + let (mut s, bg, _, _) = blurred(); + s.execute("layer.setProps", json!({"layer": bg.0, "visible": false, "name": "Back"})).unwrap(); + assert!(!s.is_enabled("edit.fade"), "a hide with a rename disables Fade"); +} + +/// Hiding the faded layer itself was not measured in the reference: Fade stays disabled, by itself +/// and when a later step shows the layer again. +#[test] +fn hiding_the_faded_layer_disables_fade() { + let (mut s, _, paint, _) = blurred(); + s.execute("layer.hideLayers", json!({})).unwrap(); + assert!(!visible(&s, paint), "Hide Layers hid the active, faded layer"); + assert!(!s.is_enabled("edit.fade")); + s.execute("layer.showLayers", json!({"layer": paint.0})).unwrap(); + assert!(!s.is_enabled("edit.fade"), "showing it again doesn't bring Fade back"); +} 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/image_cmds.rs b/crates/engine/src/cmd/image_cmds.rs index 898c71c981..318b5dbad2 100644 --- a/crates/engine/src/cmd/image_cmds.rs +++ b/crates/engine/src/cmd/image_cmds.rs @@ -318,6 +318,12 @@ fn image_size(s: &mut Session, p: &Value) -> Result { Method::Automatic if nw > ow || nh > oh => Resample::PreserveDetails, Method::Automatic => Resample::BicubicSharper, }; + // Resampling to a new pixel size drops the selection rather than scaling it, as Photoshop + // does (#13856); undo brings it back with the old size. Taken before the resample so it + // isn't scaled for nothing. A resolution-only change (returned above) keeps it. + if (nw, nh) != (ow, oh) { + doc.selection = None; + } crate::canvas_geom::keeping_count_points(doc, |doc| resample_doc_with_styles(doc, "image.imageSize", nw, nh, filter, scale_styles)) })?; // The size the document has now: without resampling `width`/`height` are ignored (#1815). @@ -1293,3 +1299,7 @@ pub fn specs() -> Vec { #[cfg(test)] mod tests; + +#[cfg(test)] +#[path = "image_size_drops_selection_tests.rs"] +mod image_size_drops_selection_tests; diff --git a/crates/engine/src/cmd/image_cmds/tests.rs b/crates/engine/src/cmd/image_cmds/tests.rs index 4d0478eccb..5acec8b8ba 100644 --- a/crates/engine/src/cmd/image_cmds/tests.rs +++ b/crates/engine/src/cmd/image_cmds/tests.rs @@ -205,8 +205,20 @@ fn image_size_keeps_canvas_edges_opaque() { let mut s = Session::new(); s.execute("file.new", json!({"width": 30, "height": 20, "depth": depth, "background": "#336699"})).unwrap(); s.execute("select.all", json!({})).unwrap(); + // The Crop tool's W x H x Resolution mode still resamples the selection with the + // pixels: a full selection keeps reaching the canvas edges. + let mut cropped = (*doc(&s)).clone(); + let ch = (20 * w + 15) / 30; + resample_doc(&mut cropped, "test", w, ch, Resample::Bicubic).unwrap(); + let sel = cropped.selection.as_ref().unwrap(); + let (x1, y1) = (cropped.size.width as i32 - 1, cropped.size.height as i32 - 1); + for (x, y) in [(0, 0), (x1, 0), (0, y1), (x1, y1)] { + assert!(sel.pixel(x, y)[0] > 0.99, "{depth} {resample}: selection at ({x},{y})"); + } s.execute("image.imageSize", json!({"width": w, "resample": resample})).unwrap(); let d = doc(&s); + // Image Size drops the selection when it resamples (#13856). + assert!(d.selection.is_none(), "{depth} {resample}: Image Size dropped the selection"); let flat = photocraft_compose::flatten(d); let (w, h) = (flat.rect.width() as usize, flat.rect.height() as usize); let mid = flat.px[(h / 2) * w + w / 2]; @@ -215,11 +227,6 @@ fn image_size_keeps_canvas_edges_opaque() { let off = p.iter().zip(mid).map(|(a, b)| (a - b).abs()).fold(0.0f32, f32::max); assert!(off < 0.01, "{depth} {resample} {w}: {p:?} vs {mid:?}"); } - let sel = d.selection.as_ref().unwrap(); - let (x1, y1) = (d.size.width as i32 - 1, d.size.height as i32 - 1); - for (x, y) in [(0, 0), (x1, 0), (0, y1), (x1, y1)] { - assert!(sel.pixel(x, y)[0] > 0.99, "{depth} {resample}: selection at ({x},{y})"); - } } } } diff --git a/crates/engine/src/cmd/image_size_drops_selection_tests.rs b/crates/engine/src/cmd/image_size_drops_selection_tests.rs new file mode 100644 index 0000000000..825331a1a0 --- /dev/null +++ b/crates/engine/src/cmd/image_size_drops_selection_tests.rs @@ -0,0 +1,83 @@ +//! #13856: Fit Image and Image Size drop the active selection when they resample to a new pixel +//! size, as the reference application does; undo brings back the old size and selection in one +//! step. A Fit Image that changes nothing and a resolution-only Image Size keep the selection. + +use photocraft_geom::Rect; +use serde_json::{Value, json}; + +use crate::Session; + +/// The issue's document: 400 x 300 px with a 10,10 50 x 50 selection. +fn doc() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 400, "height": 300})).unwrap(); + s.execute("select.rect", json!({"x": 10, "y": 10, "width": 50, "height": 50})).unwrap(); + s +} + +fn size(s: &Session) -> (u32, u32) { + let d = &s.active().unwrap().doc; + (d.size.width, d.size.height) +} + +fn selection(s: &Session) -> Option { + s.active().unwrap().doc.selection.as_ref().map(|sel| sel.content_bounds()) +} + +fn steps(s: &Session) -> usize { + s.active().unwrap().history.past_len() +} + +#[test] +fn fit_image_that_resizes_drops_the_selection_and_undo_restores_it() { + let mut s = doc(); + let before = selection(&s); + assert_eq!(before, Some(Rect::from_xywh(10, 10, 50, 50))); + let n = steps(&s); + let r = s.execute("file.automate.fitImage", json!({"width": 200, "height": 200})).unwrap(); + assert_eq!(r["changed"], Value::Bool(true)); + assert_eq!(size(&s), (200, 150)); + assert_eq!(selection(&s), None, "no selection after Fit Image"); + assert_eq!(steps(&s), n + 1, "one history step"); + s.undo(); + assert_eq!(size(&s), (400, 300), "undo restores the size"); + assert_eq!(selection(&s), before, "and the selection, in the same step"); +} + +#[test] +fn image_size_with_a_new_pixel_size_drops_the_selection_and_undo_restores_it() { + let mut s = doc(); + let before = selection(&s); + let n = steps(&s); + s.execute("image.imageSize", json!({"width": 200, "height": 150, "resample": "bicubic"})).unwrap(); + assert_eq!(size(&s), (200, 150)); + assert_eq!(selection(&s), None, "no selection after Image Size"); + assert_eq!(steps(&s), n + 1, "one history step"); + s.undo(); + assert_eq!(size(&s), (400, 300)); + assert_eq!(selection(&s), before); +} + +#[test] +fn fit_image_that_changes_nothing_keeps_the_selection_and_adds_no_step() { + for p in [json!({"width": 400, "height": 300}), json!({"width": 800, "height": 800, "dontEnlarge": true})] { + let mut s = doc(); + let before = selection(&s); + let n = steps(&s); + let r = s.execute("file.automate.fitImage", p.clone()).unwrap(); + assert_eq!(r["changed"], Value::Bool(false), "{p}"); + assert_eq!(size(&s), (400, 300), "{p}"); + assert_eq!(selection(&s), before, "{p}: selection kept"); + assert_eq!(steps(&s), n, "{p}: no history step"); + } +} + +#[test] +fn image_size_with_only_a_new_resolution_keeps_the_selection() { + let mut s = doc(); + let before = selection(&s); + s.execute("image.imageSize", json!({"resolution": 300, "resample": "none"})).unwrap(); + assert_eq!(size(&s), (400, 300)); + assert_eq!(s.active().unwrap().doc.resolution_dpi, 300.0); + assert_eq!(selection(&s), before, "a resolution-only change keeps the selection"); +} diff --git a/crates/engine/src/cmd/path_edit_cmds.rs b/crates/engine/src/cmd/path_edit_cmds.rs index 06d63eb119..3d01e8294e 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)); } @@ -292,11 +298,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( @@ -839,3 +845,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/engine/src/cmd/web_cmds/quick.rs b/crates/engine/src/cmd/web_cmds/quick.rs index afe499ffdb..4341a7ed97 100644 --- a/crates/engine/src/cmd/web_cmds/quick.rs +++ b/crates/engine/src/cmd/web_cmds/quick.rs @@ -106,6 +106,9 @@ pub(super) fn quick_export(s: &mut Session, p: &Value) -> Result { "jpg" => { o.insert("format".into(), json!("jpeg")); o.insert("quality".into(), json!(prefs.jpeg_quality.min(100))); + // Quick Export JPGs are progressive (SOF2) at every quality, as the reference + // application writes them; Save for Web keeps its own checkbox (#13787). + o.insert("progressive".into(), json!(true)); } "gif" => { o.insert("format".into(), json!("gif")); @@ -150,3 +153,7 @@ pub(super) fn quick_export(s: &mut Session, p: &Value) -> Result { crate::automate_cmds::fire_event(s, "export"); Ok(json!({"path": path, "format": fmt, "bytes": opt.bytes.len(), "warnings": web_warnings(&st, exif, wdoc.resolution_dpi)})) } + +#[cfg(test)] +#[path = "quick_jpg_progressive_tests.rs"] +mod quick_jpg_progressive_tests; diff --git a/crates/engine/src/cmd/web_cmds/quick_jpg_progressive_tests.rs b/crates/engine/src/cmd/web_cmds/quick_jpg_progressive_tests.rs new file mode 100644 index 0000000000..e394d3483c --- /dev/null +++ b/crates/engine/src/cmd/web_cmds/quick_jpg_progressive_tests.rs @@ -0,0 +1,108 @@ +//! Quick Export writes progressive JPGs (SOF2) at every quality, as the reference application +//! does, while Save for Web keeps its own Progressive checkbox, off by default (#13787). + +use super::*; + +fn tmp(name: &str) -> String { + let d = std::env::temp_dir().join(format!("photocraft-quick-jpg-{}-{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 64×48 8-bit document: a white background with a flat blue block over its left half. +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 64, "height": 48, "depth": 8, "name": "quick.psd", "background": "white"})).unwrap(); + s.execute("select.rect", json!({"x": 0, "y": 0, "width": 32, "height": 48})).unwrap(); + s.execute("edit.fill", json!({"color": "#3366cc"})).unwrap(); + s.execute("select.deselect", json!({})).unwrap(); + s +} + +/// The marker of the file's frame header (0xC0 baseline, 0xC2 progressive), found by walking the +/// marker segments in front of the first scan. +fn sof_marker(bytes: &[u8]) -> Option { + let mut i = 2; + while i + 4 <= bytes.len() { + if bytes[i] != 0xFF { + return None; + } + let m = bytes[i + 1]; + if (0xC0..=0xCF).contains(&m) && !matches!(m, 0xC4 | 0xC8 | 0xCC) { + return Some(m); + } + if m == 0xDA { + return None; + } + let len = usize::from(u16::from_be_bytes([bytes[i + 2], bytes[i + 3]])); + i += 2 + len; + } + None +} + +fn rgba8(bytes: &[u8]) -> Vec { + let img = photocraft_codecs::decode(bytes).unwrap(); + assert_eq!(img.dimensions(), (64, 48)); + img.convert(photocraft_codecs::ChannelLayout::Rgba, photocraft_codecs::SampleType::U8).data().to_vec() +} + +fn max_channel_diff(a: &[u8], b: &[u8]) -> u8 { + assert_eq!(a.len(), b.len()); + a.iter().zip(b).map(|(x, y)| x.abs_diff(*y)).max().unwrap_or(0) +} + +#[test] +fn quick_export_jpg_is_progressive_at_every_quality() { + let dir = tmp("every_quality"); + let mut s = session(); + s.execute("file.export.exportPreferences", json!({"quickExportFormat": "jpg"})).unwrap(); + let convert = s.prefs().export.convert_to_srgb; + for q in [1, 14, 29, 43, 57, 71, 85, 100] { + s.execute("file.export.exportPreferences", json!({"jpegQuality": q})).unwrap(); + let quick = format!("{dir}/quick-{q}.jpg"); + s.execute("file.export.quickExport", json!({"path": quick})).unwrap(); + let quick = std::fs::read(&quick).unwrap(); + assert_eq!(sof_marker(&quick), Some(0xC2), "Quick Export at quality {q} is progressive"); + + // Only the scan layout changed: Save for Web's progressive output at the same settings + // decodes to the same pixels. + let settings = json!({"format": "jpeg", "quality": q, "metadata": "copyright", "convertToSrgb": convert, "matte": "#ffffff"}); + let web = format!("{dir}/web-{q}.jpg"); + let mut p = settings.clone(); + p["progressive"] = json!(true); + p["path"] = json!(web); + s.execute("file.export.saveForWebLegacy", p).unwrap(); + let diff = max_channel_diff(&rgba8(&quick), &rgba8(&std::fs::read(&web).unwrap())); + assert!(diff <= 2, "quality {q}: Quick Export and Save for Web pixels differ by {diff}"); + + // Save for Web keeps its own checkbox, off by default: baseline. + let baseline = format!("{dir}/baseline-{q}.jpg"); + let mut p = settings; + p["path"] = json!(baseline); + s.execute("file.export.saveForWebLegacy", p).unwrap(); + assert_eq!(sof_marker(&std::fs::read(&baseline).unwrap()), Some(0xC0), "Save for Web at quality {q} stays baseline by default"); + } +} + +#[test] +fn quick_export_jpg_opens_again_with_the_same_pixels() { + let dir = tmp("round_trip"); + let mut s = session(); + s.execute("file.export.exportPreferences", json!({"quickExportFormat": "jpg"})).unwrap(); + // The default quality, then the highest. + for q in [None, Some(100)] { + if let Some(q) = q { + s.execute("file.export.exportPreferences", json!({"jpegQuality": q})).unwrap(); + } + let path = format!("{dir}/round-{}.jpg", q.map_or_else(|| "default".to_string(), |q| q.to_string())); + s.execute("file.export.quickExport", json!({"path": path})).unwrap(); + let bytes = std::fs::read(&path).unwrap(); + assert_eq!(sof_marker(&bytes), Some(0xC2)); + // The blue half ends on a block edge, so every pixel is flat colour. + for (i, got) in rgba8(&bytes).as_chunks::<4>().0.iter().enumerate() { + let want = if i % 64 < 32 { [0x33, 0x66, 0xcc, 255] } else { [255, 255, 255, 255] }; + assert!(max_channel_diff(got, &want) <= 2, "quality {q:?}, pixel ({}, {}): {got:?}, want {want:?}", i % 64, i / 64); + } + } +} diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index d4ce67ba24..240a64f994 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -2117,7 +2117,7 @@ fn draw_default_tool_cursor(app: &mut PhotocraftApp, ui: &mut egui::Ui, input: & } // Preferences › Cursors › Other Cursors: Precise shows a crosshair for every tool. Tool::Move if crate::move_mods::copying(app, alt) => egui::CursorIcon::Copy, - Tool::Move | Tool::Type | Tool::VerticalType | Tool::HorizontalTypeMask | Tool::VerticalTypeMask + Tool::Move | Tool::Type | Tool::VerticalType | Tool::HorizontalTypeMask | Tool::VerticalTypeMask | Tool::Ruler if app.session.prefs().cursors.other == photocraft_engine::prefs::OtherCursor::Precise => { egui::CursorIcon::Crosshair @@ -2147,6 +2147,11 @@ fn draw_default_tool_cursor(app: &mut PhotocraftApp, ui: &mut egui::Ui, input: & } egui::CursorIcon::None } + // The Ruler tool: its own arrow with a ruler below right of the tip, and that arrow with a + // protractor over the end point an ⌥-drag takes for the protractor arm (#12037). ⌘ is not + // here: it makes the Ruler the temporary Move tool (`hold_keys::cmd_moves`), so this match + // runs with `Tool::Move` and shows its pointer, on the ruler and off it. + Tool::Ruler => crate::tool_cursor::ruler(app, painter, p, xf.to_doc(p), crate::workspace_ui::sticky_mods(app, ui.input(|i| i.modifiers))), _ => egui::CursorIcon::Crosshair, }; let icon = visible_crosshair(icon, painter, p, cfg!(not(target_arch = "wasm32"))); diff --git a/crates/ui-egui/src/canvas/tool_cursor.rs b/crates/ui-egui/src/canvas/tool_cursor.rs index 37cf404357..400346ceb7 100644 --- a/crates/ui-egui/src/canvas/tool_cursor.rs +++ b/crates/ui-egui/src/canvas/tool_cursor.rs @@ -274,6 +274,68 @@ pub(crate) fn path_type(painter: &Painter, at: Pos2) -> CursorIcon { outline(painter, at, path_type_rings(), false) } +/// The Ruler tool's pointer (#12037). A small arrow with a ruler below right of its tip, and the +/// same arrow with a protractor's angle mark over an end point with ⌥ — the same hit test a press +/// makes its decision with (`analysis_ui::ruler_end_at`), so the angle mark shows exactly where an +/// ⌥-drag starts the protractor arm. The hotspot is the arrow's tip, so the point a press takes is +/// the pointer itself. `CursorIcon::None` with the shape painted where a backend takes no bitmap, +/// as for the other tool pointers. +pub(crate) fn ruler(app: &crate::PhotocraftApp, painter: &Painter, at: Pos2, doc: [f64; 2], mods: egui::Modifiers) -> CursorIcon { + outline(painter, at, ruler_rings(mods.alt && crate::analysis_ui::ruler_end_at(app, doc)), false) +} + +/// The Ruler cursors' geometry, in points round the hotspot on the arrow's tip: the arrowhead, +/// then the glyph below right of it. Our own artwork, in the same outlined pair the other tool +/// pointers use. +fn ruler_rings(protractor: bool) -> Vec> { + let mut rings = vec![ruler_arrow()]; + rings.extend(if protractor { protractor_glyph() } else { straightedge_glyph() }); + rings +} + +/// The arrowhead: tip on the hotspot, body towards the lower right as a plain pointer's sits, with +/// the notch in its back. +fn ruler_arrow() -> Vec { + let d = std::f32::consts::FRAC_1_SQRT_2; + let (along, side) = (vec2(d, d), vec2(-d, d)); + let (base, notch, half) = (along * 11.5, along * 4.6, 3.6); + vec![Vec2::ZERO, base + side * half, notch, base - side * half] +} + +/// A ticked straightedge below right of the arrow's tip: the bar and three ticks off its upper edge. +fn straightedge_glyph() -> Vec> { + let (along, side) = (vec2(0.948_7, 0.316_2), vec2(-0.316_2, 0.948_7)); + let (from, len, half) = (vec2(10.5, 12.5), 12.0, 2.4); + let to = from + along * len; + let mut rings = vec![vec![from + side * half, to + side * half, to - side * half, from - side * half]]; + for t in [0.3, 0.55, 0.8] { + let edge = from + along * (len * t) - side * half; + rings.push(open_ring(&[edge, edge + side * 1.7])); + } + rings +} + +/// A protractor's angle mark below right of the arrow's tip: two arms out of one vertex and the arc +/// between them. +fn protractor_glyph() -> Vec> { + let vertex = vec2(9.0, 19.5); + let arc: Vec = (0..=6) + .map(|i| { + let a = i as f32 * std::f32::consts::FRAC_PI_4 / 6.0; + vertex + vec2(a.cos(), -a.sin()) * 4.5 + }) + .collect(); + vec![open_ring(&[vertex, vertex + vec2(11.0, 0.0)]), open_ring(&[vertex, vertex + vec2(7.8, -7.8)]), open_ring(&arc)] +} + +/// A ring through `pts` and back again: [`Shape::Outline`] closes its rings, so an open line has to +/// list its points both ways instead of gaining the chord back to its start. +fn open_ring(pts: &[Vec2]) -> Vec { + let mut ring = pts.to_vec(); + ring.extend(pts.get(1..pts.len().saturating_sub(1)).unwrap_or(&[]).iter().rev().copied()); + ring +} + /// Can this pass show an OS cursor bitmap? eframe's immediate viewports and its web integration /// don't upload cursor images; every desktop root viewport does (winit custom cursors). Wayland at /// any scale but 1 doesn't either: winit sizes the bitmap there with a `wp_viewport` destination @@ -916,6 +978,9 @@ fn rasterize_pipette_svg(icon: &str, scale: f32, side: u16, hot: u16) -> Result< Ok(CustomCursorImage { rgba: Arc::from(rgba), size: [side, side], hotspot: [hot, hot] }) } +#[cfg(test)] +mod ruler_tests; + #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/canvas/tool_cursor/ruler_tests.rs b/crates/ui-egui/src/canvas/tool_cursor/ruler_tests.rs new file mode 100644 index 0000000000..94f45f9b5d --- /dev/null +++ b/crates/ui-egui/src/canvas/tool_cursor/ruler_tests.rs @@ -0,0 +1,298 @@ +//! The Ruler tool's own pointers (#12037). Away from the ruler, over its line or one of its end +//! points without ⌥, and with ⇧: a small arrow with a ruler below right of its tip. Over an end +//! point with ⌥ — where an ⌥-drag starts the protractor arm: the same arrow with a protractor's +//! angle mark, from the very hit test a press uses. ⌘ turns the Ruler into the temporary Move tool +//! (`hold_keys::cmd_moves`), so it keeps the Move pointer on and off the ruler. The hotspot is the +//! arrow's tip; the artwork is our own geometry, an OS cursor bitmap that is painted where a +//! backend takes no bitmap. + +use egui::{CursorIcon, CustomCursorImage, Modifiers, Shape as EShape, Vec2, vec2}; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::analysis_ui::Drag; +use crate::canvas::ToolEvent; +use crate::state::Tool; + +use super::{CursorLifecycle, Shape, native_scale, rasterize, ruler_arrow, ruler_rings}; + +/// The document's ruler, and a point well clear of it. +const START: [f64; 2] = [80.0, 120.0]; +const END: [f64; 2] = [260.0, 220.0]; +const AWAY: [f64; 2] = [340.0, 60.0]; +/// The point the pointer sits on in a bare frame. +const ON: egui::Pos2 = egui::Pos2::new(100.0, 80.0); + +/// A document with the Ruler tool and one ruler drawn in it, at `zoom`. +fn ruler_app(zoom: f32) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 400, "height": 400})).unwrap(); + app.run("image.analysis.rulerTool", json!({"start": START, "end": END, "protractor": null})).unwrap(); + app.ui.views[0].zoom = zoom; + app.ui.tool = Tool::Ruler; + app.sync_views(); + app +} + +/// One cursor pass with no renderer: the pointer the app asks for, and what it drew. +fn cursor_frame(app: &PhotocraftApp, doc: [f64; 2], mods: Modifiers) -> egui::FullOutput { + let ctx = egui::Context::default(); + ctx.add_plugin(CursorLifecycle); + let mut output = ctx.run_ui(Default::default(), |ui| { + let icon = super::ruler(app, ui.painter(), ON, doc, mods); + ui.ctx().set_cursor_icon(icon); + }); + // These tests read the cursor output, never a renderer. + output.textures_delta.clear(); + output +} + +fn alpha(image: &CustomCursorImage, x: u16, y: u16) -> u8 { + image.rgba[(usize::from(y) * usize::from(image.size[0]) + usize::from(x)) * 4 + 3] +} + +/// The Ruler tool's pointer as its bitmap: `protractor` is the angle mark over an end point. +fn bitmap(protractor: bool, scale: f32) -> CustomCursorImage { + let shape = Shape::Outline { rings: ruler_rings(protractor).into(), centre: false }; + rasterize(&shape, scale).expect("the ruler cursor rasterizes") +} + +/// The inked pixels of a bitmap as points round its hotspot, so a claim about the artwork does not +/// depend on the display scale. +fn ink(image: &CustomCursorImage, scale: f32) -> Vec { + let side = usize::from(image.size[0]); + let hot = f32::from(image.hotspot[0]); + image + .rgba + .as_chunks::<4>() + .0 + .iter() + .enumerate() + .filter(|(_, p)| p[3] > 0) + .map(|(i, _)| vec2((i % side) as f32 - hot, (i / side) as f32 - hot) / scale) + .collect() +} + +/// The ink within 8 pt of the hotspot: the arrowhead alone, wherever the glyph is. +fn arrow_ink(image: &CustomCursorImage) -> Vec<(i32, i32)> { + ink(image, 1.0).into_iter().filter(|p| p.length() <= 8.0).map(|p| (p.x.round() as i32, p.y.round() as i32)).collect() +} + +/// Assert two bitmaps are the same picture, reporting the difference in words rather than in +/// thousands of bytes. +fn assert_same_bitmap(got: &CustomCursorImage, want: &CustomCursorImage, what: &str) { + assert_eq!(got.size, want.size, "{what}: the bitmap size"); + assert_eq!(got.hotspot, want.hotspot, "{what}: the hotspot"); + let differs = got.rgba.iter().zip(want.rgba.iter()).filter(|(a, b)| a != b).count(); + assert_eq!(differs, 0, "{what}: {differs} of {} bytes differ from the pointer module's own picture", got.rgba.len()); +} + +#[test] +fn ruler_bitmaps_put_the_arrow_tip_on_the_hotspot_at_each_scale() { + for scale in [1.0, 1.25, 2.0] { + for protractor in [false, true] { + let image = bitmap(protractor, scale); + let [x, y] = image.hotspot; + assert_eq!(image.size, [2 * x + 1, 2 * y + 1]); + assert!(alpha(&image, x, y) > 100, "{protractor}: the arrow's tip is on the hotspot"); + let painted = ink(&image, scale); + let reach = painted.iter().fold(0.0f32, |m, p| m.max(p.length())); + assert!(reach <= 30.0, "{protractor} at {scale}: nothing reaches further than 30 pt from the tip, {reach} does"); + // Above and left of the tip there is nothing to show: that is where the pointer is. + let stray: Vec<_> = painted.iter().filter(|p| p.x + p.y <= -3.0).copied().collect(); + assert!(stray.is_empty(), "{protractor} at {scale}: the glyph stays below right of the tip, {stray:?}"); + assert!(painted.iter().any(|p| p.x > 12.0 && p.y > 12.0), "{protractor}: a glyph below right of the arrow"); + let pixels = image.rgba.as_chunks::<4>().0; + assert!(pixels.iter().any(|p| p[3] > 230 && p[0] > 230), "a light cursor"); + assert!(pixels.iter().any(|p| p[3] > 100 && p[0] < 25), "with a dark outline, readable on white"); + } + } +} + +#[test] +fn the_protractor_cursor_is_the_same_arrow_with_a_different_glyph() { + let ruler = bitmap(false, 1.0); + let protractor = bitmap(true, 1.0); + assert_ne!(ruler.rgba, protractor.rgba, "the angle mark is not the ruler"); + let alone = rasterize(&Shape::Outline { rings: vec![ruler_arrow()].into(), centre: false }, 1.0).expect("the arrowhead alone rasterizes"); + let want = arrow_ink(&alone); + assert!(!want.is_empty(), "the arrowhead is inked by its tip"); + for (image, what) in [(&ruler, "the ruler"), (&protractor, "the protractor")] { + assert_eq!(arrow_ink(image), want, "{what}: the same arrowhead round the tip"); + } +} + +/// Where a backend takes no cursor bitmap the shape is painted at the pointer, its tip on it. +#[test] +fn the_ruler_pointer_is_painted_at_the_pointer_without_a_bitmap() { + let ctx = egui::Context::default(); + for protractor in [false, true] { + let mut output = ctx.run_ui(Default::default(), |ui| { + super::paint(ui.painter(), ON, &Shape::Outline { rings: ruler_rings(protractor).into(), centre: false }); + }); + output.textures_delta.clear(); + let paths: Vec<_> = output.shapes.iter().filter_map(|s| if let EShape::Path(p) = &s.shape { Some(p) } else { None }).collect(); + assert!(paths.len() >= 4, "{protractor}: the arrow and its glyph are drawn, got {}", paths.len()); + assert!(paths.iter().any(|p| p.closed && p.points.first().is_some_and(|q| *q == ON)), "{protractor}: an arrowhead with its tip on the pointer"); + assert!(paths.iter().any(|p| p.points.iter().all(|q| (*q - ON).length() > 11.0)), "{protractor}: and a glyph clear of it"); + } +} + +/// The state table, as the canvas match asks for it: the arrow with its ruler everywhere but over +/// an end point with ⌥, where the angle mark takes the ruler's place. The hotspot of both is the +/// arrow's tip, which is what the pointer sits on. +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn every_ruler_state_gets_its_pointer() { + let app = ruler_app(1.0); + let scale = native_scale(&egui::Context::default()); + let mid = [(START[0] + END[0]) / 2.0, (START[1] + END[1]) / 2.0]; + for (doc, mods, protractor, what) in [ + (AWAY, Modifiers::NONE, false, "away from the ruler"), + (mid, Modifiers::NONE, false, "over the line"), + (END, Modifiers::NONE, false, "over an end"), + (START, Modifiers::NONE, false, "over the other end"), + (AWAY, Modifiers::SHIFT, false, "with ⇧"), + (mid, Modifiers::SHIFT, false, "over the line with ⇧"), + (mid, Modifiers::ALT, false, "over the line with ⌥"), + (AWAY, Modifiers::ALT, false, "away from the ruler with ⌥"), + (END, Modifiers::ALT, true, "over an end with ⌥"), + (START, Modifiers::ALT, true, "over the other end with ⌥"), + ] { + let out = cursor_frame(&app, doc, mods); + let image = out.platform_output.cursor_image.unwrap_or_else(|| panic!("{what}: the Ruler's own pointer is a bitmap cursor")); + assert_same_bitmap(&image, &bitmap(protractor, scale), what); + assert_eq!(out.platform_output.cursor_icon, CursorIcon::Crosshair, "{what}: a bitmap marks itself None, with a visible fallback"); + } +} + +/// ⌘ makes the Ruler the temporary Move tool, so the canvas' cursor match runs with `Tool::Move` +/// and shows the Move pointer — held on the ruler and off it (#12037; #9933 draws the four-way +/// cross Photoshop shows for it). +#[test] +fn ctrl_handed_to_the_ruler_is_the_move_tool() { + let app = ruler_app(1.0); + assert!(crate::hold_keys::cmd_moves(Tool::Ruler), "⌘ is the Move tool with the Ruler"); + let ctx = egui::Context::default(); + let mut input = egui::RawInput::default(); + input.events.push(egui::Event::ModifiersChanged(Modifiers::COMMAND)); + let mut out = ctx.run_ui(input, |_| {}); + out.textures_delta.clear(); + assert_eq!(crate::hold_keys::held_tool(&app, &ctx), Some(crate::hold_keys::Temporary::Move), "⌘ held over the canvas"); + assert_eq!(crate::hold_keys::Temporary::Move.tool(), Tool::Move, "and the cursor match runs with the Move tool's own arm"); +} + +/// The ⌥ pointer shows exactly where an ⌥-drag starts the protractor arm: the cursor's hit test and +/// a press agree at every zoom, because they are the same `dist` with the same grab radius, in +/// screen points. +#[test] +fn the_protractor_pointer_marks_exactly_where_an_alt_press_takes_the_end() { + for zoom in [0.5f32, 1.0, 2.0] { + // Past the end along its own line, in screen points: the grab radius is 7 of them. + for (reach, takes_the_end) in [(3.0, true), (12.0, false)] { + let app = ruler_app(zoom); + let mut pressed = ruler_app(zoom); + let p = [END[0] + reach / f64::from(app.point_zoom().max(0.01)), END[1]]; + crate::analysis_ui::pointer(&mut pressed, ToolEvent::Down { x: p[0], y: p[1], pressure: 1.0 }, Modifiers::ALT); + assert_eq!(crate::analysis_ui::ruler_end_at(&app, p), takes_the_end, "{reach} pt past the end at {zoom}: the cursor"); + assert_eq!(pressed.ui.analysis.drag == Some(Drag::RulerHandle(2)), takes_the_end, "{reach} pt past the end at {zoom}: an ⌥-press"); + } + } +} + +/// Without a ruler there is no end point to mark, and an ⌥-press starts a new ruler. +#[test] +fn an_empty_document_has_no_end_to_mark() { + let mut app = ruler_app(1.0); + app.run("image.analysis.rulerTool", json!({"clear": true})).unwrap(); + assert!(app.session.active().is_some_and(|d| d.doc.measurement.ruler.is_none())); + assert!(!crate::analysis_ui::ruler_end_at(&app, START), "no ruler, no end point"); + crate::analysis_ui::pointer(&mut app, ToolEvent::Down { x: START[0], y: START[1], pressure: 1.0 }, Modifiers::ALT); + assert!(matches!(app.ui.analysis.drag, Some(Drag::RulerNew(_))), "and a press there starts a new ruler"); +} + +/// Over an end point without ⌥ the press grabs that end, so the plain ruler pointer stays. +#[test] +fn over_an_end_without_alt_the_press_grabs_the_end() { + let mut app = ruler_app(1.0); + assert!(crate::analysis_ui::ruler_end_at(&app, END), "the end is a grab target"); + crate::analysis_ui::pointer(&mut app, ToolEvent::Down { x: END[0], y: END[1], pressure: 1.0 }, Modifiers::NONE); + assert_eq!(app.ui.analysis.drag, Some(Drag::RulerHandle(1)), "and a press there drags it"); +} + +/// The live canvas: with the Ruler tool it hands the OS the arrow-and-ruler bitmap, the angle mark +/// over an end with ⌥, and the Move tool's pointer under ⌘. +#[test] +#[cfg(not(target_arch = "wasm32"))] +fn the_canvas_gives_the_ruler_tool_its_own_pointer() { + use egui::{Event, vec2}; + use egui_kittest::Harness; + + let mut h = Harness::builder().with_size(vec2(900.0, 700.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + // Nothing to lay out before the font stack is in: an early pass draws no label at all. + let ctx = ui.ctx().clone(); + if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + }, + ruler_app(1.0), + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(4); + if !h.ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + eprintln!("skipped: no font stack, so the canvas cannot be laid out here"); + return; + } + let scale = native_scale(&h.ctx); + let at = |h: &Harness<'static, PhotocraftApp>, doc: [f64; 2]| { + crate::canvas::ViewXform::active(h.state()).expect("a document with a view").to_screen(doc[0] as f32, doc[1] as f32) + }; + let hover = |h: &mut Harness<'static, PhotocraftApp>, doc: [f64; 2], mods: Modifiers| { + h.event(Event::ModifiersChanged(mods)); + h.event(Event::PointerMoved(at(h, doc))); + h.run_steps(2); + h.output().platform_output.cursor_image.clone() + }; + for (doc, mods, protractor, what) in [ + (AWAY, Modifiers::NONE, false, "away from the ruler"), + (END, Modifiers::ALT, true, "over an end with ⌥"), + (AWAY, Modifiers::NONE, false, "back away from it"), + ] { + let image = hover(&mut h, doc, mods).unwrap_or_else(|| panic!("{what}: the canvas shows the Ruler's own pointer")); + assert_same_bitmap(&image, &bitmap(protractor, scale), what); + } + for doc in [AWAY, END] { + h.event(Event::ModifiersChanged(Modifiers::COMMAND)); + h.event(Event::PointerMoved(at(&h, doc))); + h.run_steps(2); + assert!(h.output().platform_output.cursor_image.is_none(), "{doc:?}: ⌘ shows no Ruler bitmap"); + assert_eq!(h.output().platform_output.cursor_icon, CursorIcon::Default, "{doc:?}: the Move tool's pointer"); + } + // Preferences › Cursors › Other Cursors = Precise: the Ruler keeps the plain crosshair, as + // the Move and Type tools do; its own arrow is a nice-to-have, not a precise pointer (#12037 review). + let mut app = ruler_app(1.0); + app.run("prefs.set", json!({"values": {"cursors.other": "precise"}})).unwrap(); + let mut hp = Harness::builder().with_size(vec2(900.0, 700.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let ctx = ui.ctx().clone(); + if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + }, + app, + ); + PhotocraftApp::setup_context(&hp.ctx, crate::theme::ThemeKind::ALL[0]); + hp.run_steps(4); + for doc in [AWAY, END] { + hp.event(Event::ModifiersChanged(Modifiers::NONE)); + hp.event(Event::PointerMoved(crate::canvas::ViewXform::active(hp.state()).expect("a view").to_screen(doc[0] as f32, doc[1] as f32))); + hp.run_steps(2); + // The icon is the point: Precise asks for the plain crosshair, exactly as the Move and + // Type arms do; the small bitmap that rides with it on native is the cursor pipeline's + // visible crosshair fallback, not the Ruler's arrow-and-ruler art of the phases above. + assert_eq!(hp.output().platform_output.cursor_icon, CursorIcon::Crosshair, "{doc:?}: Precise keeps the crosshair"); + } +} diff --git a/crates/ui-egui/src/dialogs.rs b/crates/ui-egui/src/dialogs.rs index e22931d190..17b8b99580 100644 --- a/crates/ui-egui/src/dialogs.rs +++ b/crates/ui-egui/src/dialogs.rs @@ -632,6 +632,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { let mut drag = egui::Vec2::ZERO; let mut close_clicked = false; let mut sizing = false; + 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), @@ -724,8 +725,10 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { crate::widgets::hairline(ui); ui.add_space(8.0); crate::field_tab::begin(ui.ctx()); - if let Some(done) = dialog_body(app, ui, &d, &mut fields, id, interactive) { - outcome = Some(done); + 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) { @@ -791,6 +794,7 @@ pub fn show(app: &mut PhotocraftApp, ctx: &egui::Context) { { outcome = Some(false); } + 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; } @@ -1171,6 +1175,7 @@ fn confirm_command_more(app: &mut PhotocraftApp, d: Dialog) -> Result Result { confirm_preflight(app, 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 => { @@ -1312,12 +1317,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; @@ -1337,6 +1346,8 @@ pub mod new_guide_ui; pub mod new_layer_ui; pub mod open_prompt; pub mod palette; +#[cfg(test)] +mod paths_export_default_tests; pub(crate) mod pattern_fill_ui; pub mod preset_group_prompt; pub mod rasterize_prompt; 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/file_ui.rs b/crates/ui-egui/src/dialogs/file_ui.rs index a04e070a79..ab8213265c 100644 --- a/crates/ui-egui/src/dialogs/file_ui.rs +++ b/crates/ui-egui/src/dialogs/file_ui.rs @@ -143,7 +143,11 @@ pub fn invoke(app: &mut PhotocraftApp, ctx: &egui::Context, id: &str, params: &V } names.extend(d.doc.paths.iter().map(|p| p.name.clone())); } - form(app, id, "Export Paths to File", json!({"path": format!("{dir}/{stem}.ai"), "paths": "all"}), json!({"paths": names})) + // Opens on the Paths panel's selected row, as the reference application does (#13777). + // A shape layer's path ("layer") is not an entry yet, and a row the document no longer + // has falls back to All Paths. + let paths = app.ui.selected_path.as_deref().filter(|s| *s != "layer" && names.iter().any(|n| n == s)).unwrap_or("all").to_string(); + form(app, id, "Export Paths to File", json!({"path": format!("{dir}/{stem}.ai"), "paths": paths}), json!({"paths": names})) } _ => return None, })) 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/dialogs/paths_export_default_tests.rs b/crates/ui-egui/src/dialogs/paths_export_default_tests.rs new file mode 100644 index 0000000000..55ba9f74ab --- /dev/null +++ b/crates/ui-egui/src/dialogs/paths_export_default_tests.rs @@ -0,0 +1,89 @@ +//! #13777: File › Export › Paths to Illustrator opens its Paths dropdown on the row that is +//! selected in the Paths panel, as the reference application does: a saved path or the Work +//! Path when that row is selected, All Paths when no row is (or the row is gone), and the +//! choice is not remembered between openings. The shape layer's path is not an entry yet +//! (#13774), so that row keeps today's All Paths. + +use crate::PhotocraftApp; +use serde_json::{Value, json}; + +const COMMAND: &str = "file.export.pathsToIllustrator"; + +/// A document with a Work Path and two saved paths, "Curve A" and "Curve B". +fn app_with_paths() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 200, "height": 150})).unwrap(); + let path = |x: f64| json!({"subpaths": [{"closed": true, "knots": [[x, 10.0], [x + 40.0, 10.0], [x + 40.0, 50.0]]}]}); + for (name, x) in [("Curve A", 10.0), ("Curve B", 60.0), ("work", 110.0)] { + app.run("path.set", json!({"name": name, "path": path(x)})).unwrap(); + } + app +} + +/// Opens the dialog as the menu item does and returns its id and the preselected entry. +fn open(app: &mut PhotocraftApp) -> (u64, Value) { + let r = super::file_ui::invoke(app, &egui::Context::default(), COMMAND, &json!({})).unwrap().unwrap(); + let id = r["dialog"].as_u64().unwrap(); + let paths = app.ui.dialog_mut(id).unwrap().fields["paths"].clone(); + (id, paths) +} + +#[test] +fn a_selected_saved_path_is_preselected() { + let mut app = app_with_paths(); + app.ui.selected_path = Some("Curve B".into()); + assert_eq!(open(&mut app).1, "Curve B"); +} + +#[test] +fn the_selected_work_path_is_preselected() { + let mut app = app_with_paths(); + app.ui.selected_path = Some("work".into()); + assert_eq!(open(&mut app).1, "work"); +} + +#[test] +fn no_selected_row_preselects_all_paths() { + let mut app = app_with_paths(); + app.ui.selected_path = None; + assert_eq!(open(&mut app).1, "all"); +} + +#[test] +fn a_row_the_document_no_longer_has_preselects_all_paths() { + let mut app = app_with_paths(); + app.ui.selected_path = Some("Deleted path".into()); + assert_eq!(open(&mut app).1, "all"); + app.run("path.delete", json!({"name": "work"})).unwrap(); + app.ui.selected_path = Some("work".into()); + assert_eq!(open(&mut app).1, "all", "a selected Work Path the document no longer has"); +} + +/// The layer path entry does not exist yet (#13774): that row keeps today's default. +#[test] +fn the_shape_layer_path_row_keeps_all_paths() { + let mut app = app_with_paths(); + app.ui.selected_path = Some("layer".into()); + assert_eq!(open(&mut app).1, "all"); +} + +#[test] +fn the_choice_is_not_remembered_between_openings() { + let mut app = app_with_paths(); + app.ui.selected_path = Some("Curve A".into()); + let (id, paths) = open(&mut app); + assert_eq!(paths, "Curve A"); + app.ui.dialog_mut(id).unwrap().fields.insert("paths".into(), json!("work")); + app.ui.close_dialog(id); + app.ui.selected_path = Some("Curve B".into()); + assert_eq!(open(&mut app).1, "Curve B"); +} + +/// The dropdown's entries and the command's parameter values stay as they are. +#[test] +fn the_entries_keep_their_parameter_values() { + let mut app = app_with_paths(); + let (id, _) = open(&mut app); + let choices = app.ui.dialog_mut(id).unwrap().fields["__choices"]["paths"].clone(); + assert_eq!(choices, json!(["all", "work", "Curve A", "Curve B"])); +} diff --git a/crates/ui-egui/src/input/shortcuts.rs b/crates/ui-egui/src/input/shortcuts.rs index 855029df3b..f82cbf11ce 100644 --- a/crates/ui-egui/src/input/shortcuts.rs +++ b/crates/ui-egui/src/input/shortcuts.rs @@ -860,7 +860,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/analysis_ui.rs b/crates/ui-egui/src/tools/analysis_ui.rs index e75d2a8b2b..6da8b1fe5a 100644 --- a/crates/ui-egui/src/tools/analysis_ui.rs +++ b/crates/ui-egui/src/tools/analysis_ui.rs @@ -242,6 +242,19 @@ fn dist(a: [f64; 2], b: [f64; 2]) -> f64 { (a[0] - b[0]).hypot(a[1] - b[1]) } +/// Is `p` within the grab radius `tol` of one of `r`'s end points? +fn near_end(r: Ruler, p: [f64; 2], tol: f64) -> bool { + dist(p, r.start) <= tol || dist(p, r.end) <= tol +} + +/// Is the pointer at document point `p` over the ruler's end points? The very hit test a press +/// makes its decision with ([`near_end`], `dist` with [`tolerance`]), so the Ruler tool's ⌥ pointer +/// shows exactly where an ⌥-drag starts the protractor arm (#12037). +pub(crate) fn ruler_end_at(app: &PhotocraftApp, p: [f64; 2]) -> bool { + let tol = tolerance(app); + app.session.active().is_some_and(|d| d.doc.measurement.ruler.is_some_and(|r| near_end(r, p, tol))) +} + /// Shift constrains to 45° steps around `from`, as the reference does (#11985): on a diagonal step /// both legs take the smaller of |dx| and |dy| (signs kept), on a 0° or 90° step the dominant /// component stays and the other becomes 0, so the ruler never gets longer than the pointer's legs. @@ -309,7 +322,7 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> let near = |q: [f64; 2]| dist(p, q) <= tol; match cur { // ⌥-drag from an end point starts the protractor arm at that vertex. - Some(mut r) if mods.alt && (near(r.start) || near(r.end)) => { + Some(mut r) if mods.alt && near_end(r, p, tol) => { if near(r.end) && !near(r.start) { std::mem::swap(&mut r.start, &mut r.end); } diff --git a/crates/ui-egui/src/tools/direct_select.rs b/crates/ui-egui/src/tools/direct_select.rs index bd331d5e59..65cda59164 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) => { @@ -1010,6 +1013,9 @@ mod convert_point_drag_segment_tests; #[cfg(test)] mod delete_key_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 53925235ae..f99b952da6 100644 --- a/crates/ui-egui/src/tools/vector_ui.rs +++ b/crates/ui-egui/src/tools/vector_ui.rs @@ -227,6 +227,8 @@ mod paint_tests; #[cfg(test)] mod triangle_box_geometry_tests; +#[cfg(test)] +mod triangle_properties_fields_tests; #[cfg(test)] mod pen_resume_tests; @@ -255,6 +257,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`.