diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index d1efb21c08..298dd4bf87 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -1,6 +1,10 @@ name: Release on: + # A nightly dry run on main: every release build except macOS, nothing signed or released + # (craft-common-actions release.yml `dry-run`). Finds release-only breakage before release day. + schedule: + - cron: "28 2 * * *" push: branches: [release] workflow_dispatch: @@ -30,6 +34,7 @@ jobs: # Intentionally tracked at @main (not SHA-pinned) so org-wide CI improvements, security fixes, and build optimizations propagate without PR churn across all craftapp repos. uses: storytold/craft-common-actions/.github/workflows/release.yml@main with: + dry-run: ${{ github.event_name == 'schedule' }} app-name: photocraft app-title: PhotoCraft craft-fonts-ref: b076417b5880bd4154bd22f00695b1d28c6bea83 diff --git a/ATTRIBUTION.md b/ATTRIBUTION.md index 99a8660929..e9764f8a5e 100644 --- a/ATTRIBUTION.md +++ b/ATTRIBUTION.md @@ -15,8 +15,8 @@ next to them. | `epaint_default_fonts::EGUI_ICONS` (build input; deflated into `OUT_DIR/egui_fonts/egui-icons.ttf.deflate`, registered by `crates/ui-egui/src/text/egui_fonts.rs`) | egui-icons, five-glyph subset of emoji-icon-font | John Slegers | [egui fork at 6d518fc](https://github.com/storytold/egui/tree/6d518fc799681571963842f95b55a6b68431b15a/crates/epaint_default_fonts/fonts), [original](https://github.com/jslegers/emoji-icon-font); egui subset, unmodified here | MIT; Copyright (c) 2014 John Slegers; full upstream notice in [NOTICE](NOTICE) | | `assets/fonts/Inter-Regular.ttf`, `Inter-Medium.ttf`, `Inter-SemiBold.ttf` | Inter 4.001 (UI font) | The Inter Project Authors (Rasmus Andersson) | | SIL OFL 1.1, [`assets/fonts/OFL-Inter.txt`](assets/fonts/OFL-Inter.txt) | | `assets/fonts/JetBrainsMono-Regular.ttf` | JetBrains Mono 2.305 (numeric font) | The JetBrains Mono Project Authors | | SIL OFL 1.1, [`assets/fonts/OFL-JetBrainsMono.txt`](assets/fonts/OFL-JetBrainsMono.txt) | -| `assets/icons/*.svg` except `vector-shape.svg`, `slice-knife.svg`, `slice-select.svg`, `font-similar.svg`, `font-variable.svg`, `sampler.svg`, `artboard.svg`, `perspective-crop.svg`, `frame-placeholder.svg`, `ellipse-dashed.svg`, `gradient.svg`, `type-mask.svg`, `type-mask-vertical.svg`, `text-warp.svg`, `clip-below.svg`, `clip-release.svg`, `layer-mask.svg`, `adjustment-layer.svg`, `brush-replace.svg`, `history-brush.svg`, `quick-selection.svg`, `eraser-background.svg`, `eraser-magic.svg`, `lasso-magnetic.svg`, `direct-select.svg`, `convert-point.svg`, `pen-add-anchor.svg`, `pen-delete-anchor.svg`, `pen-freeform.svg`, `pen-curvature.svg`, `bandage-sparkle.svg`, `painting-symmetry.svg`, `symmetry-*.svg`, `path-op-*.svg` and `marquee-{row,column}.svg`, `align-edge-*.svg` and `distribute-*.svg`, `crop-overlay-*.svg`, `vertical-align-*.svg`, `spirit-level.svg` (116 files; `star-filled.svg` is `star.svg` with a solid fill) | Lucide icons | Lucide Icons and Contributors | (`icons/.svg`; `align-*` are now named `text-align-*` upstream) | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | -| `assets/icons/{check,chevron-down,chevron-left,chevron-right,chevron-up,chevrons-left,chevrons-right,circle,clock,compass,info,link,link-2,lock,minus,monitor,moon,move,navigation,plus,search,square,trash,triangle,type,x,zoom-in}.svg` | Lucide icons derived from Feather (subset of the row above) | Cole Bemis (Feather), Lucide Contributors | via Lucide | MIT (Feather) and ISC (Lucide), [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | +| `assets/icons/*.svg` except `vector-shape.svg`, `slice-knife.svg`, `slice-select.svg`, `font-similar.svg`, `font-variable.svg`, `sampler.svg`, `artboard.svg`, `perspective-crop.svg`, `frame-placeholder.svg`, `ellipse-dashed.svg`, `gradient.svg`, `type-mask.svg`, `type-mask-vertical.svg`, `text-warp.svg`, `clip-below.svg`, `clip-release.svg`, `layer-mask.svg`, `adjustment-layer.svg`, `brush-replace.svg`, `history-brush.svg`, `quick-selection.svg`, `eraser-background.svg`, `eraser-magic.svg`, `lasso-magnetic.svg`, `direct-select.svg`, `convert-point.svg`, `pen-add-anchor.svg`, `pen-delete-anchor.svg`, `pen-freeform.svg`, `pen-curvature.svg`, `bandage-sparkle.svg`, `painting-symmetry.svg`, `symmetry-*.svg`, `path-op-*.svg` and `marquee-{row,column}.svg`, `align-edge-*.svg` and `distribute-*.svg`, `crop-overlay-*.svg`, `vertical-align-*.svg`, `spirit-level.svg` (117 files; `star-filled.svg` is `star.svg` with a solid fill) | Lucide icons | Lucide Icons and Contributors | (`icons/.svg`; `align-*` are now named `text-align-*` upstream) | ISC, [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | +| `assets/icons/{check,chevron-down,chevron-left,chevron-right,chevron-up,chevrons-left,chevrons-right,circle,clock,compass,info,link,link-2,lock,minus,monitor,moon,move,navigation,plus,search,square,trash,triangle,type,x,zoom-in,zoom-out}.svg` | Lucide icons derived from Feather (subset of the row above) | Cole Bemis (Feather), Lucide Contributors | via Lucide | MIT (Feather) and ISC (Lucide), [`assets/icons/LICENSE-lucide.txt`](assets/icons/LICENSE-lucide.txt) | | `assets/icons/vector-shape.svg` | Vector path shape-layer glyph with four anchor points | @superplay2021 | Original work for PhotoCraft | MIT OR Apache-2.0 | | `assets/icons/slice-knife.svg` | Slice tool glyph | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | | `assets/icons/slice-select.svg` | Slice Select tool glyph | PhotoCraft contributors | Original work | MIT OR Apache-2.0 | diff --git a/assets/icons/zoom-out.svg b/assets/icons/zoom-out.svg new file mode 100644 index 0000000000..70abec44b4 --- /dev/null +++ b/assets/icons/zoom-out.svg @@ -0,0 +1,15 @@ + + + + + diff --git a/crates/doc/src/vector.rs b/crates/doc/src/vector.rs index 9dc8edf258..390a31bf5f 100644 --- a/crates/doc/src/vector.rs +++ b/crates/doc/src/vector.rs @@ -303,8 +303,8 @@ pub enum LiveShape { rect: [f64; 4], }, /// Regular polygon or star inscribed in `rect`; `star_ratio` = inner/outer radius (1 = polygon). - /// `corner_radius` rounds every vertex (0 = sharp), each within what its edges allow; the - /// Triangle tool draws a 3-sided one. + /// `corner_radius` rounds every vertex of a polygon and the outer points of a star (0 = sharp), + /// each within what its edges allow; the Triangle tool draws a 3-sided one. Polygon { rect: [f64; 4], sides: u32, diff --git a/crates/engine/src/cmd/path_edit_cmds.rs b/crates/engine/src/cmd/path_edit_cmds.rs index 4e8b89f56e..1312347662 100644 --- a/crates/engine/src/cmd/path_edit_cmds.rs +++ b/crates/engine/src/cmd/path_edit_cmds.rs @@ -116,10 +116,11 @@ 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")?; if p.get("curvature").and_then(Value::as_bool).unwrap_or(false) { - return edit_path(s, CMD, p, "Drag Anchor Points", |path| edit::move_anchors_curvature(path, &anchors, d)); + return edit_path(s, CMD, p, label, |path| edit::move_anchors_curvature(path, &anchors, d)); } - edit_path(s, CMD, p, "Drag Anchor Points", |path| edit::move_anchors(path, &anchors, d)) + edit_path(s, CMD, p, label, |path| edit::move_anchors(path, &anchors, d)) } fn move_handle(s: &mut Session, p: &Value) -> Result { @@ -283,7 +284,7 @@ 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)"#.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"? (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.moveHandle", "Drag Direction Point", diff --git a/crates/engine/src/cmd/vector_cmds.rs b/crates/engine/src/cmd/vector_cmds.rs index 4539b22c4f..7d781257fa 100644 --- a/crates/engine/src/cmd/vector_cmds.rs +++ b/crates/engine/src/cmd/vector_cmds.rs @@ -98,7 +98,7 @@ pub fn specs() -> Vec { "New Shape Layer", ["Layer", "New"], leak(format!( - r##"{{"kind":"rect|roundedRect|ellipse|polygon|star|line|path"="rect","rect":[x,y,w,h] (rect/roundedRect/ellipse/polygon/star),"radii":[tl,tr,br,bl]|r (roundedRect=10),"sides":3..100=5,"starRatio":0..1 (star=0.5),"cornerRadius":px=0 (polygon/star: rounds every vertex; the Triangle tool is a 3-sided polygon),"from":[x,y],"to":[x,y],"weight":px=1 (line),"arrowStart":bool=false,"arrowEnd":bool=false,"arrowWidth":px=52,"arrowLength":px=50,"arrowConcavity":0..100=0 (line),"path":{{…}} (kind path),{fill}=foreground,{stroke}=none,"name":str?,"addTo":layerId? + "op":"combine|subtract|intersect|exclude" (append to an existing shape layer)}} → shape.info. {PATH_FORM}"## + r##"{{"kind":"rect|roundedRect|ellipse|polygon|star|line|path"="rect","rect":[x,y,w,h] (rect/roundedRect/ellipse/polygon/star),"radii":[tl,tr,br,bl]|r (roundedRect=10),"sides":3..100=5,"starRatio":0..1 (star=0.5),"cornerRadius":px=0 (polygon: rounds every vertex, star: its outer points; the Triangle tool is a 3-sided polygon),"from":[x,y],"to":[x,y],"weight":px=1 (line),"arrowStart":bool=false,"arrowEnd":bool=false,"arrowWidth":px=52,"arrowLength":px=50,"arrowConcavity":0..100=0 (line),"path":{{…}} (kind path),{fill}=foreground,{stroke}=none,"name":str?,"addTo":layerId? + "op":"combine|subtract|intersect|exclude" (append to an existing shape layer)}} → shape.info. {PATH_FORM}"## )), has_doc, shape_create @@ -372,3 +372,6 @@ pub fn specs() -> Vec { #[cfg(test)] mod tests; + +#[cfg(test)] +mod line_tool_history_name_tests; diff --git a/crates/engine/src/cmd/vector_cmds/line_tool_history_name_tests.rs b/crates/engine/src/cmd/vector_cmds/line_tool_history_name_tests.rs new file mode 100644 index 0000000000..2cf94ff571 --- /dev/null +++ b/crates/engine/src/cmd/vector_cmds/line_tool_history_name_tests.rs @@ -0,0 +1,67 @@ +//! #13244: a Line tool drag is one History step named "Line Tool" in Shape and Path mode; the +//! commands without the tool keep "New Shape Layer" and "Work Path". + +use serde_json::{Value, json}; + +use super::*; + +fn session() -> Session { + let mut s = Session::new(); + s.execute("file.new", json!({"width": 800, "height": 600})).unwrap(); + s +} + +fn steps(s: &Session) -> usize { + s.active().unwrap().history.past_len() +} + +fn last_step(s: &Session) -> Option<&str> { + s.active().unwrap().history.undo_label() +} + +fn line(history_name: Option<&str>) -> Value { + json!({"kind": "line", "from": [400, 300], "to": [600, 400], "weight": 6, "historyName": history_name}) +} + +/// The closed outline a Path-mode Line drag adds to the Work Path. +fn outline(x: f64) -> Value { + json!({"subpaths": [{"knots": [[x, 300.0], [x + 200.0, 300.0], [x + 200.0, 306.0], [x, 306.0]]}]}) +} + +#[test] +fn a_shape_mode_line_is_one_step_named_line_tool() { + let mut s = session(); + let n = steps(&s); + s.execute("shape.create", line(Some("Line Tool"))).unwrap(); + assert_eq!(steps(&s), n + 1); + assert_eq!(last_step(&s), Some("Line Tool")); +} + +#[test] +fn each_path_mode_line_is_one_step_named_line_tool() { + let mut s = session(); + for x in [100.0, 400.0] { + let n = steps(&s); + s.execute("path.set", json!({"name": "work", "path": outline(x), "historyName": "Line Tool"})).unwrap(); + assert_eq!(steps(&s), n + 1); + assert_eq!(last_step(&s), Some("Line Tool")); + } +} + +#[test] +fn without_the_tool_the_commands_keep_their_own_names() { + let mut s = session(); + s.execute("shape.create", line(None)).unwrap(); + assert_eq!(last_step(&s), Some("New Shape Layer")); + s.execute("path.set", json!({"name": "work", "path": outline(100.0)})).unwrap(); + assert_eq!(last_step(&s), Some("Work Path")); +} + +#[test] +fn an_unknown_history_name_is_refused_without_a_step() { + let mut s = session(); + let n = steps(&s); + assert!(s.execute("shape.create", line(Some("Ellipse Tool"))).is_err()); + assert!(s.execute("path.set", json!({"name": "work", "path": outline(100.0), "historyName": 7})).is_err()); + assert_eq!(steps(&s), n); +} diff --git a/crates/engine/src/cmd/vector_cmds/paths.rs b/crates/engine/src/cmd/vector_cmds/paths.rs index 37ab7a3b27..b2e687f174 100644 --- a/crates/engine/src/cmd/vector_cmds/paths.rs +++ b/crates/engine/src/cmd/vector_cmds/paths.rs @@ -73,18 +73,23 @@ pub(super) fn paths_list(s: &Session) -> Result { })) } -/// Only Freeform Pen overrides these shared commands' normal History labels (#12829). +/// The tools that override these shared commands' normal History labels with their own name: +/// Freeform Pen (#12829) and the Line tool (#13244). +const TOOL_HISTORY_NAMES: [&str; 2] = ["Freeform Pen", "Line Tool"]; + /// Validate before editing so malformed automation input cannot change the document. pub(super) fn pen_history_name<'a>(p: &Value, cmd: &str, default: &'a str) -> Result<&'a str> { match p.get("historyName") { None | Some(Value::Null) => Ok(default), - Some(Value::String(n)) if n == "Freeform Pen" => Ok("Freeform Pen"), - Some(_) => Err(bad(cmd, "`historyName` must be \"Freeform Pen\"")), + Some(v) => { + TOOL_HISTORY_NAMES.into_iter().find(|&n| v.as_str() == Some(n)).ok_or_else(|| bad(cmd, "`historyName` must be \"Freeform Pen\" or \"Line Tool\"")) + } } } /// Replaces the Work Path or a saved path, or appends subpaths with the requested operation. -/// The optional Freeform Pen history label overrides the normal Work Path or Save Path label. +/// The optional Freeform Pen or Line Tool history label overrides the normal Work Path or Save +/// Path label. pub(super) fn path_set(s: &mut Session, p: &Value) -> Result { const CMD: &str = "path.set"; let path = parse_path(p.get("path").ok_or_else(|| bad(CMD, "missing `path`"))?).map_err(|e| bad(CMD, e))?; diff --git a/crates/engine/src/cmd/vector_cmds/shape.rs b/crates/engine/src/cmd/vector_cmds/shape.rs index 547ad47eca..8b7055d7e2 100644 --- a/crates/engine/src/cmd/vector_cmds/shape.rs +++ b/crates/engine/src/cmd/vector_cmds/shape.rs @@ -433,7 +433,8 @@ fn default_name(kind: &str) -> &'static str { } /// Creates a shape layer, or adds path components to the shape identified by `addTo`. -/// The Freeform Pen history override labels new layers; additions retain the Add Shape label. +/// The Freeform Pen or Line Tool history override labels new layers; additions retain the Add +/// Shape label. pub(super) fn shape_create(s: &mut Session, p: &Value) -> Result { const CMD: &str = "shape.create"; let label = super::paths::pen_history_name(p, CMD, "New Shape Layer")?; diff --git a/crates/paint/src/mixer_click_empty_layer_tests.rs b/crates/paint/src/mixer_click_empty_layer_tests.rs index 3cde70eef2..6c0ec73cbf 100644 --- a/crates/paint/src/mixer_click_empty_layer_tests.rs +++ b/crates/paint/src/mixer_click_empty_layer_tests.rs @@ -20,7 +20,7 @@ fn click_with(s: &mut Surface, wet: f32, mix: f32, flow: f32) { let mut st = MixerState::default(); st.load([0.0, 0.0, 0.0, 1.0]); let m = MixerSettings { wet, load: 0.75, mix, flow, ..Default::default() }; - apply_mixer_stroke(s, None, &stroke, &m, &mut st, None, false); + apply_mixer_stroke(s, None, &stroke, &m, &mut st, None, false).unwrap(); } fn alpha(s: &Surface, x: i32, y: i32) -> i32 { diff --git a/crates/paint/src/replace_anti_alias_tests.rs b/crates/paint/src/replace_anti_alias_tests.rs index 92bf846f8f..75c0f8d8e9 100644 --- a/crates/paint/src/replace_anti_alias_tests.rs +++ b/crates/paint/src/replace_anti_alias_tests.rs @@ -40,7 +40,7 @@ fn click_with(anti_alias: bool, flow: f32, hardness: f32) -> Surface { color: [0.0, 0.0, 1.0, 1.0], ..Default::default() }; - apply_color_replacement(&mut s, &stroke, &rs, None, false); + apply_color_replacement(&mut s, &stroke, &rs, None, false).unwrap(); s } diff --git a/crates/ui-egui/src/canvas.rs b/crates/ui-egui/src/canvas.rs index c38f6c8d32..91faeb74d4 100644 --- a/crates/ui-egui/src/canvas.rs +++ b/crates/ui-egui/src/canvas.rs @@ -882,7 +882,7 @@ fn handle_dialog_canvas_input(app: &mut PhotocraftApp, input: DialogCanvasInput< } let b = crate::dialogs::free_buttons(input.ctx, input.rect); let pointer = input.ctx.input(|i| i.pointer.latest_pos()); - crate::zoom_tool::drag(app, input.ctx, input.view, input.xf, &b, pointer); + crate::zoom_tool::drag(app, input.ctx, input.view, input.xf, &b, pointer, &zoom_out); if b.clicked && let Some(p) = pointer { @@ -1001,6 +1001,8 @@ struct CanvasToolInput<'a> { under_dialog: bool, menu_dismiss_press: bool, zoom_out: &'a dyn Fn(bool) -> bool, + /// The Animated Zoom direction for ⌥ held or not: `zoom_out` without the Zoom Out mode. + hold_zoom_out: &'a dyn Fn(bool) -> bool, display_zoom: f32, } @@ -1206,7 +1208,7 @@ fn handle_canvas_tool_navigation( // it owns the press: no scrub, and its release is no click step. A menu-dismissal press // must not arm it: holding the dismissal click would zoom (CodeRabbit, #9841). if tool == Tool::Zoom && !transform_owns_pointer { - let out = zoom_out(ui.input(|i| i.modifiers.alt)); + let out = (input.hold_zoom_out)(ui.input(|i| i.modifiers.alt)); let on_canvas = !input.menu_dismiss_press && !input.under_dialog && !over_compass && response.is_pointer_button_down_on(); let hold = crate::zoom_hold::hold_id(idx, primary, ctx.viewport_id()); if crate::zoom_hold::update(ctx, view, xf, app.session.prefs().general.animated_zoom, out, ppp, on_canvas, hold) { @@ -1215,7 +1217,7 @@ fn handle_canvas_tool_navigation( } // Zoom tool drags: scrubby zoom or a zoom rectangle (zoom_tool.rs); clicks step below. // Like the Hand, the selected Zoom yields to an open Free Transform box (#4799). - if tool == Tool::Zoom && !transform_owns_pointer && crate::zoom_tool::drag(app, ctx, view, xf, buttons, response.interact_pointer_pos()) { + if tool == Tool::Zoom && !transform_owns_pointer && crate::zoom_tool::drag(app, ctx, view, xf, buttons, response.interact_pointer_pos(), zoom_out) { (buttons.started, buttons.dragged, buttons.stopped) = (false, false, false); } } @@ -2387,10 +2389,20 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: app.tool_override = (temporary == Some(crate::hold_keys::Temporary::Move)).then_some(Tool::Move); // `~` held: a Brush or Pencil stroke that starts now erases (`tool_event`'s `Down`). app.held_erase = crate::hold_keys::erase_held(app, &ctx); - // Zoom direction: the temporary zoom key decides, else ⌥ (Zoom tool), held or latched in - // Window › Modifier Keys (the way around a desktop that takes Alt+click, `alt_grab`). + // Zoom direction: the temporary zoom key decides, else the Zoom tool's Zoom In / Zoom Out + // mode, turned around by ⌥ held or latched in Window › Modifier Keys (the way around a + // desktop that takes Alt+click, `alt_grab`). A held Z is a temporary zoom key too: in, out + // with ⌥, whatever the mode (#12066). let sticky_alt = app.ui.shell.sticky_alt; + let out_mode = !app.ui.tool_options.zoom_in && !crate::spring_tools::holds(app, Tool::Zoom); let zoom_out = |alt: bool| match temporary { + Some(crate::hold_keys::Temporary::ZoomOut) => true, + Some(crate::hold_keys::Temporary::ZoomIn) => false, + _ => (alt || sticky_alt) != out_mode, + }; + // Animated Zoom (press and hold) keeps its direction in either mode: in, out with ⌥. Zoom + // Out mode was not measured for it (#12066). + let hold_zoom_out = |alt: bool| match temporary { Some(crate::hold_keys::Temporary::ZoomOut) => true, Some(crate::hold_keys::Temporary::ZoomIn) => false, _ => alt || sticky_alt, @@ -2509,6 +2521,7 @@ pub fn canvas_view(app: &mut PhotocraftApp, ui: &mut egui::Ui, idx: usize, rect: under_dialog, menu_dismiss_press, zoom_out: &zoom_out, + hold_zoom_out: &hold_zoom_out, display_zoom: display_view.zoom, }; handle_primary_canvas_input(app, ui, &mut view, &input); diff --git a/crates/ui-egui/src/canvas/zoom_hold.rs b/crates/ui-egui/src/canvas/zoom_hold.rs index 8da4535e01..852e0a6776 100644 --- a/crates/ui-egui/src/canvas/zoom_hold.rs +++ b/crates/ui-egui/src/canvas/zoom_hold.rs @@ -249,6 +249,23 @@ mod tests { assert!(xf(&h).to_screen(doc[0] as f32, doc[1] as f32).distance(p) < 0.5); } + #[test] + fn zoom_out_mode_leaves_the_hold_direction_alone() { + // Zoom Out mode was not measured for Animated Zoom (#12066): a hold still zooms in, and + // out with ⌥, as in Zoom In mode. + for alt in [false, true] { + let held = |zoom_in: bool| { + let mut h = harness(true); + h.state_mut().ui.tool_options.zoom_in = zoom_in; + let p = h.state().last_canvas_rect.center() + vec2(50.0, -30.0); + hold(&mut h, p, 8, alt) + }; + let (zoom_in, zoom_out) = (held(true), held(false)); + assert_eq!(zoom_out, zoom_in, "alt {alt}"); + assert!(zoom_out[4..=8].windows(2).all(|w| (w[1] < w[0]) == alt), "alt {alt}: {zoom_out:?}"); + } + } + #[test] fn a_hold_at_the_zoom_limit_leaves_the_view_alone() { // Zoom Resizes Windows centres the image in a window wrapped around it diff --git a/crates/ui-egui/src/color_swatch_tests.rs b/crates/ui-egui/src/color_swatch_tests.rs index 6a88301859..89ef2514e7 100644 --- a/crates/ui-egui/src/color_swatch_tests.rs +++ b/crates/ui-egui/src/color_swatch_tests.rs @@ -94,7 +94,8 @@ fn note_and_count_colours_open_the_color_picker() { app.ui.tool = Tool::Count; app.run("count.newGroup", json!({})).unwrap(); }); - pick(&mut h, "Color"); + // The Count swatch is "Count group color", its picker "Color Picker (Count Color)" (#11765). + assert_eq!(pick(&mut h, "Count group color"), crate::color_picker_ui::title_for("Count Color")); let st = h.state().session.active().unwrap(); let m = &st.doc.measurement; let g = &m.count_groups[m.active_count_group]; diff --git a/crates/ui-egui/src/icon_data.rs b/crates/ui-egui/src/icon_data.rs index 3dd68269fb..8e32a301c8 100644 --- a/crates/ui-egui/src/icon_data.rs +++ b/crates/ui-egui/src/icon_data.rs @@ -192,4 +192,5 @@ pub static ICONS: &[(&str, &[u8])] = &[ ("wand-sparkles", include_bytes!("../../../assets/icons/wand-sparkles.svg")), ("x", include_bytes!("../../../assets/icons/x.svg")), ("zoom-in", include_bytes!("../../../assets/icons/zoom-in.svg")), + ("zoom-out", include_bytes!("../../../assets/icons/zoom-out.svg")), ]; diff --git a/crates/ui-egui/src/input/shortcuts.rs b/crates/ui-egui/src/input/shortcuts.rs index 742061d835..51970cbe3b 100644 --- a/crates/ui-egui/src/input/shortcuts.rs +++ b/crates/ui-egui/src/input/shortcuts.rs @@ -895,6 +895,9 @@ fn handle_escape_and_view_keys(app: &mut PhotocraftApp, ctx: &egui::Context) { // Rotate View, Adaptive Wide Angle, the Filter Gallery, the TIFF prompt, any open egui popup // and the toolbar tool and "…" flyouts. A canvas drag in progress (a marquee being drawn) keeps it too. let esc_taken = app.drag.is_some() + // A Direct Selection drag (a Cmd-drag on an anchor) never reaches `app.drag`: Esc must not + // leave full screen or deselect pixels while its release is still to come (#13072). + || (app.ui.tool == Tool::DeleteAnchorPoint && app.ui.direct_selection.drag.is_some()) || app.ui.palette_open || app.ui.canvas_tool_menu.is_some() || app.ui.layer_menu.is_some() @@ -923,22 +926,31 @@ fn handle_escape_and_view_keys(app: &mut PhotocraftApp, ctx: &egui::Context) { } return; } - // Delete Anchor Point (#12773): Esc first clears anchors selected on the saved path targeted in - // the Paths panel, then deselects that path, so clicks edit nothing. Not while its name is typed - // in the panel: egui has already dropped the field's focus, and the panel cancels on Esc. + // Delete Anchor Point (#12773): Esc first hides the anchors of the saved path targeted in the + // Paths panel, then deselects that path, so clicks edit nothing. The first Esc leaves the path + // targeted whether or not an anchor was selected (#13072), and clears only anchors selected on + // that path, never another path's. Not while its name is typed in the panel: egui has already + // dropped the field's focus, and the panel cancels on Esc. A Direct Selection drag keeps Esc + // away through `esc_taken` above, so its release still moves the anchors (#13072). if !esc_taken && app.ui.tool == Tool::DeleteAnchorPoint && !crate::vector_ui::path_renaming(app, ctx) && let Some((index, _)) = crate::vector_ui::selected_saved_path_index(app) { let ds = &app.ui.direct_selection; - let selected = ds.target == Some(crate::direct_select::PathRef::Saved(index)) && (!ds.anchors.is_empty() || ds.segment.is_some()); + let on_this_path = ds.target == Some(crate::direct_select::PathRef::Saved(index)); + let selected = on_this_path && (!ds.anchors.is_empty() || ds.segment.is_some()); if pressed(Key::Escape) { - if selected { - app.ui.direct_selection.anchors.clear(); - app.ui.direct_selection.segment = None; + // The stage belongs to this path: choosing another one starts at the first Esc again. + if selected || app.ui.direct_selection.escape_hidden != Some(index) { + if selected { + app.ui.direct_selection.anchors.clear(); + app.ui.direct_selection.segment = None; + } + app.ui.direct_selection.escape_hidden = Some(index); } else { app.ui.selected_path = None; + app.ui.direct_selection.escape_hidden = None; } return; } diff --git a/crates/ui-egui/src/input/spring_tools.rs b/crates/ui-egui/src/input/spring_tools.rs index 5f51136cdb..e87ec56684 100644 --- a/crates/ui-egui/src/input/spring_tools.rs +++ b/crates/ui-egui/src/input/spring_tools.rs @@ -82,6 +82,12 @@ pub fn pressed(app: &mut PhotocraftApp, letter: char, before: Tool, plain: bool, app.ui.spring = (before.key() != letter).then(|| Spring { previous: before, tool, keys: vec![letter], since: now, used: false, released: false }); } +/// Is `tool` in effect only while its letter is held (or its drag finishes)? A tap that turns out +/// permanent has no spring left by then (`tick`). +pub fn holds(app: &PhotocraftApp, tool: Tool) -> bool { + app.ui.tool == tool && app.ui.spring.as_ref().is_some_and(|s| s.tool == tool) +} + /// The canvas was pressed: a held letter's tool becomes temporary. pub fn note_canvas_press(app: &mut PhotocraftApp) { if let Some(s) = app.ui.spring.as_mut().filter(|s| !s.released) { diff --git a/crates/ui-egui/src/panels/options_bar.rs b/crates/ui-egui/src/panels/options_bar.rs index 895e6b0a02..3e9034715e 100644 --- a/crates/ui-egui/src/panels/options_bar.rs +++ b/crates/ui-egui/src/panels/options_bar.rs @@ -789,6 +789,13 @@ fn tool_specific_options(app: &mut PhotocraftApp, ui: &mut egui::Ui, t: Tokens, } Tool::Eyedropper => crate::eyedropper_ui::options(app, ui), Tool::Zoom => { + // Zoom In / Zoom Out: a pair, exactly one pressed; Zoom Out makes a click step out. + for (zoom_in, icon, tip) in [(true, "zoom-in", tl!("Zoom In")), (false, "zoom-out", tl!("Zoom Out"))] { + if icons::button(ui, icon, 24.0, app.ui.tool_options.zoom_in == zoom_in, tip).clicked() { + app.ui.tool_options.zoom_in = zoom_in; + } + } + widgets::vline(ui, 22.0); // Resize Windows to Fit is Preferences › Zoom Resizes Windows itself, as in // Photoshop: one setting, shown in both places (zoom_window_fit.rs). let mut fit = app.session.prefs().general.zoom_resizes_windows; diff --git a/crates/ui-egui/src/state/tool_options.rs b/crates/ui-egui/src/state/tool_options.rs index 0f800645da..18d9c09d48 100644 --- a/crates/ui-egui/src/state/tool_options.rs +++ b/crates/ui-egui/src/state/tool_options.rs @@ -251,6 +251,10 @@ pub struct ToolOptions { /// Zoom tool › Scrubby Zoom: dragging left/right zooms continuously (else a zoom rectangle). #[serde(default = "yes")] pub zoom_scrubby: bool, + /// Zoom tool › Zoom In / Zoom Out: which way a click steps (⌥ turns it around). Reset Tool + /// leaves it, as in Photoshop. + #[serde(default = "yes")] + pub zoom_in: bool, /// Hand tool › Scroll All Windows: a Hand drag pans every shown document view, not only the /// one dragged in (`scroll_all_windows.rs`). Shift held while dragging does the same. #[serde(default)] @@ -506,11 +510,11 @@ impl Default for ToolOptions { shape_stroke_gradient: None, corner_radius: 0.0, polygon_sides: 5, - line_weight: 3.0, + line_weight: 1.0, arrow_start: false, arrow_end: false, - arrow_width: 52.0, - arrow_length: 50.0, + arrow_width: 5.0, + arrow_length: 10.0, arrow_concavity: 0.0, curve_fit: default_curve_fit(), pen_auto_add_delete: true, @@ -557,6 +561,7 @@ impl Default for ToolOptions { cr_tolerance: 30.0, cr_anti_alias: true, zoom_scrubby: true, + zoom_in: true, hand_scroll_all: false, pencil_auto_erase: false, brush_clear: false, diff --git a/crates/ui-egui/src/tools.rs b/crates/ui-egui/src/tools.rs index d62f9542e3..684c8dbc32 100644 --- a/crates/ui-egui/src/tools.rs +++ b/crates/ui-egui/src/tools.rs @@ -71,6 +71,8 @@ mod crop_options_labels_tests; mod gradient_options_bar_mode_tests; #[cfg(test)] mod gradient_refusal_messages_tests; +#[cfg(test)] +mod line_tool_defaults_tests; #[cfg(test)] mod remove_default_size_tests; diff --git a/crates/ui-egui/src/tools/analysis_ui.rs b/crates/ui-egui/src/tools/analysis_ui.rs index 4cbedd29e0..2e78f5ea6b 100644 --- a/crates/ui-egui/src/tools/analysis_ui.rs +++ b/crates/ui-egui/src/tools/analysis_ui.rs @@ -631,48 +631,84 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo let m = &doc.measurement; ui.label(RichText::new(crate::i18n::fmt(tl!("Count: {n}"), &[("n", &count_readout(m))])).color(t.text).size(11.0)); crate::widgets::vline(ui, 22.0); - if !m.count_groups.is_empty() { - let mut gi = m.active_count_group.min(m.count_groups.len() - 1); + // Every control from the start, in Photoshop's order (#11765): group, eye, folder, + // trash, Clear, colour, Marker Size, Label Size. With no group yet the swatch and the + // sizes show what the next new group gets; using them, or the eye, changes nothing + // until there is a group (not measured). + let group = (!m.count_groups.is_empty()).then(|| m.active_count_group.min(m.count_groups.len() - 1)); + let next = photocraft_doc::CountGroup::default(); + let g = group.map_or(&next, |gi| &m.count_groups[gi]); + if let Some(mut gi) = group { let opts: Vec<(usize, &str)> = m.count_groups.iter().enumerate().map(|(i, g)| (i, g.name.as_str())).collect(); - if crate::widgets::dropdown(ui, "count-group", tl!("Group"), &mut gi, &opts, 140.0) { + if crate::widgets::dropdown(ui, "count-group", tl!("Group"), &mut gi, &opts, 150.0) { let _ = app.run("count.setGroup", json!({"group": gi, "active": true})); } - let g = &m.count_groups[gi]; - let eye = if g.visible { "eye" } else { "eye-off" }; - if crate::icons::button(ui, eye, 22.0, false, tl!("Toggle count group visibility")).clicked() { - let _ = app.run("count.setGroup", json!({"group": gi, "visible": !g.visible})); - } - let rgb = g.color.to_rgb(); - // PhotoCraft's Color Picker (sRGB), as everywhere else (#2144). - if crate::widgets::color_swatch_button(ui, color32(rgb), tl!("Color")).clicked() { - crate::color_picker_ui::open_for_command( - app, - &crate::color_picker_ui::title_for(tl!("Color")), - rgb, - "count.setGroup", - json!({"group": gi}), - ); - } - if crate::icons::button(ui, "trash", 22.0, false, tl!("Delete count group")).clicked() { - let _ = app.run("count.deleteGroup", json!({"group": gi})); - } + } else { + ui.add_enabled_ui(false, |ui| crate::widgets::dropdown(ui, "count-group", tl!("Group"), &mut 0usize, &[(0, tl!("Count Group"))], 150.0)); + } + let eye = if g.visible { "eye" } else { "eye-off" }; + if crate::icons::button(ui, eye, 22.0, false, tl!("Toggle visibility of count group")).clicked() + && let Some(gi) = group + { + let _ = app.run("count.setGroup", json!({"group": gi, "visible": !g.visible})); } if crate::icons::button(ui, "folder-plus", 22.0, false, tl!("Create a new count group")).clicked() { let _ = app.run("count.newGroup", json!({})); } - if crate::widgets::secondary_button(ui, tl!("Clear"), 0.0).clicked() && m.count_total() > 0 { + // The last group can't be deleted from here (`count.deleteGroup` still can). + let trash = ui.add_enabled_ui(m.count_groups.len() >= 2, |ui| { + crate::icons::button(ui, "trash", 22.0, false, tl!("Delete the currently selected count group")) + }); + if trash.inner.clicked() + && let Some(gi) = group + { + let _ = app.run("count.deleteGroup", json!({"group": gi})); + } + // Clear acts on a visible current group with markers (`count.clear` itself is unchanged). + let clearable = group.is_some() && g.visible && !g.points.is_empty(); + if ui.add_enabled_ui(clearable, |ui| crate::widgets::secondary_button(ui, tl!("Clear"), 0.0)).inner.clicked() { let _ = app.run("count.clear", json!({})); } - if let Some(g) = m.count_groups.get(m.active_count_group) { - crate::widgets::vline(ui, 22.0); - let (mut ms, mut ls) = (g.marker_size as f32, g.label_size as f32); - ui.label(RichText::new(tl!("Marker Size")).color(t.text_dim).size(11.0)); - let a = crate::widgets::value_field(ui, &mut ms, 1.0..=10.0, "", 40.0).accessible_name(tl!("Marker Size")).changed(); - ui.label(RichText::new(tl!("Label Size")).color(t.text_dim).size(11.0)); - let b = crate::widgets::value_field(ui, &mut ls, 8.0..=72.0, "", 44.0).accessible_name(tl!("Label Size")).changed(); - if a || b { - let _ = app.run("count.setGroup", count_size_params(ms, ls)); + let rgb = g.color.to_rgb(); + // PhotoCraft's Color Picker (sRGB), as everywhere else (#2144). + if crate::widgets::color_swatch_button(ui, color32(rgb), tl!("Count group color")).on_hover_text(tl!("Count group color")).clicked() + && let Some(gi) = group + { + crate::color_picker_ui::open_for_command( + app, + &crate::color_picker_ui::title_for(tl!("Count Color")), + rgb, + "count.setGroup", + json!({"group": gi}), + ); + } + crate::widgets::vline(ui, 22.0); + let (mut ms, mut ls) = (g.marker_size as f32, g.label_size as f32); + // Scrubby captions with colons, as in Photoshop: the options bar's own caption, which + // scrubs the field after it when dragged. The catalogs translate the names without + // the colon (main's captions), so the colon follows the translation. + let caption = |ui: &mut egui::Ui, text: &str| crate::panels::opt_label(ui, &format!("{text}:")); + // Each caption names its field (the scrub link), so a screen reader reads what is shown. + caption(ui, tl!("Marker Size")); + let a = crate::widgets::value_field_whole(ui, &mut ms, 1.0..=10.0, "", 40.0); + caption(ui, tl!("Label Size")); + let b = crate::widgets::value_field_whole(ui, &mut ls, 8.0..=72.0, "", 44.0); + // One undo step per scrub (of a field or its caption), as the Gradient tool's Opacity. + let drag = |r: &egui::Response| { + let key = r.id.with("count-size-drag"); + if r.drag_started() { + let n = ui.ctx().cumulative_pass_nr(); + ui.data_mut(|d| d.insert_temp(key, n)); } + if r.changed() && r.dragged() { ui.data(|d| d.get_temp::(key)).map(|n| format!("count-size:{}:{n}", key.value())) } else { None } + }; + let coalesce = drag(&a).or(drag(&b)); + if (a.changed() || b.changed()) && group.is_some() { + let mut p = count_size_params(ms, ls); + if let Some(k) = coalesce { + p["coalesce"] = json!(k); + } + let _ = app.run("count.setGroup", p); } true } @@ -1261,3 +1297,7 @@ mod note_clear_all_tests; #[cfg(test)] #[path = "analysis_ruler_escape_tests.rs"] mod analysis_ruler_escape_tests; + +#[cfg(test)] +#[path = "count_options_bar_tests.rs"] +mod count_options_bar_tests; diff --git a/crates/ui-egui/src/tools/anchor_tools.rs b/crates/ui-egui/src/tools/anchor_tools.rs index 909b892220..4f1b4c1e2b 100644 --- a/crates/ui-egui/src/tools/anchor_tools.rs +++ b/crates/ui-egui/src/tools/anchor_tools.rs @@ -9,13 +9,15 @@ //! direction handles showing, and a drag from the click moves it, as in Photoshop (#8653). //! * Delete Anchor Point: hovering an anchor highlights it; a click removes it //! (`path.deleteAnchor`), joining its neighbours. -//! * ⌥ swaps the two tools and ⌘/Ctrl is Direct Selection (`direct_select`) while held. +//! * ⌥ swaps the two tools and ⌘/Ctrl is Direct Selection (`direct_select`) while held; ⌥-click +//! with Delete Anchor Point on an anchor selects its whole subpath instead. //! * The Pen does both with Auto Add/Delete on (its options bar, on by default, #4144): a click on //! a segment adds, a click on an anchor deletes, except an open subpath's end points; ⇧ turns it //! off while held. It edits the active path, or while a path is being drawn that path (#6140), //! and drawing carries on from its last anchor. //! -//! Each click (or add and drag) is one history step; a click on nothing it can edit does nothing. +//! Each click (or add and drag) is one history step; a click on nothing it can edit does nothing; +//! ⌥-click on an anchor with Delete Anchor Point only selects. use egui::{Color32, Modifiers, Pos2, Stroke}; use photocraft_doc::vector::Path; @@ -25,7 +27,7 @@ use photocraft_vector::edit::{self, Hit}; use crate::PhotocraftApp; use crate::canvas::ToolEvent; -use crate::direct_select::{DirectSelection, PathRef}; +use crate::direct_select::{DirectSelection, Owner, PathRef}; use crate::state::Tool; /// The anchor tool in effect, if the current tool is one: ⌥ swaps Add and Delete. @@ -109,7 +111,7 @@ pub fn pen_auto(app: &PhotocraftApp, tool: Tool, mods: Modifiers, p: [f64; 2]) - /// opposite it (`path.convertPoint` on release, through Direct Selection's drag). Both are one /// History step, Add Anchor Point. False when the press is not that, so ⌥ stays Convert Point. pub fn pen_alt_segment_press(app: &mut PhotocraftApp, mods: Modifiers, p: [f64; 2]) -> bool { - use crate::direct_select::{Drag, Edit, Owner, active_paths}; + use crate::direct_select::{Drag, Edit, active_paths}; if !mods.alt { return false; } @@ -158,12 +160,47 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: Modifiers) -> bool return true; } let Some(tool) = effective(app.ui.tool, mods) else { return false }; - if let ToolEvent::Down { x, y, .. } = ev { - click(app, tool, [x, y]); + match ev { + ToolEvent::Down { x, y, .. } => { + app.ui.direct_selection.subpath_press = None; + if app.ui.tool == Tool::DeleteAnchorPoint && mods.alt && subpath_at(app, [x, y]).is_some() { + let owner = Owner::current(app); + let ds = &mut app.ui.direct_selection; + ds.subpath_press = Some([x, y]); + // A stale press is dropped with the selection (`cancel_stale`). + ds.owner = owner; + } else { + click(app, tool, [x, y]); + } + } + ToolEvent::Up { x, y } => { + if let Some(start) = app.ui.direct_selection.subpath_press.take() + && !crate::direct_select::moved(app, start, [x, y]) + && let Some((r, anchors)) = subpath_at(app, start) + { + let owner = Owner::current(app); + app.ui.direct_selection = DirectSelection { target: Some(r), anchors, owner, ..Default::default() }; + } + } + // Once the pointer has moved off the press it is a drag, even if it comes back. + ToolEvent::Move { x, y, .. } => { + if app.ui.direct_selection.subpath_press.is_some_and(|start| crate::direct_select::moved(app, start, [x, y])) { + app.ui.direct_selection.subpath_press = None; + } + } } true } +/// ⌥-click with Delete Anchor Point on an anchor of a targeted path selects its whole subpath, as +/// in Photoshop (#12770); ⌥ is Add Anchor Point only on a segment. The path and that subpath's +/// anchors, or `None` when the press hits no anchor of a targeted path (a shape in a group that +/// is not active is hit as before but is not targeted). +fn subpath_at(app: &PhotocraftApp, p: [f64; 2]) -> Option<(PathRef, Vec<[usize; 2]>)> { + let (r, path, Hit::Anchor([s, _])) = target(app, Tool::DeleteAnchorPoint, p)? else { return None }; + crate::direct_select::active_paths(app).iter().any(|(a, _)| *a == r).then(|| (r, edit::subpath_anchors(&path, s))) +} + fn click(app: &mut PhotocraftApp, tool: Tool, p: [f64; 2]) { let Some((r, path, hit)) = target(app, tool, p) else { hide_anchors(app, tool, p); @@ -347,3 +384,4 @@ mod delete_anchor_escape_tests; #[cfg(test)] mod delete_anchor_shown_anchors_tests; +mod delete_anchor_alt_tests; diff --git a/crates/ui-egui/src/tools/anchor_tools/delete_anchor_alt_tests.rs b/crates/ui-egui/src/tools/anchor_tools/delete_anchor_alt_tests.rs new file mode 100644 index 0000000000..e5047a9d8e --- /dev/null +++ b/crates/ui-egui/src/tools/anchor_tools/delete_anchor_alt_tests.rs @@ -0,0 +1,94 @@ +//! #12770: ⌥-click with Delete Anchor Point on an anchor of the targeted path selects its whole +//! subpath and edits nothing; on a segment ⌥ still adds an anchor (Add Anchor Point). + +use egui::Modifiers; +use serde_json::json; + +use super::add_anchor_lock_tests::click_with_modifiers; +use super::delete_anchor_targeted_path_tests::{click, group_shape, setup, shape_path, steps}; +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::direct_select::PathRef; +use crate::state::Tool; + +/// Delete Anchor Point with the saved path "Path 1", a closed corner square +/// (100,300)(300,300)(300,500)(100,500), targeted in the Paths panel. +fn square() -> PhotocraftApp { + let (mut app, _) = setup(Tool::DeleteAnchorPoint); + let path = json!({"subpaths": [{"closed": true, "knots": [[100, 300], [300, 300], [300, 500], [100, 500]]}]}); + app.run("path.set", json!({"name": "Path 1", "path": path})).unwrap(); + app.ui.selected_path = Some("Path 1".into()); + app +} + +fn knots(app: &PhotocraftApp) -> usize { + app.session.active().unwrap().doc.paths[0].path.subpaths[0].knots.len() +} + +#[test] +fn alt_click_on_an_anchor_selects_the_whole_subpath_and_records_nothing() { + let mut app = square(); + let n = steps(&app); + click_with_modifiers(&mut app, [300.0, 500.0], Modifiers::ALT); + app.sync_views(); + let ds = &app.ui.direct_selection; + assert_eq!(ds.target, Some(PathRef::Saved(0))); + assert_eq!(ds.anchors, vec![[0, 0], [0, 1], [0, 2], [0, 3]]); + assert_eq!(knots(&app), 4); + assert_eq!(steps(&app), n); +} + +#[test] +fn alt_click_on_a_segment_still_adds_an_anchor() { + let mut app = square(); + let n = steps(&app); + click_with_modifiers(&mut app, [200.0, 300.0], Modifiers::ALT); + assert_eq!(knots(&app), 5); + assert_eq!(steps(&app), n + 1); + assert_eq!(app.session.active().unwrap().history.undo_label(), Some("Add Anchor Point")); +} + +#[test] +fn a_plain_click_on_an_anchor_still_deletes_it() { + let mut app = square(); + let n = steps(&app); + click(&mut app, [300.0, 500.0]); + assert_eq!(knots(&app), 3); + assert_eq!(steps(&app), n + 1); + assert_eq!(app.session.active().unwrap().history.undo_label(), Some("Delete Anchor Point")); + assert!(app.ui.direct_selection.anchors.is_empty()); +} + +#[test] +fn alt_drag_from_an_anchor_selects_nothing() { + let mut app = square(); + let n = steps(&app); + tool_event(&mut app, ToolEvent::Down { x: 300.0, y: 500.0, pressure: 1.0 }, Modifiers::ALT); + tool_event(&mut app, ToolEvent::Move { x: 360.0, y: 560.0, pressure: 1.0 }, Modifiers::ALT); + tool_event(&mut app, ToolEvent::Up { x: 360.0, y: 560.0 }, Modifiers::ALT); + assert!(app.ui.direct_selection.anchors.is_empty()); + assert_eq!(knots(&app), 4); + assert_eq!(steps(&app), n); +} + +#[test] +fn alt_drag_that_returns_to_the_press_selects_nothing() { + let mut app = square(); + tool_event(&mut app, ToolEvent::Down { x: 300.0, y: 500.0, pressure: 1.0 }, Modifiers::ALT); + tool_event(&mut app, ToolEvent::Move { x: 360.0, y: 560.0, pressure: 1.0 }, Modifiers::ALT); + tool_event(&mut app, ToolEvent::Move { x: 300.0, y: 500.0, pressure: 1.0 }, Modifiers::ALT); + tool_event(&mut app, ToolEvent::Up { x: 300.0, y: 500.0 }, Modifiers::ALT); + assert!(app.ui.direct_selection.anchors.is_empty()); + assert_eq!(knots(&app), 4); +} + +#[test] +fn alt_click_on_a_shape_in_a_group_that_is_not_active_selects_nothing() { + let (mut app, shape) = setup(Tool::DeleteAnchorPoint); + group_shape(&mut app, shape); + let (before, n) = (shape_path(&mut app, shape), steps(&app)); + click_with_modifiers(&mut app, [650.0, 250.0], Modifiers::ALT); + assert!(app.ui.direct_selection.anchors.is_empty()); + assert_eq!(shape_path(&mut app, shape), before); + assert_eq!(steps(&app), n); +} diff --git a/crates/ui-egui/src/tools/anchor_tools/delete_anchor_escape_tests.rs b/crates/ui-egui/src/tools/anchor_tools/delete_anchor_escape_tests.rs index 2fd81fdbd2..7513898191 100644 --- a/crates/ui-egui/src/tools/anchor_tools/delete_anchor_escape_tests.rs +++ b/crates/ui-egui/src/tools/anchor_tools/delete_anchor_escape_tests.rs @@ -9,7 +9,7 @@ use serde_json::json; use super::tests::{click, steps}; use crate::PhotocraftApp; -use crate::direct_select::{PathRef, active_paths, candidates}; +use crate::direct_select::{Drag, PathRef, active_paths, candidates}; use crate::state::Tool; /// The issue's document: 800 x 600 with the saved path "Path 1", a corner square with an anchor @@ -142,3 +142,43 @@ fn escape_while_renaming_path_1_cancels_the_rename() { assert_eq!(names, ["Path 1"], "Esc cancels the rename"); assert_eq!(h.state().ui.selected_path.as_deref(), Some("Path 1")); } + +#[test] +fn the_first_escape_without_a_selected_anchor_keeps_path_1_targeted() { + let mut app = app(); + let n = steps(&app); + escape(&mut app); + assert_eq!(app.ui.selected_path.as_deref(), Some("Path 1"), "the first Esc keeps Path 1 targeted"); + assert!(!active_paths(&app).is_empty(), "its outline stays"); + escape(&mut app); + assert_eq!(app.ui.selected_path, None, "the second Esc deselects Path 1"); + assert!(candidates(&app).is_empty(), "no outline or anchors are drawn"); + assert_eq!(steps(&app), n, "Esc adds no History step"); +} + +#[test] +fn an_escape_during_a_direct_selection_drag_keeps_the_anchors() { + let mut app = app(); + // Cmd is Direct Selection while held: it selects the anchor instead of deleting it. + click(&mut app, [300.0, 300.0], Modifiers::COMMAND); + assert_eq!(app.ui.direct_selection.anchors, vec![[0, 1]]); + app.ui.direct_selection.drag = Some(Drag::Marquee { start: [200.0, 200.0], end: [400.0, 400.0], add: false }); + escape(&mut app); + assert_eq!(app.ui.direct_selection.anchors, vec![[0, 1]], "the drag's release still moves them"); + assert!(app.ui.direct_selection.drag.is_some(), "and Esc does not end the drag"); + assert_eq!(app.ui.selected_path.as_deref(), Some("Path 1"), "nor deactivates the path"); +} + +#[test] +fn a_newly_targeted_path_starts_at_the_first_escape_again() { + let mut app = app(); + let line = json!({"subpaths": [{"knots": [[600, 100], [700, 100]]}]}); + app.run("path.set", json!({"name": "Path 2", "path": line})).unwrap(); + escape(&mut app); + assert_eq!(app.ui.selected_path.as_deref(), Some("Path 1"), "the first Esc keeps Path 1 targeted"); + app.ui.selected_path = Some("Path 2".into()); + escape(&mut app); + assert_eq!(app.ui.selected_path.as_deref(), Some("Path 2"), "the first Esc on a new path keeps it targeted"); + escape(&mut app); + assert_eq!(app.ui.selected_path, None, "and the second Esc deselects it"); +} diff --git a/crates/ui-egui/src/tools/anchor_tools/tests.rs b/crates/ui-egui/src/tools/anchor_tools/tests.rs index d04b5aa1a2..ef815c66cf 100644 --- a/crates/ui-egui/src/tools/anchor_tools/tests.rs +++ b/crates/ui-egui/src/tools/anchor_tools/tests.rs @@ -53,7 +53,7 @@ fn the_anchor_tools_have_no_letter() { } #[test] -fn add_on_a_straight_segment_inserts_a_corner_in_one_step() { +fn add_on_a_straight_segment_inserts_a_smooth_anchor_in_one_step() { let mut app = app(Tool::AddAnchorPoint); with_path(&mut app); let (before, n) = (work(&app), steps(&app)); @@ -61,7 +61,11 @@ fn add_on_a_straight_segment_inserts_a_corner_in_one_step() { let p = work(&app); assert_eq!(p.subpaths[0].knots.len(), 5); let k = p.subpaths[0].knots[3]; - assert!(!k.smooth && (k.anchor.y - 120.0).abs() < 1e-9 && (k.anchor.x - 80.0).abs() < 1.0, "a corner on the bottom edge: {k:?}"); + assert!(k.smooth && (k.anchor.y - 120.0).abs() < 1e-9 && (k.anchor.x - 80.0).abs() < 1.0, "a smooth anchor on the bottom edge: {k:?}"); + assert!( + (k.in_ctrl.y - 120.0).abs() < 1e-9 && (k.out_ctrl.y - 120.0).abs() < 1e-9 && k.in_ctrl.x != k.anchor.x && k.out_ctrl.x != k.anchor.x, + "with handles along the edge: {k:?}" + ); assert_eq!(steps(&app), n + 1); assert_eq!(app.session.active().unwrap().history.undo_label(), Some("Add Anchor Point")); assert!(app.session.undo()); diff --git a/crates/ui-egui/src/tools/corner_radius.rs b/crates/ui-egui/src/tools/corner_radius.rs index f5ec3192e9..2381e623b3 100644 --- a/crates/ui-egui/src/tools/corner_radius.rs +++ b/crates/ui-egui/src/tools/corner_radius.rs @@ -26,8 +26,9 @@ const MIN_INSET: f64 = 10.0; enum Geom { /// `[x, y, w, h]` with a positive size. Rect([f64; 4]), - /// The polygon's parameters and its sharp vertices, in path order. - Polygon { rect: [f64; 4], sides: u32, star_ratio: f64, vertices: Vec<[f64; 2]> }, + /// The polygon's parameters, its sharp vertices in path order, and the indices of those + /// that take the radius (a star's outer points only). + Polygon { rect: [f64; 4], sides: u32, star_ratio: f64, vertices: Vec<[f64; 2]>, rounded: Vec }, } /// A selected live shape with corners: its layer, its geometry, and its radii (a rectangle's four @@ -52,7 +53,7 @@ impl Target { fn corners(&self) -> usize { match &self.geom { Geom::Rect(_) => 4, - Geom::Polygon { vertices, .. } => vertices.len(), + Geom::Polygon { rounded, .. } => rounded.len(), } } @@ -72,27 +73,29 @@ impl Target { }; Some(Corner { vertex, step: d }) } - Geom::Polygon { vertices, .. } => { + Geom::Polygon { vertices, rounded, .. } => { let f = self.fillet(i, 1.0)?; let sin = f.half_angle.sin(); - (sin > 1e-9).then(|| Corner { vertex: vertices.get(i).copied().unwrap_or(f.centre), step: [f.bisector[0] / sin, f.bisector[1] / sin] }) + let vertex = rounded.get(i).and_then(|&v| vertices.get(v)).copied().unwrap_or(f.centre); + (sin > 1e-9).then(|| Corner { vertex, step: [f.bisector[0] / sin, f.bisector[1] / sin] }) } } } - /// A polygon vertex's rounding with radius `r`. + /// Corner `i`'s rounding with radius `r` (a polygon's). fn fillet(&self, i: usize, r: f64) -> Option { - let Geom::Polygon { vertices, .. } = &self.geom else { return None }; + let Geom::Polygon { vertices, rounded, .. } = &self.geom else { return None }; let n = vertices.len(); + let v = *rounded.get(i)?; let at = |k: usize| vertices.get(k % n).copied(); - shapes::fillet(at(i + n - 1)?, at(i)?, at(i + 1)?, r) + shapes::fillet(at(v + n - 1)?, at(v)?, at(v + 1)?, r) } /// The largest radius every corner of the shape can take. fn max_radius(&self) -> f64 { match &self.geom { Geom::Rect(r) => r[2].min(r[3]) / 2.0, - Geom::Polygon { vertices, .. } => (0..vertices.len()).filter_map(|i| self.fillet(i, 1.0e12)).map(|f| f.radius).fold(f64::INFINITY, f64::min), + Geom::Polygon { rounded, .. } => (0..rounded.len()).filter_map(|i| self.fillet(i, 1.0e12)).map(|f| f.radius).fold(f64::INFINITY, f64::min), } } @@ -175,8 +178,9 @@ fn target(layer: u64, live: &LiveShape) -> Option { return None; } let sharp = shapes::polygon(rect[0], rect[1], rect[2], rect[3], sides, star_ratio); - let vertices = sharp.subpaths.first()?.knots.iter().map(|k| [k.anchor.x, k.anchor.y]).collect(); - Some(Target { layer, geom: Geom::Polygon { rect, sides, star_ratio, vertices }, radii: [corner_radius.max(0.0); 4] }) + let vertices: Vec<[f64; 2]> = sharp.subpaths.first()?.knots.iter().map(|k| [k.anchor.x, k.anchor.y]).collect(); + let rounded = (0..vertices.len()).filter(|&i| shapes::polygon_rounds_vertex(star_ratio, i)).collect(); + Some(Target { layer, geom: Geom::Polygon { rect, sides, star_ratio, vertices, rounded }, radii: [corner_radius.max(0.0); 4] }) } LiveShape::Ellipse { .. } | LiveShape::Line { .. } | LiveShape::ArrowLine { .. } => None, } diff --git a/crates/ui-egui/src/tools/corner_radius/tests.rs b/crates/ui-egui/src/tools/corner_radius/tests.rs index 252e9ce587..904eb9ff59 100644 --- a/crates/ui-egui/src/tools/corner_radius/tests.rs +++ b/crates/ui-egui/src/tools/corner_radius/tests.rs @@ -267,3 +267,27 @@ fn rectangles_and_triangles_selected_together_take_the_same_radius() { assert_eq!(rr, [4.0; 4]); assert!((corner_radius_of(&app, tri) - 4.0).abs() < 1e-9); } + +#[test] +fn a_star_shows_widgets_at_its_outer_points_only() { + // #13308: a star's inner points stay sharp, so they have no widget. + let live = LiveShape::Polygon { rect: [40.0, 40.0, 120.0, 100.0], sides: 5, star_ratio: 0.5, corner_radius: 6.0 }; + let t = super::target(1, &live).unwrap(); + assert_eq!(t.corners(), 5); + let sharp = &photocraft_vector::shapes::polygon(40.0, 40.0, 120.0, 100.0, 5, 0.5).subpaths[0].knots; + for i in 0..5 { + let v = sharp[2 * i].anchor; + assert_eq!(t.corner(i).unwrap().vertex, [v.x, v.y], "corner {i} is outer point {i}"); + } + // The widgets preview the outline `shape.create` makes with the same radius. + assert_eq!(t.path(t.radii), photocraft_vector::shapes::live_path(&live)); + // The largest radius is the one every outer point can take. + let outer_most = (0..5).filter_map(|i| t.fillet(i, 1.0e12)).map(|f| f.radius).fold(f64::INFINITY, f64::min); + assert!(outer_most.is_finite() && t.max_radius() == outer_most); +} + +#[test] +fn a_plain_polygon_shows_a_widget_at_every_vertex() { + let live = LiveShape::Polygon { rect: [40.0, 40.0, 120.0, 100.0], sides: 6, star_ratio: 1.0, corner_radius: 6.0 }; + assert_eq!(super::target(1, &live).unwrap().corners(), 6); +} diff --git a/crates/ui-egui/src/tools/count_options_bar_tests.rs b/crates/ui-egui/src/tools/count_options_bar_tests.rs new file mode 100644 index 0000000000..3a2e9c1f20 --- /dev/null +++ b/crates/ui-egui/src/tools/count_options_bar_tests.rs @@ -0,0 +1,234 @@ +//! #11765: the Count tool's options bar shows every control from the start, in Photoshop's order, +//! with its tooltips, and greys what can't act: the group dropdown until there is a group, the +//! trash with fewer than two groups, Clear while the current group is empty or hidden. + +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::state::Tool; + +const EYE: &str = "Toggle visibility of count group"; +const FOLDER: &str = "Create a new count group"; +const TRASH: &str = "Delete the currently selected count group"; +const SWATCH: &str = "Count group color"; + +/// A 100 × 100 document with the Count tool and `groups` count groups (the first with a marker). +fn app(groups: usize) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 100, "height": 100})).unwrap(); + app.ui.tool = Tool::Count; + if groups > 0 { + app.run("count.add", json!({"x": 10, "y": 10})).unwrap(); + } + for _ in 1..groups { + app.run("count.newGroup", json!({})).unwrap(); + } + if groups > 0 { + app.run("count.setGroup", json!({"group": 0, "active": true})).unwrap(); + } + app +} + +fn harness(app: PhotocraftApp) -> Harness<'static, PhotocraftApp> { + let mut h = Harness::builder().with_size(vec2(1400.0, 120.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + if !ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + crate::panels::options_bar(app, ui); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::Studio); + h.run_steps(4); + h +} + +fn disabled(h: &Harness<'static, PhotocraftApp>, label: &str) -> bool { + h.get_by_label(label).accesskit_node().is_disabled() +} + +fn combo_disabled(h: &Harness<'static, PhotocraftApp>) -> bool { + h.get_all_by_role(egui::accesskit::Role::ComboBox).next().expect("the group dropdown").accesskit_node().is_disabled() +} + +#[test] +fn the_controls_are_in_the_reference_order_in_every_state() { + for groups in [0, 1, 2] { + let h = harness(app(groups)); + let x = |label: &str| h.get_by_label(label).rect().left(); + let combo = h.get_all_by_role(egui::accesskit::Role::ComboBox).next().expect("the group dropdown").rect().left(); + let order = [combo, x(EYE), x(FOLDER), x(TRASH), x("Clear"), x(SWATCH), x("Marker Size:"), x("Label Size:")]; + assert!(order.windows(2).all(|w| w[0] < w[1]), "{groups} groups: left edges {order:?}"); + let count = h.get_all_by_label_contains("Count: ").next().expect("the Count: readout").rect().left(); + assert!(count < combo, "{groups} groups: the readout comes first"); + } +} + +#[test] +fn with_no_group_the_dropdown_trash_and_clear_are_greyed_and_the_next_groups_values_show() { + let h = harness(app(0)); + assert!(combo_disabled(&h), "the dropdown is greyed"); + let combo = h.get_all_by_role(egui::accesskit::Role::ComboBox).next().unwrap(); + let node = combo.accesskit_node(); + assert_eq!(node.value().as_deref(), Some("Count Group"), "with the placeholder"); + assert!(disabled(&h, TRASH) && disabled(&h, "Clear")); + assert!(!disabled(&h, EYE) && !disabled(&h, FOLDER)); + // The sizes the next new group gets today. + let next = photocraft_doc::CountGroup::default(); + assert!(h.query_by_value(&next.marker_size.to_string()).is_some(), "Marker Size {}", next.marker_size); + assert!(h.query_by_value(&next.label_size.to_string()).is_some(), "Label Size {}", next.label_size); +} + +#[test] +fn using_the_eye_with_no_group_changes_nothing() { + let mut h = harness(app(0)); + let steps = h.state().session.active().unwrap().history.past_len(); + h.get_by_label(EYE).click(); + h.run_steps(3); + let st = h.state().session.active().unwrap(); + assert!(st.doc.measurement.count_groups.is_empty()); + assert_eq!(st.history.past_len(), steps); +} + +#[test] +fn the_trash_needs_two_groups() { + assert!(disabled(&harness(app(1)), TRASH), "one group"); + let mut h = harness(app(2)); + assert!(!disabled(&h, TRASH), "two groups"); + h.get_by_label(TRASH).click(); + h.run_steps(3); + assert_eq!(h.state().session.active().unwrap().doc.measurement.count_groups.len(), 1); + assert!(disabled(&h, TRASH), "back to one group"); +} + +#[test] +fn clear_needs_a_visible_current_group_with_markers() { + let h = harness(app(1)); + assert!(!disabled(&h, "Clear"), "one marker, visible"); + let mut hidden = app(1); + hidden.run("count.setGroup", json!({"visible": false})).unwrap(); + assert!(disabled(&harness(hidden), "Clear"), "hidden"); + let mut empty = app(2); + empty.run("count.setGroup", json!({"group": 1, "active": true})).unwrap(); + assert!(disabled(&harness(empty), "Clear"), "the current group has no markers"); +} + +#[test] +fn the_swatch_opens_the_count_color_picker() { + let mut h = harness(app(1)); + h.get_by_label(SWATCH).click(); + h.run_steps(3); + let want = crate::color_picker_ui::title_for("Count Color"); + assert_eq!(want, "Color Picker (Count Color)"); + assert!(h.state().ui.dialogs.iter().any(|d| crate::dialogs::title(d) == want), "a picker titled {want}"); +} + +#[test] +fn the_size_captions_scrub_their_fields() { + let mut h = harness(app(1)); + // The visible caption, not the field it names (`get_by_label` returns the labelled field). + let from = h + .query_all(egui_kittest::kittest::by().label("Marker Size:").include_labels()) + .find(|n| n.accesskit_node().role() == egui::accesskit::Role::Label) + .expect("the Marker Size: caption") + .rect() + .center(); + // As the Brush options' scrub test drives a caption (options_hit_area_tests): hover, press, + // move in steps, release, letting each step settle. + h.hover_at(from); + h.run(); + h.drag_at(from); + h.run(); + for i in 1..=4 { + h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE)); + h.hover_at(from + vec2(12.0 * i as f32, 0.0)); + h.run(); + } + h.drop_at(from + vec2(48.0, 0.0)); + h.run_steps(2); + let g = &h.state().session.active().unwrap().doc.measurement.count_groups[0]; + assert!(g.marker_size > 1, "dragging the caption right raised Marker Size: {}", g.marker_size); + assert!(g.marker_size <= 10, "within its range"); +} + +/// Drags the visible "Marker Size:" caption `dx` points right in four moves. +fn scrub_marker_size(h: &mut Harness<'static, PhotocraftApp>, dx: f32) { + let from = h + .query_all(egui_kittest::kittest::by().label("Marker Size:").include_labels()) + .find(|n| n.accesskit_node().role() == egui::accesskit::Role::Label) + .expect("the Marker Size: caption") + .rect() + .center(); + h.hover_at(from); + h.run(); + h.drag_at(from); + h.run(); + for i in 1..=4 { + h.event(egui::Event::ModifiersChanged(egui::Modifiers::NONE)); + h.hover_at(from + vec2(dx / 4.0 * i as f32, 0.0)); + h.run(); + } + h.drop_at(from + vec2(dx, 0.0)); + h.run_steps(2); +} + +#[test] +fn one_size_scrub_is_one_history_step() { + let mut h = harness(app(1)); + let steps = |h: &Harness<'static, PhotocraftApp>| h.state().session.active().unwrap().history.past_len(); + let before = steps(&h); + scrub_marker_size(&mut h, 24.0); + let size = h.state().session.active().unwrap().doc.measurement.count_groups[0].marker_size; + assert!(size > 2, "the scrub moved Marker Size several steps: {size}"); + assert_eq!(steps(&h), before + 1, "one scrub, one Undo step"); + // Back left, as the first may have reached the top of the range. + scrub_marker_size(&mut h, -24.0); + let back = h.state().session.active().unwrap().doc.measurement.count_groups[0].marker_size; + assert!(back < size, "the second scrub moved it back: {size} -> {back}"); + assert_eq!(steps(&h), before + 2, "a second scrub is a step of its own"); +} + +#[test] +fn automation_delete_and_clear_work_as_today() { + // The greying is the options bar's: the commands still delete the last group and clear a + // hidden one. + let mut app = app(1); + app.run("count.setGroup", json!({"visible": false})).unwrap(); + app.run("count.clear", json!({})).unwrap(); + assert_eq!(app.session.active().unwrap().doc.measurement.count_total(), 0); + app.run("count.deleteGroup", json!({})).unwrap(); + assert!(app.session.active().unwrap().doc.measurement.count_groups.is_empty()); +} + +/// The visible caption node (a `Role::Label`) reading `text`, if any. +fn caption_node(h: &Harness<'static, PhotocraftApp>, text: &str) -> bool { + h.query_all(egui_kittest::kittest::by().label(text).include_labels()).any(|n| n.accesskit_node().role() == egui::accesskit::Role::Label) +} + +#[test] +fn the_size_captions_are_translated() { + // The catalogs translate "Marker Size" and "Label Size" (main's captions); the colon follows. + // A missing catalog row shows the English, so the test doesn't require the translation. + if !crate::i18n::needs_catalogs() { + return; + } + let _de = crate::i18n::language_scope(crate::i18n::Lang::from_code("de").expect("German")); + let h = harness(app(1)); + for key in ["Marker Size", "Label Size"] { + let want = format!("{}:", crate::i18n::t(key)); + assert!(caption_node(&h, &want), "the caption reads {want}"); + } +} + +#[test] +fn the_size_fields_are_named_by_their_visible_captions() { + let h = harness(app(1)); + for caption in ["Marker Size:", "Label Size:"] { + let fields = h.query_all(egui_kittest::kittest::by().label(caption).predicate(|n| n.role() != egui::accesskit::Role::Label)).count(); + assert_eq!(fields, 1, "one field named {caption}, as its caption reads"); + } +} diff --git a/crates/ui-egui/src/tools/direct_select.rs b/crates/ui-egui/src/tools/direct_select.rs index 1c7e9e1b4c..abda6368c6 100644 --- a/crates/ui-egui/src/tools/direct_select.rs +++ b/crates/ui-egui/src/tools/direct_select.rs @@ -10,8 +10,9 @@ //! The arrow keys nudge the selected anchors 1 px (⇧ 10 px), one history step per press. //! * Convert Point (the tool, or Pen + ⌥): click an anchor to make it a corner, drag from it to //! pull out smooth handles, drag a handle to move it alone. The tool selects the anchor it -//! converts, so its handles show; a press on empty canvas or a segment does nothing, and ⌘/Ctrl -//! is Direct Selection, as with the Pen. +//! converts, so its handles show; a press on empty canvas does nothing, and ⌘/Ctrl is Direct +//! Selection, as with the Pen. The tool drags a straight segment with nothing selected, or the +//! whole path when all of it is selected, as Direct Selection would (#12741). //! * While a Pen path is being drawn, ⌘/Ctrl edits it in place (its anchors, handles and //! segments) and the Pen carries on drawing from its last anchor once ⌘/Ctrl is let go; a //! ⌘/Ctrl-press anywhere else ends it, as in Photoshop (#4022). @@ -88,12 +89,20 @@ pub struct DirectSelection { pub(crate) owner: Option, #[serde(skip)] pub(crate) cancelled_drag: bool, + /// The saved path whose anchors the first Escape hid (#13072): the next Escape deactivates it, + /// and targeting another path starts at the first Escape again. + #[serde(skip)] + pub(crate) escape_hidden: Option, /// Path Selection only: the target path's [`crate::path_components::SelectionSignature`] when /// the selection was made — a structural identity that survives history revisions (a click /// activates the layer, colours change, components move), so the component selection lives /// until the path's structure changes (#10854). #[serde(skip)] pub(crate) signature: Option, + /// Where a ⌥-press with Delete Anchor Point hit an anchor: its release without a drag selects + /// the anchor's subpath (`anchor_tools`). + #[serde(skip)] + pub(crate) subpath_press: Option<[f64; 2]>, } /// The cached structural check for one document revision. Type Paths are generated only when @@ -266,6 +275,8 @@ pub enum Edit { /// A handle, where it was at the press, and whether it moves alone (⌥). Handle([usize; 2], Handle, Point, bool), Segment([usize; 2], f64), + /// The Convert Point tool dragging a whole selected path by a segment: its anchors, all of them. + Path(Vec<[usize; 2]>), /// Pen + ⌥ on an anchor: a click makes a corner, a drag pulls out smooth handles. Convert([usize; 2]), } @@ -286,6 +297,7 @@ impl Edit { ("path.moveHandle", json!({"subpath": s, "knot": k, "handle": h.name(), "to": [from.x + d[0], from.y + d[1]], "independent": independent})) } Edit::Segment([s, k], t) => ("path.bendSegment", json!({"subpath": s, "knot": k, "t": t, "move": d})), + Edit::Path(a) => ("path.moveAnchors", json!({"anchors": a, "move": d, "stepName": "Drag Path"})), Edit::Convert([s, k]) => ("path.convertPoint", json!({"subpath": s, "knot": k, "out": end})), } } @@ -295,7 +307,7 @@ impl Edit { let d = [end[0] - start[0], end[1] - start[1]]; let mut p = base.clone(); match self { - Edit::Anchors(a) => edit::move_anchors(&mut p, a, d), + Edit::Anchors(a) | Edit::Path(a) => edit::move_anchors(&mut p, a, d), Edit::Curvature(a) => edit::move_anchors_curvature(&mut p, a, d), Edit::Handle(k, h, from, independent) => edit::move_handle(&mut p, *k, *h, Point::new(from.x + d[0], from.y + d[1]), *independent), Edit::Segment(k, t) => edit::bend_segment(&mut p, *k, *t, d), @@ -662,8 +674,21 @@ fn press(app: &mut PhotocraftApp, p: [f64; 2], mods: Modifiers, convert: bool) - } Edit::Convert(k) } - // Pen + ⌥ on a segment does nothing. - Hit::Segment(..) if convert => return true, + // Pen + ⌥ on a segment does nothing; so does the tool where the reference was not + // measured: with ⇧ or ⌥, on a curve, or with part of the path selected. + Hit::Segment(k, t) if convert => { + if !own_tool || mods.alt || mods.shift || !straight(&base, k) { + return true; + } + let all: Vec<[usize; 2]> = (0..base.subpaths.len()).flat_map(|s| edit::subpath_anchors(&base, s)).collect(); + if ds.anchors.is_empty() { + Edit::Segment(k, t) + } else if all.iter().all(|a| ds.anchors.contains(a)) { + Edit::Path(all) + } else { + return true; + } + } Hit::Anchor(k) => { ds.segment = None; if mods.alt { @@ -695,6 +720,18 @@ fn press(app: &mut PhotocraftApp, p: [f64; 2], mods: Modifiers, convert: bool) - true } +/// Is the segment leaving knot `k` straight: both of its handles retracted? The distance test is +/// the one `edit::bend_segment` uses, so a segment counted straight here moves as straight there. +fn straight(path: &Path, [s, k]: [usize; 2]) -> bool { + let Some(sub) = path.subpaths.get(s) else { return false }; + let next = if k + 1 < sub.knots.len() { k + 1 } else { 0 }; + let near = |c: Point, a: Point| (c.x - a.x).hypot(c.y - a.y) < 1e-9; + match (sub.knots.get(k), sub.knots.get(next)) { + (Some(a), Some(b)) => near(a.out_ctrl, a.anchor) && near(b.in_ctrl, b.anchor), + _ => false, + } +} + /// What the idle Curvature Pen has under document point `p` on the active paths: an anchor or a /// segment, with the path it is on. Handles don't count. fn curvature_target(app: &PhotocraftApp, p: [f64; 2]) -> Option<(PathRef, Path, Hit)> { @@ -780,10 +817,15 @@ pub(crate) fn grab_added(app: &mut PhotocraftApp, target: PathRef, base: Path, k app.ui.direct_selection.drag = Some(Drag::Edit { target, base, edit: Edit::Anchors(vec![k]), start: p, end: p, preview: None }); } +/// Did the pointer move between `start` and `end` (document points): a screen pixel or more? +pub(crate) fn moved(app: &PhotocraftApp, start: [f64; 2], end: [f64; 2]) -> bool { + (end[0] - start[0]).hypot(end[1] - start[1]) * f64::from(app.point_zoom()) >= 1.0 +} + /// End of an edit drag: commit it as one command. A click (no movement) commits nothing, except /// Pen + ⌥ on an anchor, which makes it a corner. The Pen path being drawn takes the edit directly. fn release(app: &mut PhotocraftApp, target: PathRef, base: &Path, edit: &Edit, start: [f64; 2], end: [f64; 2], mods: Modifiers) { - let moved = (end[0] - start[0]).hypot(end[1] - start[1]) * f64::from(app.point_zoom()) >= 1.0; + let moved = moved(app, start, end); if target == PathRef::Pen { let edited = match edit { Edit::Convert(k) if !moved => { @@ -956,6 +998,9 @@ mod convert_point_targeted_path_tests; #[cfg(test)] mod convert_point_tolerance_tests; +#[cfg(test)] +mod convert_point_drag_segment_tests; + #[cfg(test)] mod freeform_command_tests { use super::*; diff --git a/crates/ui-egui/src/tools/direct_select/convert_point_drag_segment_tests.rs b/crates/ui-egui/src/tools/direct_select/convert_point_drag_segment_tests.rs new file mode 100644 index 0000000000..33290ed703 --- /dev/null +++ b/crates/ui-egui/src/tools/direct_select/convert_point_drag_segment_tests.rs @@ -0,0 +1,172 @@ +//! #12741: a drag that starts on a segment with the Convert Point tool works as a temporary +//! Direct Selection, as in the reference: with nothing selected the straight segment moves +//! ("Drag Segment"), with the whole path selected the whole path moves ("Drag Path"). A click, +//! and the cases the reference was not measured on, do nothing. + +use egui::Modifiers; +use photocraft_doc::vector::Path; +use photocraft_geom::Point; +use serde_json::json; + +use super::convert_point_history_tests::{added, click, drag}; +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; + +const BOTTOM_EDGE: [f64; 2] = [200.0, 500.0]; + +/// The reference document: 800×600 px with a saved path, targeted in the Paths panel: a closed +/// corner square, an open straight line and an open S-curve of two smooth points. +fn app(tool: Tool) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 800, "height": 600})).unwrap(); + let path = json!({"subpaths": [ + {"closed": true, "knots": [[100, 300], [300, 300], [300, 500], [100, 500]]}, + {"knots": [[400, 300], [700, 300]]}, + {"knots": [ + {"anchor": [400, 450], "in": [300, 550], "out": [500, 350], "smooth": true}, + {"anchor": [700, 450], "in": [600, 550], "out": [800, 350], "smooth": true}, + ]}, + ]}); + app.run("path.set", json!({"name": "Path 1", "path": path})).unwrap(); + app.ui.selected_path = Some("Path 1".into()); + app.sync_views(); + app.ui.tool = tool; + app +} + +fn path(app: &PhotocraftApp) -> Path { + app.session.active().unwrap().doc.paths[0].path.clone() +} + +/// `p` with knots `which` (all when `None`) moved by `d`, handles included. +fn moved(p: &Path, which: Option<&[[usize; 2]]>, d: [f64; 2]) -> Path { + let mut p = p.clone(); + for (s, sub) in p.subpaths.iter_mut().enumerate() { + for (k, kn) in sub.knots.iter_mut().enumerate() { + if which.is_none_or(|w| w.contains(&[s, k])) { + for q in [&mut kn.anchor, &mut kn.in_ctrl, &mut kn.out_ctrl] { + *q = Point::new(q.x + d[0], q.y + d[1]); + } + } + } + } + p +} + +/// Every anchor of the path selected, by a ⌘-marquee (Direct Selection in this tool). +fn select_all(app: &mut PhotocraftApp) { + drag(app, [0.0, 0.0], [800.0, 600.0], Modifiers::COMMAND); + assert_eq!(app.ui.direct_selection.anchors.len(), 8); +} + +#[test] +fn with_nothing_selected_a_segment_drag_moves_only_that_segment() { + let mut app = app(Tool::ConvertPoint); + let before = path(&app); + let steps = added(&mut app, |a| drag(a, BOTTOM_EDGE, [200.0, 540.0], Modifiers::NONE)); + assert_eq!(steps, ["Drag Segment"]); + let after = path(&app); + assert_eq!(after.subpaths[0].knots[2].anchor, Point::new(300.0, 540.0)); + assert_eq!(after.subpaths[0].knots[3].anchor, Point::new(100.0, 540.0)); + assert_eq!(after, moved(&before, Some(&[[0, 2], [0, 3]]), [0.0, 40.0]), "the other anchors stay"); + assert!(app.session.undo()); + assert_eq!(path(&app), before); +} + +#[test] +fn the_closing_segment_of_a_closed_subpath_moves_too() { + let mut app = app(Tool::ConvertPoint); + let before = path(&app); + assert_eq!(added(&mut app, |a| drag(a, [100.0, 400.0], [60.0, 400.0], Modifiers::NONE)), ["Drag Segment"]); + assert_eq!(path(&app), moved(&before, Some(&[[0, 3], [0, 0]]), [-40.0, 0.0])); +} + +#[test] +fn with_the_whole_path_selected_a_segment_drag_moves_the_whole_path() { + let mut app = app(Tool::ConvertPoint); + select_all(&mut app); + let before = path(&app); + let steps = added(&mut app, |a| drag(a, BOTTOM_EDGE, [200.0, 540.0], Modifiers::NONE)); + assert_eq!(steps, ["Drag Path"]); + assert_eq!(path(&app), moved(&before, None, [0.0, 40.0]), "all three subpaths moved"); + assert_eq!(app.ui.direct_selection.anchors.len(), 8, "the selection stays"); +} + +#[test] +fn a_click_on_a_segment_does_nothing() { + for all in [false, true] { + let mut app = app(Tool::ConvertPoint); + if all { + select_all(&mut app); + } + let (before, selection) = (path(&app), app.ui.direct_selection.anchors.clone()); + assert!(added(&mut app, |a| click(a, BOTTOM_EDGE, Modifiers::NONE)).is_empty(), "all selected: {all}"); + assert_eq!((path(&app), &app.ui.direct_selection.anchors), (before, &selection)); + assert!(app.ui.direct_selection.drag.is_none()); + } +} + +#[test] +fn unmeasured_segment_drags_still_do_nothing() { + let nothing = |mut app: PhotocraftApp, from: [f64; 2], mods: Modifiers, what: &str| { + let before = path(&app); + let steps = added(&mut app, |a| drag(a, from, [from[0], from[1] + 40.0], mods)); + assert!(steps.is_empty(), "{what}: {steps:?}"); + assert_eq!(path(&app), before, "{what}"); + }; + nothing(app(Tool::ConvertPoint), [550.0, 450.0], Modifiers::NONE, "a curved segment"); + let mut all = app(Tool::ConvertPoint); + select_all(&mut all); + nothing(all, [550.0, 450.0], Modifiers::NONE, "a curved segment, the whole path selected"); + nothing(app(Tool::ConvertPoint), BOTTOM_EDGE, Modifiers::SHIFT, "⇧"); + nothing(app(Tool::ConvertPoint), BOTTOM_EDGE, Modifiers::ALT, "⌥"); + let mut some = app(Tool::ConvertPoint); + click(&mut some, [100.0, 300.0], Modifiers::COMMAND); + assert_eq!(some.ui.direct_selection.anchors, vec![[0, 0]]); + nothing(some, BOTTOM_EDGE, Modifiers::NONE, "part of the path selected"); + + // Pen + ⌥ on a segment is the Pen's own: it adds an anchor there, and the segment stays. + let mut pen = app(Tool::Pen); + assert_eq!(added(&mut pen, |a| drag(a, BOTTOM_EDGE, [200.0, 540.0], Modifiers::ALT)), ["Add Anchor Point"]); + let bottom = &path(&pen).subpaths[0].knots; + assert!(bottom.iter().all(|k| k.anchor.y <= 500.0), "the segment did not move: {bottom:?}"); +} + +#[test] +fn direct_selection_segment_drags_keep_their_behaviour() { + for all in [false, true] { + let mut app = app(Tool::DirectSelection); + if all { + select_all(&mut app); + } + let before = path(&app); + assert_eq!(added(&mut app, |a| drag(a, BOTTOM_EDGE, [200.0, 540.0], Modifiers::NONE)), ["Drag Segment"]); + assert_eq!(path(&app), moved(&before, Some(&[[0, 2], [0, 3]]), [0.0, 40.0]), "all selected: {all}"); + } +} + +#[test] +fn a_command_anchor_drag_released_without_command_keeps_its_own_step_name() { + let mut app = app(Tool::ConvertPoint); + select_all(&mut app); + tool_event(&mut app, ToolEvent::Down { x: 300.0, y: 300.0, pressure: 1.0 }, Modifiers::COMMAND); + tool_event(&mut app, ToolEvent::Move { x: 320.0, y: 300.0, pressure: 1.0 }, Modifiers::COMMAND); + let steps = added(&mut app, |a| { + tool_event(a, ToolEvent::Up { x: 320.0, y: 300.0 }, Modifiers::NONE); + }); + assert_eq!(steps, ["Drag Anchor Points"]); +} + +#[test] +fn move_anchors_takes_the_drag_path_step_name_and_refuses_any_other() { + let mut app = app(Tool::ConvertPoint); + let params = |name: serde_json::Value| json!({"name": "Path 1", "anchors": [[0, 0]], "move": [1, 1], "stepName": name}); + assert_eq!(added(&mut app, |a| a.run("path.moveAnchors", params(json!("Drag Path"))).map(|_| ()).unwrap()), ["Drag Path"]); + let before = path(&app); + for bad in [json!("Drag Segment"), json!("Drag Path "), json!(1)] { + let e = app.run("path.moveAnchors", params(bad.clone())).unwrap_err(); + assert!(e.contains("stepName"), "{bad}: {e}"); + } + assert_eq!(path(&app), before); +} 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 86d842af1c..7539f7aa6f 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 @@ -35,7 +35,7 @@ pub(super) fn drag(app: &mut PhotocraftApp, from: [f64; 2], to: [f64; 2], mods: tool_event(app, ToolEvent::Up { x: to[0], y: to[1] }, mods); } -fn click(app: &mut PhotocraftApp, at: [f64; 2], mods: Modifiers) { +pub(super) fn click(app: &mut PhotocraftApp, at: [f64; 2], mods: Modifiers) { drag(app, at, at, mods); } @@ -44,7 +44,7 @@ fn names(app: &PhotocraftApp) -> Vec { } /// Runs `gesture` and returns the History steps it added. -fn added(app: &mut PhotocraftApp, gesture: impl FnOnce(&mut PhotocraftApp)) -> Vec { +pub(super) fn added(app: &mut PhotocraftApp, gesture: impl FnOnce(&mut PhotocraftApp)) -> Vec { let n = names(app).len(); gesture(app); names(app).split_off(n) diff --git a/crates/ui-egui/src/tools/line_tool_defaults_tests.rs b/crates/ui-egui/src/tools/line_tool_defaults_tests.rs new file mode 100644 index 0000000000..60ceea5f96 --- /dev/null +++ b/crates/ui-egui/src/tools/line_tool_defaults_tests.rs @@ -0,0 +1,79 @@ +//! #13241: the Line tool starts, and resets to, Weight 1 px with arrowheads 5 px wide and 10 px +//! long (Start and End off, Concavity 0 %), as the reference application does. + +use egui::Modifiers; +use photocraft_doc::LayerContent; +use photocraft_doc::vector::LiveShape; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::{Tool, ToolOptions}; + +fn assert_line_defaults(o: &ToolOptions) { + assert_eq!(o.line_weight, 1.0, "Weight"); + assert!(!o.arrow_start && !o.arrow_end, "Start and End off"); + assert_eq!(o.arrow_width, 5.0, "arrowhead Width"); + assert_eq!(o.arrow_length, 10.0, "arrowhead Length"); + assert_eq!(o.arrow_concavity, 0.0, "arrowhead Concavity"); +} + +#[test] +fn fresh_settings_give_the_reference_line_defaults() { + assert_line_defaults(&ToolOptions::default()); +} + +#[test] +fn reset_tool_gives_the_reference_line_defaults() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.ui.tool = Tool::Line; + let o = &mut app.ui.tool_options; + (o.line_weight, o.arrow_start, o.arrow_end, o.arrow_width, o.arrow_length, o.arrow_concavity) = (3.0, true, true, 52.0, 50.0, 40.0); + crate::menus::invoke(&mut app, &egui::Context::default(), crate::tools::tool_reset::RESET, json!({})).unwrap(); + assert_line_defaults(&app.ui.tool_options); +} + +#[test] +fn a_default_drag_with_end_on_makes_a_1_px_shaft_and_a_10_by_5_px_head() { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 800, "height": 600})).unwrap(); + app.ui.tool = Tool::Line; + app.ui.tool_options.arrow_end = true; + let none = Modifiers::NONE; + tool_event(&mut app, ToolEvent::Down { x: 400.0, y: 300.0, pressure: 1.0 }, none); + tool_event(&mut app, ToolEvent::Move { x: 600.0, y: 300.0, pressure: 1.0 }, none); + tool_event(&mut app, ToolEvent::Up { x: 600.0, y: 300.0 }, none); + + let st = app.session.active().unwrap(); + let layer = st.doc.layer(st.active_layer.unwrap()).unwrap(); + let LayerContent::Shape(shape) = &layer.content else { panic!("a shape layer: {:?}", layer.content) }; + let Some(LiveShape::ArrowLine { from, to, weight, start, end, width, length, concavity }) = shape.live.clone() else { + panic!("a live arrow line: {:?}", shape.live) + }; + assert_eq!((weight, start, end, width, length, concavity), (1.0, false, true, 5.0, 10.0, 0.0)); + assert_eq!(to[0], 600.0, "the head's tip is at the drag's end"); + assert_eq!(from[1], to[1], "a horizontal line"); + + // The shaft, then the head: its tip at 600, 10 px long and 5 px wide. + let [shaft, head] = &shape.path.subpaths[..] else { panic!("a shaft and one head: {:?}", shape.path) }; + let bounds = |sp: &photocraft_doc::vector::Subpath| photocraft_doc::vector::Path::new(vec![sp.clone()]).control_bounds().unwrap(); + let (_, sy0, _, sy1) = bounds(shaft); + assert_eq!(sy1 - sy0, 1.0, "a 1 px shaft"); + let (hx0, hy0, hx1, hy1) = bounds(head); + assert_eq!((hx0, hx1), (590.0, 600.0), "a head 10 px long ending at the tip"); + assert_eq!(hy1 - hy0, 5.0, "a head 5 px wide"); +} + +#[test] +fn line_options_saved_before_the_new_defaults_keep_their_values() { + let saved = json!({"line_weight": 3.0, "arrow_end": true, "arrow_width": 52.0, "arrow_length": 50.0, "arrow_concavity": 25.0}); + let o: ToolOptions = serde_json::from_value(saved).unwrap(); + assert_eq!((o.line_weight, o.arrow_end, o.arrow_width, o.arrow_length, o.arrow_concavity), (3.0, true, 52.0, 50.0, 25.0)); + assert!(!o.arrow_start, "a field the file lacks takes its default"); +} + +#[test] +fn line_options_missing_from_a_saved_file_take_the_new_defaults() { + let o: ToolOptions = serde_json::from_value(json!({"tolerance": 10.0})).unwrap(); + assert_line_defaults(&o); +} diff --git a/crates/ui-egui/src/tools/perspective_crop_click_preview_tests.rs b/crates/ui-egui/src/tools/perspective_crop_click_preview_tests.rs index aef086e406..395498c0a3 100644 --- a/crates/ui-egui/src/tools/perspective_crop_click_preview_tests.rs +++ b/crates/ui-egui/src/tools/perspective_crop_click_preview_tests.rs @@ -188,3 +188,22 @@ fn hover_over_the_canvas_moves_the_preview() { assert!((q[2][0] - 110.0).abs() < 0.5 && (q[2][1] - 100.0).abs() < 0.5, "{q:?}"); assert_eq!(q[2], q[3]); } + +/// #13065: a drag that builds no box, which is what a start the snap moved onto its release +/// point gives, keeps the corners clicked so far, so the next click still finishes the quad. +#[test] +fn a_drag_that_makes_no_box_keeps_the_clicked_corners() { + let mut app = app(); + for p in [A, B, C] { + click(&mut app, p); + } + // A straight drag has no area, so `new_box` returns None and no quad replaces the clicks. + pointer(&mut app, ToolEvent::Down { x: 60.0, y: 70.0, pressure: 1.0 }, egui::Modifiers::NONE); + pointer(&mut app, ToolEvent::Move { x: 120.0, y: 70.0, pressure: 1.0 }, egui::Modifiers::NONE); + pointer(&mut app, ToolEvent::Up { x: 120.0, y: 70.0 }, egui::Modifiers::NONE); + assert_eq!(app.ui.perspective_crop, None, "a drag with no area builds no box"); + assert_eq!(app.pcrop.clicks, vec![A, B, C], "the three clicks stay"); + click(&mut app, D); + assert!(app.pcrop.clicks.is_empty(), "the fourth click still finishes the quad"); + assert_eq!(app.ui.perspective_crop, Some([A, B, C, D])); +} diff --git a/crates/ui-egui/src/tools/perspective_crop_ui.rs b/crates/ui-egui/src/tools/perspective_crop_ui.rs index 2906dcdcce..a58e462b7a 100644 --- a/crates/ui-egui/src/tools/perspective_crop_ui.rs +++ b/crates/ui-egui/src/tools/perspective_crop_ui.rs @@ -189,9 +189,12 @@ pub fn pointer(app: &mut PhotocraftApp, ev: ToolEvent, mods: egui::Modifiers) -> app.ui.perspective_crop = Some(ordered([a, b, c, d])); app.pcrop.clicks.clear(); } - } else { + } else if let Some(quad) = new_box(start, cur, square, centred) { + // Only a drag that built a box replaces the corners clicked so far. One that + // made none (a start the snap moved onto its release point) leaves them, so the + // next click still finishes the quad (#13065). app.pcrop.clicks.clear(); - app.ui.perspective_crop = new_box(start, cur, square, centred); + app.ui.perspective_crop = Some(quad); } } app.pcrop.drag = None; diff --git a/crates/ui-egui/src/tools/tool_reset.rs b/crates/ui-egui/src/tools/tool_reset.rs index b40ecb59af..0351a0eeae 100644 --- a/crates/ui-egui/src/tools/tool_reset.rs +++ b/crates/ui-egui/src/tools/tool_reset.rs @@ -132,7 +132,11 @@ fn is_selection_tool(tool: Tool) -> bool { ) } -/// Put `tool`'s fields of `o` back to their defaults. +/// Options a tool preset stores but Reset Tool leaves, as in Photoshop: the Zoom tool keeps Zoom +/// Out selected (#12066). +const KEPT_BY_RESET: &[&str] = &["zoom_in"]; + +/// Put `tool`'s fields of `o` back to their defaults, except those [`KEPT_BY_RESET`]. pub fn reset_options(o: &mut ToolOptions, tool: Tool) { let keys = option_keys(tool); if keys.is_empty() { @@ -141,7 +145,7 @@ pub fn reset_options(o: &mut ToolOptions, tool: Tool) { let (Ok(Value::Object(mut cur)), Ok(Value::Object(d))) = (serde_json::to_value(&*o), serde_json::to_value(ToolOptions::default())) else { return; }; - for k in keys { + for k in keys.iter().filter(|k| !KEPT_BY_RESET.contains(k)) { if let Some(v) = d.get(*k) { cur.insert((*k).to_string(), v.clone()); } @@ -167,8 +171,8 @@ pub fn sample_all_key(tool: Tool) -> Option { m.into_iter().find(|(k, v)| b.get(k) != Some(v)).map(|(k, _)| k) } -/// The [`ToolOptions`] fields `tool` shows, by their serialized names: what Reset Tool resets and -/// what a tool preset made with + stores (#7356). +/// The [`ToolOptions`] fields `tool` shows, by their serialized names: what Reset Tool resets (but +/// for [`KEPT_BY_RESET`]) and what a tool preset made with + stores (#7356). pub fn option_keys(tool: Tool) -> &'static [&'static str] { // `reset!` names each field once; one that is misspelt or gone fails to compile. macro_rules! reset { @@ -226,7 +230,7 @@ pub fn option_keys(tool: Tool) -> &'static [&'static str] { Tool::Type | Tool::VerticalType | Tool::HorizontalTypeMask | Tool::VerticalTypeMask => { reset!(type_font, type_style, type_size, type_aa, type_align, type_direction, type_style_defaults) } - Tool::Zoom => reset!(zoom_scrubby), + Tool::Zoom => reset!(zoom_scrubby, zoom_in), Tool::Hand => reset!(hand_scroll_all), Tool::SpotHealing => reset!(spot_type), Tool::Healing => reset!(clone_aligned, clone_sample), diff --git a/crates/ui-egui/src/tools/type_tool.rs b/crates/ui-egui/src/tools/type_tool.rs index 60dbb231ed..636c0f3e75 100644 --- a/crates/ui-egui/src/tools/type_tool.rs +++ b/crates/ui-egui/src/tools/type_tool.rs @@ -144,6 +144,8 @@ mod font_commit_tests; mod font_picker_tests; #[cfg(test)] mod options_tooltips_tests; +#[cfg(test)] +mod panels_toggle_tests; #[cfg(test)] mod tests; diff --git a/crates/ui-egui/src/tools/type_tool/options_bar.rs b/crates/ui-egui/src/tools/type_tool/options_bar.rs index 4a1687dbd4..56b54b5c27 100644 --- a/crates/ui-egui/src/tools/type_tool/options_bar.rs +++ b/crates/ui-egui/src/tools/type_tool/options_bar.rs @@ -167,6 +167,14 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui) { app.ui.status = e; app.ui.status_error = true; } + // The bar's last button, as in Photoshop (#12054): Window › Character, which shows the + // Character | Paragraph group with Character in front, and hides it when clicked again. + if crate::icons::button(ui, "panels-top-left", 24.0, false, tl!("Toggle Character and Paragraph panels")).clicked() + && let Err(e) = crate::menus::invoke(app, &ui.ctx().clone(), "window.panel.character", json!({})) + { + app.ui.status = e; + app.ui.status_error = true; + } if app.ui.text_edit.is_some() { ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| { ui.add_space(8.0); diff --git a/crates/ui-egui/src/tools/type_tool/panels_toggle_tests.rs b/crates/ui-egui/src/tools/type_tool/panels_toggle_tests.rs new file mode 100644 index 0000000000..893a5a90ba --- /dev/null +++ b/crates/ui-egui/src/tools/type_tool/panels_toggle_tests.rs @@ -0,0 +1,149 @@ +//! #12054: the Type options bar ends with the reference application's button that shows and +//! hides the Character and Paragraph panels. It runs Window › Character, so the cases the issue +//! leaves unmeasured keep that command's behaviour. + +use egui::accesskit::Role; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use photocraft_doc::LayerId; +use serde_json::json; + +use crate::PhotocraftApp; + +const TOGGLE: &str = "Toggle Character and Paragraph panels"; + +fn bare_app() -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.ui.tool = crate::state::Tool::Type; + app +} + +/// An app with one selected type layer, and the layer's id. +fn app_with_layer() -> (PhotocraftApp, LayerId) { + let mut app = bare_app(); + app.run("file.new", json!({"width": 200, "height": 100})).unwrap(); + let made = app.run("type.create", json!({"text": "Sample", "font": "Inter", "size": 18})).unwrap(); + let id = LayerId(made["layer"].as_u64().unwrap()); + app.run("layer.select", json!({"layer": id.0, "mode": "replace"})).unwrap(); + (app, id) +} + +fn editing(mut app: PhotocraftApp, id: LayerId) -> PhotocraftApp { + app.ui.text_edit = Some(crate::state::TextEdit { + layer: id.0, + document: None, + caret: 2, + anchor: 2, + session: "panels-toggle".into(), + created: false, + mask: false, + dragging: false, + resize: None, + preedit: None, + }); + app +} + +/// The options bar in a row, once the app's fonts are set up (the first pass has none). +fn harness(app: PhotocraftApp) -> Harness<'static, PhotocraftApp> { + let mut h = Harness::builder().with_size(vec2(1400.0, 200.0)).with_max_steps(16).build_ui_state( + |ui, app| { + if ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + ui.horizontal(|ui| super::options_bar::options_bar(app, ui)); + } + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + h.run_steps(4); + h +} + +fn click(h: &mut Harness<'static, PhotocraftApp>) { + h.get_by_role_and_label(Role::Button, TOGGLE).click(); + h.run(); +} + +/// Whether the Character | Paragraph group is shown, and its front tab (0 Character, 1 Paragraph). +fn group(h: &Harness<'static, PhotocraftApp>) -> (bool, usize) { + (h.state().ui.panels.character, h.state().ui.dock_tabs.character) +} + +/// Clicks the button twice: the group opens with Character in front, then closes. +fn opens_then_closes(app: PhotocraftApp) { + let mut h = harness(app); + assert!(!group(&h).0, "the group starts hidden"); + click(&mut h); + assert_eq!(group(&h), (true, 0)); + click(&mut h); + assert!(!group(&h).0, "the second click hides the group"); +} + +#[test] +fn the_button_follows_create_warped_text_with_the_reference_tooltip() { + let (app, _) = app_with_layer(); + let h = harness(app); + let warp = h.get_by_role_and_label(Role::Button, "Create warped text").rect(); + let toggle = h.get_by_role_and_label(Role::Button, TOGGLE); + let rect = toggle.rect(); + assert!(rect.left() >= warp.right(), "{rect:?} is not after {warp:?}"); + assert!((rect.center().y - warp.center().y).abs() < 1.0, "{rect:?} is not in the row of {warp:?}"); + // Nothing sits between the two. + let between = h.query_all_by_role(Role::Button).filter(|b| b.rect().left() >= warp.right() && b.rect().right() <= rect.left()).count(); + assert_eq!(between, 0); + assert_eq!(toggle.accesskit_node().description().map(|d| d.to_string()), Some(TOGGLE.to_owned())); +} + +#[test] +fn with_a_type_layer_it_opens_the_group_with_character_in_front_then_closes_it() { + opens_then_closes(app_with_layer().0); +} + +#[test] +fn without_a_document_it_opens_and_closes_the_group() { + opens_then_closes(bare_app()); +} + +#[test] +fn while_editing_text_it_opens_and_closes_the_group() { + let (app, id) = app_with_layer(); + opens_then_closes(editing(app, id)); +} + +/// While editing, Cancel and Commit stay at the bar's right end, after the toggle. +#[test] +fn while_editing_cancel_and_commit_follow_the_toggle() { + let (app, id) = app_with_layer(); + let h = harness(editing(app, id)); + let toggle = h.get_by_role_and_label(Role::Button, TOGGLE).rect(); + for label in ["Cancel any current edits (Esc)", "Commit any current edits (⌘↩)"] { + let r = h.query_all_by_role(Role::Button).find(|b| b.accesskit_node().label().is_some_and(|l| l.starts_with(&label[..12]))); + let r = r.unwrap_or_else(|| panic!("no {label}")).rect(); + assert!(r.left() >= toggle.right(), "{label} {r:?} is before the toggle {toggle:?}"); + } +} + +/// Not measured: with Paragraph in front, the button does what Window › Character does and +/// brings Character to the front of the open group. +#[test] +fn with_paragraph_in_front_it_brings_character_forward_like_window_character() { + let (mut app, _) = app_with_layer(); + let ctx = egui::Context::default(); + crate::menus::invoke(&mut app, &ctx, "window.panel.paragraph", json!({})).unwrap(); + let mut h = harness(app); + assert_eq!(group(&h), (true, 1)); + click(&mut h); + assert_eq!(group(&h), (true, 0)); +} + +#[test] +fn the_toggle_leaves_the_document_alone() { + let (app, _) = app_with_layer(); + let steps = app.session.active().unwrap().history.entries().len(); + let mut h = harness(app); + click(&mut h); + click(&mut h); + assert_eq!(h.state().session.active().unwrap().history.entries().len(), steps); + assert!(!h.state().ui.status_error, "{}", h.state().ui.status); +} diff --git a/crates/ui-egui/src/tools/vector_ui/freeform_close_tolerance_tests.rs b/crates/ui-egui/src/tools/vector_ui/freeform_close_tolerance_tests.rs new file mode 100644 index 0000000000..dd47cb0fac --- /dev/null +++ b/crates/ui-egui/src/tools/vector_ui/freeform_close_tolerance_tests.rs @@ -0,0 +1,95 @@ +//! #12830: a Freeform Pen stroke closes only when it is released within 3 screen px of its start +//! on each axis, as in Photoshop. Other zoom levels keep the screen-based scaling. + +use egui::Modifiers; +use photocraft_doc::vector::Subpath; +use serde_json::json; + +use crate::PhotocraftApp; +use crate::canvas::{ToolEvent, tool_event}; +use crate::state::Tool; + +/// The measured document: 800 × 600 px with the Freeform Pen in Path mode at `zoom`. +fn app(zoom: f32) -> PhotocraftApp { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.session.execute("file.new", json!({"width": 800, "height": 600})).unwrap(); + app.sync_views(); + app.ui.views[0].zoom = zoom; + app.ui.tool = Tool::FreeformPen; + app.ui.tool_options.vector_mode = "path".into(); + app +} + +/// The measured stroke: a circle around (600, 300) of radius 100 from (700, 300) in 60 moves, +/// released `off` document px from its start. Returns the stroke's subpath. +fn circle(app: &mut PhotocraftApp, off: [f64; 2]) -> Subpath { + let mods = Modifiers::NONE; + tool_event(app, ToolEvent::Down { x: 700.0, y: 300.0, pressure: 1.0 }, mods); + for i in 1..60 { + let a = std::f64::consts::TAU * f64::from(i) / 60.0; + tool_event(app, ToolEvent::Move { x: 600.0 + 100.0 * a.cos(), y: 300.0 + 100.0 * a.sin(), pressure: 1.0 }, mods); + } + let [x, y] = [700.0 + off[0], 300.0 + off[1]]; + tool_event(app, ToolEvent::Move { x, y, pressure: 1.0 }, mods); + tool_event(app, ToolEvent::Up { x, y }, mods); + let st = app.session.active().unwrap(); + assert_eq!(st.history.undo_label(), Some("Freeform Pen"), "one History step"); + st.doc.work_path.as_ref().unwrap().subpaths.last().unwrap().clone() +} + +/// The measured cases at 100 %: within ±3 px on each axis (a square) closes, 4 px off does not. +#[test] +fn at_100_percent_a_release_within_3_px_on_each_axis_closes_the_circle() { + for off in [[0.0, 0.0], [3.0, 0.0], [0.0, -3.0], [3.0, 3.0], [-3.0, 3.0]] { + let mut app = app(1.0); + let n = app.session.active().unwrap().history.past_len(); + assert!(circle(&mut app, off).closed, "released {off:?} off the start closes"); + assert_eq!(app.session.active().unwrap().history.past_len(), n + 1); + } + for off in [[4.0, 0.0], [0.0, 4.0], [5.0, 0.0], [4.0, 4.0], [5.0, 3.0], [-4.0, 0.0]] { + assert!(!circle(&mut app(1.0), off).closed, "released {off:?} off the start stays open"); + } +} + +/// Not measured, kept as today: the box scales with zoom like the old reach, 3 screen px. +#[test] +fn at_other_zooms_the_3_px_box_is_in_screen_pixels() { + for (zoom, inside, outside) in [(2.0, [1.5, 1.5], [2.0, 0.0]), (0.5, [6.0, 6.0], [0.0, 8.0])] { + assert!(circle(&mut app(zoom), inside).closed, "{inside:?} off at {zoom}× closes"); + assert!(!circle(&mut app(zoom), outside).closed, "{outside:?} off at {zoom}× stays open"); + } +} + +/// Not measured: a trace with ⌥-clicked straight segments closes like a freehand one. It ends in +/// a freehand run released near the start: an ⌥-click there would be the outline's own grab. +#[test] +fn a_trace_with_straight_segments_closes_within_the_same_box() { + for (off, closed) in [([3.0, 3.0], true), ([4.0, 0.0], false)] { + let mut app = app(1.0); + for [x, y] in [[100.0, 100.0], [300.0, 100.0], [300.0, 300.0]] { + tool_event(&mut app, ToolEvent::Down { x, y, pressure: 1.0 }, Modifiers::ALT); + tool_event(&mut app, ToolEvent::Up { x, y }, Modifiers::ALT); + } + tool_event(&mut app, ToolEvent::Down { x: 100.0, y: 300.0, pressure: 1.0 }, Modifiers::ALT); + let end = [100.0 + off[0], 100.0 + off[1]]; + for i in 1..=10 { + let y = 300.0 + (end[1] - 300.0) * f64::from(i) / 10.0; + tool_event(&mut app, ToolEvent::Move { x: 100.0 + off[0] * f64::from(i) / 10.0, y, pressure: 1.0 }, Modifiers::ALT); + } + tool_event(&mut app, ToolEvent::Up { x: end[0], y: end[1] }, Modifiers::NONE); + let st = app.session.active().unwrap(); + assert_eq!(st.history.undo_label(), Some("Freeform Pen"), "one History step"); + let sub = &st.doc.work_path.as_ref().unwrap().subpaths[0]; + assert_eq!(sub.knots[0].out_ctrl, sub.knots[0].anchor, "the first segment is straight"); + assert_eq!(sub.closed, closed, "released {off:?} off the start"); + } +} + +/// The release decides: a short last run that fitting shortens past the box still closes. +#[test] +fn a_release_in_the_box_closes_even_when_fitting_moves_the_last_anchor() { + let trace = [[100.0, 100.0], [200.0, 100.0], [200.0, 200.0], [103.01, 100.0], [103.0, 100.0]]; + let (pen, closed) = super::fit_with_straight_segments(&trace, &[1, 2, 3], 2.0, true); + assert!(closed); + assert_eq!(pen.knots.len(), 3, "the last anchor became the first one"); +} diff --git a/crates/ui-egui/src/tools/vector_ui/options.rs b/crates/ui-egui/src/tools/vector_ui/options.rs index fae9f13269..39519be0a6 100644 --- a/crates/ui-egui/src/tools/vector_ui/options.rs +++ b/crates/ui-egui/src/tools/vector_ui/options.rs @@ -402,7 +402,7 @@ pub fn shape_properties(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: photocra } } photocraft_doc::vector::LiveShape::Polygon { sides, star_ratio, corner_radius, .. } => { - // One radius rounds every vertex of a triangle, polygon or star, as in Photoshop. + // One radius rounds every vertex of a triangle or polygon, or a star's outer points, as in Photoshop. ui.horizontal(|ui| { let mut r = *corner_radius as f32; if num(ui, tl!("Corner radius"), &mut r, 0.0..=100000.0, "px") { diff --git a/crates/ui-egui/src/tools/vector_ui/pen.rs b/crates/ui-egui/src/tools/vector_ui/pen.rs index 6c99f9c5a4..28203f6441 100644 --- a/crates/ui-egui/src/tools/vector_ui/pen.rs +++ b/crates/ui-egui/src/tools/vector_ui/pen.rs @@ -818,9 +818,13 @@ pub(crate) fn freeform_finish_owned(app: &mut PhotocraftApp, points: &[[f64; 3]] } let trace: Vec<[f64; 2]> = points.iter().map(|p| [p[0], p[1]]).collect(); let (Some(first), Some(last)) = (trace.first(), trace.last()) else { return }; - let tol = 6.0 / app.point_zoom().max(0.01) as f64; + let zoom = app.point_zoom().max(0.01) as f64; + // Photoshop closes a release within 3 screen px of the start on each axis, a square (#12830). + let reach = 3.0 / zoom; + // The trace must still be longer than the former 4 × 6 screen px to close: unchanged. + let min_length = 24.0 / zoom; let length: f64 = trace.windows(2).map(|w| (w[1][0] - w[0][0]).hypot(w[1][1] - w[0][1])).sum(); - let closed = (first[0] - last[0]).hypot(first[1] - last[1]) < tol && length > 4.0 * tol; + let closed = near_start(first, last, reach) && length > min_length; let fit = f64::from(app.ui.tool_options.curve_fit); let pen = if straight.is_empty() { let Some(sub) = photocraft_vector::trace::fit_trace(&trace, fit, closed) else { return }; @@ -828,7 +832,7 @@ pub(crate) fn freeform_finish_owned(app: &mut PhotocraftApp, points: &[[f64; 3]] let unlinked = sub.knots.iter().enumerate().filter(|(_, k)| !k.smooth).map(|(i, _)| i).collect(); (PenPath { knots, unlinked, ..Default::default() }, sub.closed) } else { - fit_with_straight_segments(&trace, straight, fit, closed.then_some(tol)) + fit_with_straight_segments(&trace, straight, fit, closed) }; let (mut pen, closed) = pen; pen.owner = Some(owner); @@ -839,14 +843,22 @@ pub(crate) fn freeform_finish_owned(app: &mut PhotocraftApp, points: &[[f64; 3]] } } +/// Is the Freeform Pen's `end` within `reach` of its `start` on both axes? +fn near_start(start: &[f64; 2], end: &[f64; 2], reach: f64) -> bool { + // The screen-to-document conversion runs in f32, so a release exactly `reach` off can land a hair past it. + let reach = reach + 1e-3; + (start[0] - end[0]).abs() <= reach && (start[1] - end[1]).abs() <= reach +} + fn knot_points(k: &photocraft_doc::Knot) -> [[f64; 2]; 3] { [[k.anchor.x, k.anchor.y], [k.in_ctrl.x, k.in_ctrl.y], [k.out_ctrl.x, k.out_ctrl.y]] } /// A Freeform Pen trace with ⌥-clicked straight segments (into the points at `straight`): each /// freehand run between them is fitted on its own, and the runs are joined by straight lines -/// between corner anchors. `close` (a reach) closes the path when it ends on its start point. -fn fit_with_straight_segments(trace: &[[f64; 2]], straight: &[usize], fit: f64, close: Option) -> (PenPath, bool) { +/// between corner anchors. `close`: the release was near the start, so the last anchor becomes +/// the first one. The fitted last anchor is not tested again: fitting can move it past the reach. +fn fit_with_straight_segments(trace: &[[f64; 2]], straight: &[usize], fit: f64, close: bool) -> (PenPath, bool) { let mut cuts: Vec = straight.iter().copied().filter(|&i| i > 0 && i < trace.len()).collect(); cuts.sort_unstable(); cuts.dedup(); @@ -877,12 +889,7 @@ fn fit_with_straight_segments(trace: &[[f64; 2]], straight: &[usize], fit: f64, } start = end; } - // Ended on the start point: the last anchor is the first one. - let ends_on_start = |k: &[[[f64; 2]; 3]], reach: f64| match (k.first(), k.last()) { - (Some(a), Some(b)) => k.len() > 3 && (a[0][0] - b[0][0]).hypot(a[0][1] - b[0][1]) < reach, - _ => false, - }; - let closed = close.is_some_and(|reach| ends_on_start(&knots, reach)); + let closed = close && knots.len() > 3; if closed && let Some(last) = knots.pop() { if let Some(k) = knots.first_mut() { k[1] = [last[1][0] - last[0][0] + k[0][0], last[1][1] - last[0][1] + k[0][1]]; @@ -986,3 +993,7 @@ mod freeform_history_name_tests; #[cfg(test)] #[path = "pen_alt_drag_segment_tests.rs"] mod pen_alt_drag_segment_tests; + +#[cfg(test)] +#[path = "freeform_close_tolerance_tests.rs"] +mod freeform_close_tolerance_tests; diff --git a/crates/ui-egui/src/tools/vector_ui/shapes.rs b/crates/ui-egui/src/tools/vector_ui/shapes.rs index 0776227d04..3d80360ea5 100644 --- a/crates/ui-egui/src/tools/vector_ui/shapes.rs +++ b/crates/ui-egui/src/tools/vector_ui/shapes.rs @@ -152,7 +152,8 @@ pub fn finish_shape(app: &mut PhotocraftApp, tool: Tool, start: [f64; 2], end: [ .unwrap_or_else(|| photocraft_doc::vector::Path { fill_rule: outline.fill_rule, ..Default::default() }); let outline = as_one_component(&outline, path.fill_rule).unwrap_or(outline); path.subpaths.extend(outline.subpaths); - let r = app.run("path.set", json!({"name": "work", "path": photocraft_engine::vector_cmds::path_json(&path)})); + let path = photocraft_engine::vector_cmds::path_json(&path); + let r = app.run("path.set", json!({"name": "work", "path": path, "historyName": line_history_name(tool)})); match r { Ok(_) => app.ui.selected_path = Some("work".into()), Err(e) => { @@ -171,12 +172,19 @@ pub fn finish_shape(app: &mut PhotocraftApp, tool: Tool, start: [f64; 2], end: [ } return; } + p["historyName"] = json!(line_history_name(tool)); if let Err(e) = create_shape(app, p) { app.ui.status = e; app.ui.status_error = true; } } +/// A Line tool drag is one History step named after the tool, as in Photoshop (#13244); the +/// other Shape tools keep the commands' own names. +fn line_history_name(tool: Tool) -> Option<&'static str> { + (tool == Tool::Line).then_some("Line Tool") +} + pub(super) fn fill_param(app: &PhotocraftApp) -> Value { if app.ui.tool_options.shape_fill { tool_paint_param(app, false) } else { Value::Null } } diff --git a/crates/ui-egui/src/tools/zoom_tool.rs b/crates/ui-egui/src/tools/zoom_tool.rs index 553e9ad781..e2b86f3b1b 100644 --- a/crates/ui-egui/src/tools/zoom_tool.rs +++ b/crates/ui-egui/src/tools/zoom_tool.rs @@ -2,8 +2,9 @@ //! //! With Scrubby Zoom on (the default, as in Photoshop) press-and-drag zooms continuously: right //! zooms in, left zooms out, anchored at the point where the button went down. With it off, the -//! drag draws a rectangle and the release zooms to fit it. A click (no drag) still steps the zoom -//! in, or out with ⌥ (handled by the canvas). +//! drag draws a rectangle and the release zooms to fit it, unless it zooms out (Zoom Out mode, or +//! ⌥ in Zoom In mode): then the release steps out once at the press point. A click (no drag) +//! steps the zoom in, or out in Zoom Out mode, ⌥ turning either around (handled by the canvas). use egui::{Pos2, Rect, vec2}; @@ -25,6 +26,8 @@ struct ZoomDrag { zoom0: f32, /// Scrubby Zoom off: a zoom rectangle, its current corner. rect_to: Option, + /// The release steps out (Zoom Out mode, or ⌥ in Zoom In mode): no rectangle is shown. + out: bool, } fn id() -> egui::Id { @@ -51,18 +54,29 @@ pub fn anchor_view(view: &mut View, xf: &ViewXform, screen: Pos2, doc: [f64; 2], } /// Route the canvas buttons for the Zoom tool. Returns true when it consumed the drag (the -/// canvas then handles only the click). -pub fn drag(app: &PhotocraftApp, ctx: &egui::Context, view: &mut View, xf: &ViewXform, b: &Buttons, pointer: Option) -> bool { +/// canvas then handles only the click). `zoom_out` is the canvas's direction for ⌥ held or not +/// (temporary zoom key, Zoom In / Zoom Out mode, latched ⌥). +pub fn drag( + app: &PhotocraftApp, + ctx: &egui::Context, + view: &mut View, + xf: &ViewXform, + b: &Buttons, + pointer: Option, + zoom_out: &dyn Fn(bool) -> bool, +) -> bool { let scrubby = app.ui.tool_options.zoom_scrubby; + let out = zoom_out(ctx.input(|i| i.modifiers.alt)); if b.started { let anchor = ctx.input(|i| i.pointer.press_origin()).filter(|p| xf.rect.contains(*p)).or(pointer); if let Some(anchor) = anchor { - let z = ZoomDrag { anchor, doc: xf.to_doc(anchor), zoom0: view.zoom, rect_to: (!scrubby).then_some(anchor) }; + let z = ZoomDrag { anchor, doc: xf.to_doc(anchor), zoom0: view.zoom, rect_to: (!scrubby).then_some(anchor), out }; ctx.data_mut(|d| d.insert_temp(id(), z)); } } let Some(mut z) = ctx.data(|d| d.get_temp::(id())) else { return b.started || b.dragged || b.stopped }; if let Some(p) = pointer.filter(|_| b.dragged || b.stopped) { + z.out = out; match z.rect_to.as_mut() { Some(to) => *to = p, None => { @@ -79,7 +93,6 @@ pub fn drag(app: &PhotocraftApp, ctx: &egui::Context, view: &mut View, xf: &View if b.stopped { ctx.data_mut(|d| d.remove::(id())); if let Some(to) = z.rect_to { - let out = crate::workspace_ui::sticky_mods(app, ctx.input(|i| i.modifiers)).alt; zoom_to_rect(view, xf, Rect::from_two_pos(z.anchor, to), z.anchor, out, app.ppp); } } @@ -87,7 +100,7 @@ pub fn drag(app: &PhotocraftApp, ctx: &egui::Context, view: &mut View, xf: &View } /// Scrubby Zoom off: zoom so the dragged rectangle fills the canvas (a tiny one steps the zoom -/// at the press point; ⌥ steps out). +/// at the press point; `out` steps out there). fn zoom_to_rect(view: &mut View, xf: &ViewXform, r: Rect, anchor: Pos2, out: bool, ppp: f32) { if out || r.width() < 4.0 || r.height() < 4.0 { let doc = xf.to_doc(anchor); @@ -103,12 +116,19 @@ fn zoom_to_rect(view: &mut View, xf: &ViewXform, r: Rect, anchor: Pos2, out: boo /// Scrubby Zoom off: the zoom rectangle being dragged, as marching ants. pub fn draw(ctx: &egui::Context, painter: &egui::Painter) { - let Some(z) = ctx.data(|d| d.get_temp::(id())) else { return }; - let Some(to) = z.rect_to else { return }; - let r = Rect::from_two_pos(z.anchor, to); + let Some(r) = shown_rect(ctx) else { return }; let r = Rect::from_min_max(r.min.round() + vec2(0.5, 0.5), r.max.round() + vec2(0.5, 0.5)); crate::tool_feedback::draw_ants(painter, &[r.left_top(), r.right_top(), r.right_bottom(), r.left_bottom()], true); } +/// The zoom rectangle on screen, if any: none for a drag that steps out at its release. +fn shown_rect(ctx: &egui::Context) -> Option { + let z = ctx.data(|d| d.get_temp::(id()))?; + let to = z.rect_to.filter(|_| !z.out)?; + Some(Rect::from_two_pos(z.anchor, to)) +} + #[cfg(test)] mod tests; +#[cfg(test)] +mod zoom_out_mode_tests; diff --git a/crates/ui-egui/src/tools/zoom_tool/zoom_out_mode_tests.rs b/crates/ui-egui/src/tools/zoom_tool/zoom_out_mode_tests.rs new file mode 100644 index 0000000000..44beb97553 --- /dev/null +++ b/crates/ui-egui/src/tools/zoom_tool/zoom_out_mode_tests.rs @@ -0,0 +1,285 @@ +//! Zoom tool › Zoom In / Zoom Out (#12066): a pair of toggles on the options bar. In Zoom Out mode +//! a click steps out and ⌥+click steps in, the cursor is the "-" magnifier ("+" with ⌥), and a +//! drag with Scrubby Zoom off steps out once at the press point, as ⌥+drag does in Zoom In mode. + +use super::*; +use egui::{Event, Key, Modifiers, PointerButton}; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use serde_json::json; + +use crate::state::{Tool, ToolOptions}; + +const DOC: [u32; 2] = [400, 300]; + +fn harness(tool: Tool, zoom_in: bool, scrubby: bool) -> Harness<'static, PhotocraftApp> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": DOC[0], "height": DOC[1]})).unwrap(); + // No animation, the clicked point stays under the pointer, and the view is never clamped: + // every step lands on the first frame where the tests can compare it. + app.run("prefs.set", json!({"values": {"general.animatedZoom": false, "tools.zoomClickedPointToCenter": false, "tools.overscroll": true}})).unwrap(); + app.sync_views(); + app.ui.extras.rulers = false; + app.ui.tool = tool; + app.ui.tool_options.zoom_in = zoom_in; + app.ui.tool_options.zoom_scrubby = scrubby; + let mut h = Harness::builder().with_size(vec2(1000.0, 700.0)).build_ui_state( + |ui, app: &mut PhotocraftApp| { + let ctx = ui.ctx().clone(); + if !ctx.fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) { + return; + } + crate::shortcuts::handle(app, &ctx); + egui::CentralPanel::default().show(ui, |ui| crate::canvas::document_area(app, ui)); + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, crate::theme::ThemeKind::ALL[0]); + h.run_steps(4); + let v = &mut h.state_mut().ui.views[0]; + v.zoom = 1.0; + v.center = [200.0, 150.0]; + v.fit_pending = false; + v.fill_pending = false; + h.run_steps(2); + h +} + +fn xf(h: &Harness<'static, PhotocraftApp>) -> ViewXform { + ViewXform::active(h.state()).unwrap() +} + +/// The platform's modifiers for `Cmd` (⌘ on the Mac, Ctrl elsewhere), as egui-winit reports them. +fn platform(m: Modifiers) -> Modifiers { + let mut out = Modifiers { alt: m.alt, shift: m.shift, ctrl: m.ctrl, ..Default::default() }; + if m.command { + out.command = true; + if cfg!(target_os = "macos") { + out.mac_cmd = true; + } else { + out.ctrl = true; + } + } + out +} + +fn button(h: &mut Harness<'static, PhotocraftApp>, p: Pos2, pressed: bool, m: Modifiers) { + h.event(Event::PointerButton { pos: p, button: PointerButton::Primary, pressed, modifiers: platform(m) }); + h.step(); +} + +fn click(h: &mut Harness<'static, PhotocraftApp>, p: Pos2, m: Modifiers) { + h.event(Event::ModifiersChanged(platform(m))); + h.event(Event::PointerMoved(p)); + h.step(); + button(h, p, true, m); + button(h, p, false, m); + h.event(Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(2); +} + +/// The view after one click at `p` with `m`, from zoom 1 centred on the document. +fn view_after_click(zoom_in: bool, m: Modifiers) -> (f32, [f32; 2]) { + let mut h = harness(Tool::Zoom, zoom_in, true); + let p = h.state().last_canvas_rect.center() + vec2(90.0, -45.0); + click(&mut h, p, m); + let v = &h.state().ui.views[0]; + (v.zoom, v.center) +} + +#[test] +fn zoom_out_mode_click_steps_out_and_alt_click_steps_in() { + let mut h = harness(Tool::Zoom, false, true); + let p = h.state().last_canvas_rect.center() + vec2(90.0, -45.0); + let doc = xf(&h).to_doc(p); + + click(&mut h, p, Modifiers::NONE); + let out = crate::zoom_levels::step(1.0, -1, DOC); + assert!(out < 1.0); + assert_eq!(h.state().current_zoom(), out, "a click steps one stop out"); + assert!(xf(&h).to_screen(doc[0] as f32, doc[1] as f32).distance(p) < 0.5, "about the clicked point"); + + click(&mut h, p, Modifiers::ALT); + assert_eq!(h.state().current_zoom(), crate::zoom_levels::step(out, 1, DOC), "⌥+click steps one stop in"); + assert!(xf(&h).to_screen(doc[0] as f32, doc[1] as f32).distance(p) < 0.5); + + assert_eq!(h.state().session.documents()[0].history.past_len(), 0, "zooming adds no history state"); +} + +#[test] +fn zoom_out_mode_click_is_zoom_in_mode_alt_click_and_the_reverse() { + assert_eq!(view_after_click(false, Modifiers::NONE), view_after_click(true, Modifiers::ALT)); + assert_eq!(view_after_click(false, Modifiers::ALT), view_after_click(true, Modifiers::NONE)); + // Zoom In mode keeps today's click: in, and out with ⌥. + assert_eq!(view_after_click(true, Modifiers::NONE).0, crate::zoom_levels::step(1.0, 1, DOC)); + assert_eq!(view_after_click(true, Modifiers::ALT).0, crate::zoom_levels::step(1.0, -1, DOC)); +} + +/// A cursor as the platform gets it: the icon, and the bitmap with its size where one is drawn. +type Cursor = (egui::CursorIcon, Option<([u16; 2], std::sync::Arc<[u8]>)>); + +/// The canvas cursor over the image with ⌥ held or not. +fn cursor(h: &mut Harness<'static, PhotocraftApp>, alt: bool) -> Cursor { + let p = h.state().last_canvas_rect.center() + vec2(alt as u8 as f32, 0.0); + h.event(Event::ModifiersChanged(if alt { Modifiers::ALT } else { Modifiers::NONE })); + h.event(Event::PointerMoved(p)); + h.run_steps(2); + let o = &h.output().platform_output; + (o.cursor_icon, o.cursor_image.clone().map(|i| (i.size, i.rgba))) +} + +#[test] +fn zoom_out_mode_cursor_is_the_minus_magnifier_and_plus_with_alt() { + let mut zoom_in = harness(Tool::Zoom, true, true); + let (plus, minus) = (cursor(&mut zoom_in, false), cursor(&mut zoom_in, true)); + assert_ne!(plus, minus, "the two magnifiers differ"); + let mut zoom_out = harness(Tool::Zoom, false, true); + assert_eq!(cursor(&mut zoom_out, false), minus, "Zoom Out mode shows \"-\""); + assert_eq!(cursor(&mut zoom_out, true), plus, "\"+\" while ⌥ is held"); +} + +/// Scrubby Zoom off: a drag from a point to 120 x 80 points away, with `m` held. Returns the +/// view at the release, and whether a zoom rectangle was on screen while dragging. +fn rect_drag(zoom_in: bool, m: Modifiers) -> ((f32, [f32; 2]), bool) { + let mut h = harness(Tool::Zoom, zoom_in, false); + let a = h.state().last_canvas_rect.center() + vec2(-80.0, -50.0); + let doc = xf(&h).to_doc(a); + h.event(Event::ModifiersChanged(platform(m))); + h.event(Event::PointerMoved(a)); + h.step(); + button(&mut h, a, true, m); + let mut shown = false; + for t in [0.25, 0.5, 1.0] { + h.event(Event::PointerMoved(a + vec2(120.0, 80.0) * t)); + h.step(); + shown |= shown_rect(&h.ctx).is_some(); + assert_eq!(h.state().current_zoom(), 1.0, "no zoom while dragging"); + } + button(&mut h, a + vec2(120.0, 80.0), false, m); + h.event(Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(2); + if !zoom_in || m.alt { + assert!(xf(&h).to_screen(doc[0] as f32, doc[1] as f32).distance(a) < 0.5, "anchored at the press point"); + } + let v = &h.state().ui.views[0]; + ((v.zoom, v.center), shown) +} + +#[test] +fn zoom_out_mode_drag_without_scrubby_zoom_steps_out_once_like_alt_drag() { + let (out_mode, out_shown) = rect_drag(false, Modifiers::NONE); + let (alt_drag, alt_shown) = rect_drag(true, Modifiers::ALT); + assert_eq!(out_mode.0, crate::zoom_levels::step(1.0, -1, DOC), "one stop out"); + assert_eq!(out_mode, alt_drag, "the same view as ⌥+drag in Zoom In mode"); + assert!(!out_shown && !alt_shown, "no zoom rectangle for a drag that steps out"); + // Zoom In mode keeps its zoom rectangle. + let (rect, rect_shown) = rect_drag(true, Modifiers::NONE); + assert!(rect_shown); + assert!(rect.0 > 1.0, "the rectangle zooms in: {}", rect.0); +} + +#[test] +fn temporary_zoom_keys_ignore_the_zoom_out_mode() { + let mut h = harness(Tool::Brush, false, true); + let p = h.state().last_canvas_rect.center(); + let key = |h: &mut Harness<'static, PhotocraftApp>, pressed: bool, m: Modifiers| { + let m = platform(m); + h.event(Event::ModifiersChanged(m)); + h.event(Event::Key { key: Key::Space, physical_key: None, pressed, repeat: false, modifiers: m }); + h.step(); + }; + key(&mut h, true, Modifiers::COMMAND); + click(&mut h, p, Modifiers::COMMAND); + key(&mut h, false, Modifiers::COMMAND); + h.event(Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(2); + let z = h.state().current_zoom(); + assert_eq!(z, crate::zoom_levels::step(1.0, 1, DOC), "⌘Space still zooms in"); + key(&mut h, true, Modifiers::COMMAND | Modifiers::ALT); + click(&mut h, p, Modifiers::COMMAND | Modifiers::ALT); + key(&mut h, false, Modifiers::COMMAND | Modifiers::ALT); + h.event(Event::ModifiersChanged(Modifiers::NONE)); + h.run_steps(2); + assert_eq!(h.state().current_zoom(), crate::zoom_levels::step(z, -1, DOC), "⌘⌥Space still zooms out"); + assert_eq!(h.state().ui.tool, Tool::Brush); + assert!(!h.state().ui.tool_options.zoom_in); +} + +#[test] +fn held_z_ignores_the_zoom_out_mode() { + let mut h = harness(Tool::Brush, false, true); + let p = h.state().last_canvas_rect.center(); + let z_key = |h: &mut Harness<'static, PhotocraftApp>, pressed: bool| { + h.event(Event::Key { key: Key::Z, physical_key: None, pressed, repeat: false, modifiers: Modifiers::NONE }); + h.run_steps(3); + }; + z_key(&mut h, true); + assert_eq!(h.state().ui.tool, Tool::Zoom, "Z held springs to the Zoom tool"); + click(&mut h, p, Modifiers::NONE); + z_key(&mut h, false); + let z = h.state().current_zoom(); + assert_eq!(z, crate::zoom_levels::step(1.0, 1, DOC), "a click with Z held still zooms in"); + assert_eq!(h.state().ui.tool, Tool::Brush); + z_key(&mut h, true); + click(&mut h, p, Modifiers::ALT); + z_key(&mut h, false); + assert_eq!(h.state().current_zoom(), crate::zoom_levels::step(z, -1, DOC), "⌥+click with Z held still zooms out"); + assert_eq!(h.state().ui.tool, Tool::Brush); + assert!(!h.state().ui.tool_options.zoom_in); +} + +fn options_bar() -> Harness<'static, PhotocraftApp> { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.ui.tool = Tool::Zoom; + let mut ready = false; + let mut h = Harness::builder().with_size(vec2(1400.0, 60.0)).build_ui_state( + move |ui, app: &mut PhotocraftApp| { + if !ready { + crate::theme::install_fonts(ui.ctx()); + crate::theme::apply(ui.ctx(), crate::theme::ThemeKind::ALL[0]); + ready = true; + return; + } + crate::panels::options_bar(app, ui); + }, + app, + ); + h.run_steps(4); + h +} + +fn left(h: &Harness<'static, PhotocraftApp>, label: &str) -> f64 { + h.get_by_label(label).accesskit_node().bounding_box().unwrap_or_else(|| panic!("{label} is laid out")).x0 +} + +#[test] +fn options_bar_has_the_zoom_in_and_zoom_out_pair_before_the_checkboxes() { + let mut h = options_bar(); + assert!(h.state().ui.tool_options.zoom_in, "Zoom In is pressed by default"); + let (zin, zout, fit) = (left(&h, "Zoom In"), left(&h, "Zoom Out"), left(&h, "Resize Windows to Fit")); + assert!(zin < zout && zout < fit, "Zoom In {zin}, Zoom Out {zout}, Resize Windows to Fit {fit}"); + + // Exactly one is pressed: clicking either selects it, clicking it again keeps it. + for (label, zoom_in) in [("Zoom Out", false), ("Zoom Out", false), ("Zoom In", true), ("Zoom In", true), ("Zoom Out", false)] { + h.get_by_label(label).click(); + h.run_steps(2); + assert_eq!(h.state().ui.tool_options.zoom_in, zoom_in, "after clicking {label}"); + } +} + +#[test] +fn zoom_mode_survives_reset_tool_and_defaults_to_zoom_in() { + let mut o = ToolOptions { zoom_in: false, zoom_scrubby: false, ..ToolOptions::default() }; + crate::tool_reset::reset_options(&mut o, Tool::Zoom); + assert!(o.zoom_scrubby, "Reset Tool resets Scrubby Zoom"); + assert!(!o.zoom_in, "but leaves Zoom Out selected"); + + assert!(ToolOptions::default().zoom_in); + let mut saved = serde_json::to_value(ToolOptions { zoom_in: false, ..ToolOptions::default() }).unwrap(); + assert!(!serde_json::from_value::(saved.clone()).unwrap().zoom_in, "the mode is saved"); + // Options saved before the mode existed load as Zoom In; a bad value is an error, not a panic. + saved.as_object_mut().unwrap().remove("zoom_in"); + assert!(serde_json::from_value::(saved.clone()).unwrap().zoom_in); + saved["zoom_in"] = json!("out"); + assert!(serde_json::from_value::(saved).is_err()); +} diff --git a/crates/ui-egui/src/widgets.rs b/crates/ui-egui/src/widgets.rs index 9e8d890259..c4e69aa2b1 100644 --- a/crates/ui-egui/src/widgets.rs +++ b/crates/ui-egui/src/widgets.rs @@ -54,7 +54,7 @@ pub(crate) use fields::compact_wrapping_value_field; use fields::{FieldOpts, NUMERIC_INPUT_LIMIT, value_field_in}; pub use fields::{ POPUP_ARROW_W, PopupFieldResponse, VALUE_FIELD_H, compact_value_field, elided_label, elided_label_sensed, popup_value_field, typed_text_parses, - value_field, value_field_named, value_field_whole_alerting, value_field_with_trailing, + value_field, value_field_named, value_field_whole, value_field_whole_alerting, value_field_with_trailing, }; pub use label_column::{LABEL_COLUMN_GAP, column_label, column_label_padded, label_column_width}; pub(crate) use panel::body_margin; diff --git a/crates/ui-egui/src/widgets/fields.rs b/crates/ui-egui/src/widgets/fields.rs index 078d4ef003..433d552eac 100644 --- a/crates/ui-egui/src/widgets/fields.rs +++ b/crates/ui-egui/src/widgets/fields.rs @@ -12,6 +12,13 @@ pub fn value_field(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive value_field_in(ui, value, range, suffix, width, 0.0, FieldOpts::default(), None).0 } +/// A [`value_field`] for a whole number: no decimals, and the arrow keys and a scrub (of the field +/// or of its caption) move it a whole step at a time, whatever its range. A small range such as +/// 1–10 would otherwise scrub in hundredths, which a whole-number setting rounds away (#11765). +pub fn value_field_whole(ui: &mut Ui, value: &mut f32, range: std::ops::RangeInclusive, suffix: &str, width: f32) -> Response { + value_field_in(ui, value, range, suffix, width, 0.0, FieldOpts { decimals: Some(0), step_from_decimals: true, ..Default::default() }, None).0 +} + /// A [`value_field_named`] for whole numbers that says when a typed value was past `range` /// (Photoshop's "Closest value inserted" alerts, #11938): it stores the closest whole number in /// range, and returns true once the field is left after such a value was typed, so the caller diff --git a/crates/vector/src/edit.rs b/crates/vector/src/edit.rs index 30b200216b..83e7acbcc4 100644 --- a/crates/vector/src/edit.rs +++ b/crates/vector/src/edit.rs @@ -211,8 +211,9 @@ fn lerp(a: Point, b: Point, t: f64) -> Point { /// Add Anchor Point: inserts an anchor into the segment leaving `knot` at curve parameter `t` /// (strictly between 0 and 1) and returns the new knot's `[subpath, knot]`. A curve is split at -/// `t` (de Casteljau), so its shape does not change and the new anchor is smooth; on a straight -/// segment (both handles retracted) the new anchor is a corner on the line. +/// `t` (de Casteljau), so its shape does not change and the new anchor is smooth. A straight +/// segment (both handles retracted) is split the same way, with controls (start, start, end, end): +/// the new anchor is smooth with handles, and the neighbours keep their retracted handles. pub fn add_anchor(path: &mut Path, knot: [usize; 2], t: f64) -> Result<[usize; 2], String> { if !(t.is_finite() && t > 0.0 && t < 1.0) { return Err("`t` must be strictly between 0 and 1".into()); @@ -220,18 +221,15 @@ pub fn add_anchor(path: &mut Path, knot: [usize; 2], t: f64) -> Result<[usize; 2 let end = segment_end(path, knot)?; let a = *knot_mut(path, knot)?; let b = *knot_mut(path, end)?; - let new = if straight(&a, &b) { - // Hit testing and hover feedback use the cubic parameter, which is not linear even - // when both handles are retracted. Keep the inserted corner at that same point. - let p = eval(&[a.anchor, a.out_ctrl, b.in_ctrl, b.anchor], t); - Knot::corner(p.x, p.y) - } else { - let (p01, p12, p23) = (lerp(a.anchor, a.out_ctrl, t), lerp(a.out_ctrl, b.in_ctrl, t), lerp(b.in_ctrl, b.anchor, t)); - let (p012, p123) = (lerp(p01, p12, t), lerp(p12, p23, t)); - knot_mut(path, knot)?.out_ctrl = p01; - knot_mut(path, end)?.in_ctrl = p23; - Knot::smooth(lerp(p012, p123, t), p012, p123) - }; + // Straight or not, the segment is split by de Casteljau at `t`. A straight one has controls + // (start, start, end, end), so the neighbours' handles stay retracted and the new anchor is + // smooth with handles a quarter of the segment either side at the middle. The hit position + // stays the cubic point at `t`, which hit testing and hover feedback use. + let (p01, p12, p23) = (lerp(a.anchor, a.out_ctrl, t), lerp(a.out_ctrl, b.in_ctrl, t), lerp(b.in_ctrl, b.anchor, t)); + let (p012, p123) = (lerp(p01, p12, t), lerp(p12, p23, t)); + knot_mut(path, knot)?.out_ctrl = p01; + knot_mut(path, end)?.in_ctrl = p23; + let new = Knot::smooth(lerp(p012, p123, t), p012, p123); let [s, k] = knot; let at = k.checked_add(1).ok_or_else(|| format!("no segment leaves knot {k} of subpath {s}"))?; let sp = path.subpaths.get_mut(s).ok_or_else(|| format!("no subpath {s}"))?; @@ -648,19 +646,23 @@ mod tests { let added = add_anchor(&mut p, knot, hit_t).unwrap(); let inserted = at(&p, added[0], added[1]); assert!(dist(inserted.anchor, clicked) < 1e-9, "t={t}: inserted {:?}, clicked {clicked:?}", inserted.anchor); - assert_eq!(inserted, Knot::corner(clicked.x, clicked.y), "straight segments retain retracted handles"); + assert!(inserted.smooth, "a straight segment is split like any cubic"); + let handles = [inserted.in_ctrl, inserted.out_ctrl]; + assert!(handles.iter().all(|h| dist(*h, inserted.anchor) > 1e-6), "the new anchor has handles"); } } } #[test] - fn adding_to_a_straight_segment_makes_a_corner_on_the_line() { + fn adding_to_a_straight_segment_makes_a_smooth_anchor_on_the_line() { let mut p = tri(); // The closing segment (2 → 0) wraps: the new anchor goes last. assert_eq!(add_anchor(&mut p, [0, 2], 0.5).unwrap(), [0, 3]); - assert_eq!(at(&p, 0, 3), Knot::corner(25.0, 40.0)); + let k = at(&p, 0, 3); + assert!(k.smooth && dist(k.anchor, Point::new(25.0, 40.0)) < 1e-9, "{k:?}"); assert_eq!(add_anchor(&mut p, [0, 0], 0.25).unwrap(), [0, 1]); - assert_eq!(at(&p, 0, 1), Knot::corner(15.625, 0.0)); + let k = at(&p, 0, 1); + assert!(k.smooth && dist(k.anchor, Point::new(15.625, 0.0)) < 1e-9, "{k:?}"); assert_eq!(p.subpaths[0].knots.len(), 5); assert!(p.subpaths[0].closed); } @@ -766,3 +768,7 @@ mod tests { #[cfg(test)] #[path = "edit_delete_last_anchor_tests.rs"] mod edit_delete_last_anchor_tests; + +#[cfg(test)] +#[path = "edit_add_anchor_straight_tests.rs"] +mod edit_add_anchor_straight_tests; diff --git a/crates/vector/src/edit_add_anchor_straight_tests.rs b/crates/vector/src/edit_add_anchor_straight_tests.rs new file mode 100644 index 0000000000..05f1c3d8ec --- /dev/null +++ b/crates/vector/src/edit_add_anchor_straight_tests.rs @@ -0,0 +1,60 @@ +//! Add Anchor Point on a straight segment (#12706): the segment is split like any cubic (controls +//! start, start, end, end), so the new anchor is smooth with handles and the neighbours keep +//! their retracted handles. + +use photocraft_doc::{Path, Subpath}; + +use super::*; + +fn square() -> Path { + Path::new(vec![Subpath::polygon(&[(100.0, 300.0), (300.0, 300.0), (300.0, 500.0), (100.0, 500.0)])]) +} + +fn knot(p: &Path, k: usize) -> Knot { + p.subpaths[0].knots[k] +} + +fn near(a: Point, x: f64, y: f64, tol: f64) -> bool { + (a.x - x).abs() <= tol && (a.y - y).abs() <= tol +} + +#[test] +fn a_closed_square_edge_gets_a_smooth_anchor_with_quarter_length_handles() { + let mut p = square(); + let before = p.subpaths[0].segments()[0]; + let added = add_anchor(&mut p, [0, 0], 0.5).unwrap(); + assert_eq!(added, [0, 1]); + let k = knot(&p, 1); + assert!(near(k.anchor, 200.0, 300.0, 0.5), "anchor {:?}", k.anchor); + assert!(near(k.in_ctrl, 150.0, 300.0, 0.5), "in handle {:?}", k.in_ctrl); + assert!(near(k.out_ctrl, 250.0, 300.0, 0.5), "out handle {:?}", k.out_ctrl); + assert!(k.smooth, "the new anchor is smooth"); + let (first, last) = (knot(&p, 0), knot(&p, 2)); + assert_eq!(first.out_ctrl, first.anchor, "(100,300) keeps its handle retracted"); + assert_eq!(last.in_ctrl, last.anchor, "(300,300) keeps its handle retracted"); + assert_eq!(p.subpaths[0].knots.len(), 5); + // The outline is unchanged: both new cubics lie on the old line, and together cover it. + let segs = p.subpaths[0].segments(); + for i in 0..=100 { + let u = f64::from(i) / 100.0; + for q in [eval(&segs[0], u), eval(&segs[1], u)] { + assert!((q.y - 300.0).abs() < 1e-9 && (100.0..=300.0).contains(&q.x), "off the old line: {q:?}"); + } + } + let (a, b) = (eval(&segs[0], 1.0), eval(&segs[1], 0.0)); + assert!(dist(a, b) < 1e-9 && dist(eval(&segs[0], 0.0), eval(&before, 0.0)) < 1e-9 && dist(eval(&segs[1], 1.0), eval(&before, 1.0)) < 1e-9); +} + +#[test] +fn an_open_line_hit_at_650_gets_the_measured_handles() { + let mut p = Path::new(vec![Subpath::polyline(&[(400.0, 300.0), (700.0, 300.0)])]); + // `t` the way the Add tool finds it: `hit` on the clicked point, which returns the cubic + // parameter (not linear along a retracted segment), then `add_anchor` at that `t`. + let Some(Hit::Segment(seg, t)) = hit(&p, Point::new(650.0, 300.0), 1.0, &[]) else { panic!("no segment hit") }; + let added = add_anchor(&mut p, seg, t).unwrap(); + let k = knot(&p, added[1]); + assert!(near(k.anchor, 650.0, 300.0, 1.0), "anchor {:?}", k.anchor); + assert!(near(k.in_ctrl, 564.0, 300.0, 1.0), "in handle {:?}", k.in_ctrl); + assert!(near(k.out_ctrl, 679.6, 300.0, 1.0), "out handle {:?}", k.out_ctrl); + assert!(k.smooth); +} diff --git a/crates/vector/src/shapes.rs b/crates/vector/src/shapes.rs index 0b7e65a48d..607531d5b3 100644 --- a/crates/vector/src/shapes.rs +++ b/crates/vector/src/shapes.rs @@ -99,7 +99,7 @@ pub fn polygon(x: f64, y: f64, w: f64, h: f64, sides: u32, star_ratio: f64) -> P let sides = sides.clamp(3, 100) as usize; let (rx, ry) = (w / 2.0, h / 2.0); let (cx, cy) = (x + rx, y + ry); - let star = star_ratio > 0.0 && star_ratio < 1.0; + let star = is_star(star_ratio); let count = if star { sides * 2 } else { sides }; let pts: Vec<(f64, f64)> = (0..count) .map(|i| { @@ -111,6 +111,18 @@ pub fn polygon(x: f64, y: f64, w: f64, h: f64, sides: u32, star_ratio: f64) -> P Path::new(vec![Subpath::polygon(&pts)]) } +/// Does `star_ratio` make [`polygon`] a star (inner points between its outer ones)? +fn is_star(star_ratio: f64) -> bool { + star_ratio > 0.0 && star_ratio < 1.0 +} + +/// Does vertex `i` of [`polygon`] with `star_ratio` take the corner radius? Every vertex of a +/// plain polygon; only a star's outer points (even `i`), its inner points stay sharp, as in +/// Photoshop. +pub fn polygon_rounds_vertex(star_ratio: f64, i: usize) -> bool { + !is_star(star_ratio) || i.is_multiple_of(2) +} + /// A rounded vertex: see [`fillet`]. #[derive(Clone, Copy, Debug, PartialEq)] pub struct Fillet { @@ -168,6 +180,12 @@ pub fn fillet(prev: [f64; 2], v: [f64; 2], next: [f64; 2], r: f64) -> Option Path { + round_corners_where(path, r, |_| true) +} + +/// [`round_corners`] for the vertices `rounds` picks by their index in the subpath; the others +/// stay sharp corners. +pub fn round_corners_where(path: Path, r: f64, rounds: impl Fn(usize) -> bool) -> Path { if r.is_nan() || r <= 0.0 { return path; } @@ -183,7 +201,7 @@ pub fn round_corners(path: Path, r: f64) -> Path { let mut knots = Vec::with_capacity(n * 2); for i in 0..n { let (prev, v, next) = (pt(i + n - 1), pt(i), pt(i + 1)); - let Some(f) = fillet(prev, v, next, r) else { + let Some(f) = rounds(i).then(|| fillet(prev, v, next, r)).flatten() else { knots.push(Knot::corner(v[0], v[1])); continue; }; @@ -280,7 +298,7 @@ pub fn live_path(s: &LiveShape) -> Path { LiveShape::Rect { rect: [x, y, w, h], radii } => rounded_rect(*x, *y, *w, *h, *radii), LiveShape::Ellipse { rect: [x, y, w, h] } => ellipse(*x, *y, *w, *h), LiveShape::Polygon { rect: [x, y, w, h], sides, star_ratio, corner_radius } => { - round_corners(polygon(*x, *y, *w, *h, *sides, *star_ratio), *corner_radius) + round_corners_where(polygon(*x, *y, *w, *h, *sides, *star_ratio), *corner_radius, |i| polygon_rounds_vertex(*star_ratio, i)) } LiveShape::Line { from, to, weight } => line((from[0], from[1]), (to[0], to[1]), *weight), LiveShape::ArrowLine { from, to, weight, start, end, width, length, concavity } => { @@ -368,9 +386,9 @@ mod tests { } #[test] - fn a_star_rounds_its_inner_vertices_too() { + fn a_star_rounds_its_outer_vertices_only() { let p = live_path(&LiveShape::Polygon { rect: [0.0, 0.0, 200.0, 200.0], sides: 5, star_ratio: 0.5, corner_radius: 6.0 }); - assert_eq!(p.subpaths[0].knots.len(), 20); + assert_eq!(p.subpaths[0].knots.len(), 15); } #[test] @@ -407,6 +425,10 @@ mod tests { } } +#[cfg(test)] +#[path = "star_outer_corner_radius_tests.rs"] +mod star_outer_corner_radius_tests; + #[cfg(test)] mod line_arrow_6408_tests { use super::*; diff --git a/crates/vector/src/star_outer_corner_radius_tests.rs b/crates/vector/src/star_outer_corner_radius_tests.rs new file mode 100644 index 0000000000..6718498c1a --- /dev/null +++ b/crates/vector/src/star_outer_corner_radius_tests.rs @@ -0,0 +1,61 @@ +//! A rounded star rounds only its outer points; its inner points stay sharp corners, as in +//! Photoshop (#13308). Plain polygons keep rounding every vertex. + +use super::*; + +fn star(corner_radius: f64) -> Path { + live_path(&LiveShape::Polygon { rect: [400.0, 300.0, 200.0, 100.0], sides: 5, star_ratio: 0.5, corner_radius }) +} + +fn has_handles(k: &Knot) -> bool { + k.in_ctrl != k.anchor || k.out_ctrl != k.anchor +} + +#[test] +fn a_rounded_five_point_star_has_two_anchors_per_outer_point_and_sharp_inner_points() { + let knots = &star(10.0).subpaths[0].knots; + assert_eq!(knots.len(), 15); + let sharp = &polygon(400.0, 300.0, 200.0, 100.0, 5, 0.5).subpaths[0].knots; + // Each outer point becomes an arc (two anchors with a handle each), then the inner point + // follows as a corner anchor exactly where the sharp star has it. + for (n, chunk) in knots.chunks(3).enumerate() { + let [from, to, inner] = chunk else { panic!("15 knots in threes") }; + assert!(has_handles(from) && has_handles(to), "outer point {n} is rounded"); + assert!(!has_handles(inner), "inner point {n} is a corner"); + assert_eq!(inner.anchor, sharp[2 * n + 1].anchor, "inner point {n} stays put"); + } + assert_eq!(knots.iter().filter(|k| has_handles(k)).count(), 10); +} + +#[test] +fn an_outer_point_is_rounded_by_the_arc_the_radius_asks_for() { + let knots = &star(10.0).subpaths[0].knots; + let sharp: Vec<[f64; 2]> = polygon(400.0, 300.0, 200.0, 100.0, 5, 0.5).subpaths[0].knots.iter().map(|k| [k.anchor.x, k.anchor.y]).collect(); + for n in 0..5 { + let v = 2 * n; + let f = fillet(sharp[(v + 9) % 10], sharp[v], sharp[v + 1], 10.0).unwrap(); + assert_eq!([knots[3 * n].anchor.x, knots[3 * n].anchor.y], f.from, "outer point {n}"); + assert_eq!([knots[3 * n + 1].anchor.x, knots[3 * n + 1].anchor.y], f.to, "outer point {n}"); + } +} + +#[test] +fn a_plain_polygon_still_rounds_every_vertex() { + for star_ratio in [1.0, 0.0, 1.5] { + let p = live_path(&LiveShape::Polygon { rect: [400.0, 300.0, 200.0, 100.0], sides: 5, star_ratio, corner_radius: 10.0 }); + assert_eq!(p, round_corners(polygon(400.0, 300.0, 200.0, 100.0, 5, star_ratio), 10.0), "star ratio {star_ratio}"); + assert_eq!(p.subpaths[0].knots.len(), 10); + assert!(p.subpaths[0].knots.iter().all(has_handles)); + } +} + +#[test] +fn a_star_without_a_radius_stays_sharp() { + assert_eq!(star(0.0), polygon(400.0, 300.0, 200.0, 100.0, 5, 0.5)); +} + +#[test] +fn only_a_stars_outer_vertices_take_the_radius() { + assert!((0..10).all(|i| polygon_rounds_vertex(1.0, i))); + assert_eq!((0..6).map(|i| polygon_rounds_vertex(0.5, i)).collect::>(), [true, false, true, false, true, false]); +}