diff --git a/crates/engine/src/cmd/vector_cmds.rs b/crates/engine/src/cmd/vector_cmds.rs index 7d781257fa..ad6daa4f89 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: 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}"## + 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":-50..50=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 @@ -108,7 +108,7 @@ pub fn specs() -> Vec { "Edit Shape", [], leak(format!( - r##"{{"layer":id?,"path":{{…}}? (replaces; drops live shape),"kind":str?,"rect":[x,y,w,h]?,"radii":[tl,tr,br,bl]|r?,"sides":n?,"starRatio":r?,"cornerRadius":px?,"from":[x,y]?,"to":[x,y]?,"weight":px? (live-shape params regenerate the path),"arrowStart":bool?,"arrowEnd":bool?,"arrowWidth":px?,"arrowLength":px?,"arrowConcavity":0..100? (line arrows),"move":[dx,dy]?,"transform":[a,b,c,d,e,f]?,"op":"combine|…"? + "subpath":index? (default all but the first),"fillRule":"nonzero|evenodd"?,{fill}?,{stroke}? (merged into the current stroke),"name":str?}} → shape.info"## + r##"{{"layer":id?,"path":{{…}}? (replaces; drops live shape),"kind":str?,"rect":[x,y,w,h]?,"radii":[tl,tr,br,bl]|r?,"sides":n?,"starRatio":r?,"cornerRadius":px?,"from":[x,y]?,"to":[x,y]?,"weight":px? (live-shape params regenerate the path),"arrowStart":bool?,"arrowEnd":bool?,"arrowWidth":px?,"arrowLength":px?,"arrowConcavity":-50..50? (line arrows),"move":[dx,dy]?,"transform":[a,b,c,d,e,f]?,"op":"combine|…"? + "subpath":index? (default all but the first),"fillRule":"nonzero|evenodd"?,{fill}?,{stroke}? (merged into the current stroke),"name":str?}} → shape.info"## )), has_layer, shape_edit diff --git a/crates/engine/src/cmd/vector_cmds/params.rs b/crates/engine/src/cmd/vector_cmds/params.rs index bab083c162..bd13af9977 100644 --- a/crates/engine/src/cmd/vector_cmds/params.rs +++ b/crates/engine/src/cmd/vector_cmds/params.rs @@ -398,7 +398,9 @@ pub(super) fn live_from_params(cmd: &str, kind: &str, p: &Value, prev: Option<&L end: flag("arrowEnd", pe)?, width: dim("arrowWidth", pwidth, 1.0, 4096.0)?, length: dim("arrowLength", plen, 1.0, 4096.0)?, - concavity: dim("arrowConcavity", pc, 0.0, 100.0)?, + // -50..50 % as in Photoshop (#13258); a shape saved with the old 0..100 range + // keeps working when another property is edited. + concavity: dim("arrowConcavity", if pc.is_finite() { pc.clamp(-50.0, 50.0) } else { 0.0 }, -50.0, 50.0)?, } } else { LiveShape::Line { from, to, weight } diff --git a/crates/engine/src/cmd/vector_cmds/tests.rs b/crates/engine/src/cmd/vector_cmds/tests.rs index 3cd399d096..9ba81ece10 100644 --- a/crates/engine/src/cmd/vector_cmds/tests.rs +++ b/crates/engine/src/cmd/vector_cmds/tests.rs @@ -1464,7 +1464,7 @@ fn arrowhead_dimensions_reject_invalid_values_without_mutation() { for (key, invalids) in [ ("arrowWidth", [json!("52"), json!(null), json!([]), json!(0), json!(4097)]), ("arrowLength", [json!("50"), json!(null), json!([]), json!(0), json!(4097)]), - ("arrowConcavity", [json!("0"), json!(null), json!([]), json!(-1), json!(101)]), + ("arrowConcavity", [json!("0"), json!(null), json!([]), json!(-51), json!(51)]), ] { for invalid in invalids { let mut create = json!({ @@ -1486,6 +1486,32 @@ fn arrowhead_dimensions_reject_invalid_values_without_mutation() { } } +/// Concavity takes -50..50 % (#13258); a shape saved with the old 0..100 range still edits. +#[test] +fn arrow_concavity_takes_minus_fifty_to_fifty() { + let mut s = session(160, 120, 8); + let concavity = |s: &Session, id: u64| match s.active().unwrap().doc.layer(LayerId(id)).map(|l| &l.content) { + Some(LayerContent::Shape(sh)) => match sh.live { + Some(LiveShape::ArrowLine { concavity, .. }) => concavity, + _ => panic!("expected a live arrow"), + }, + _ => panic!("expected a shape layer"), + }; + let created = s.execute("shape.create", json!({"kind": "line", "from": [10, 20], "to": [120, 20], "arrowEnd": true, "arrowConcavity": -50})).unwrap(); + let id = created["layer"].as_u64().unwrap(); + assert_eq!(concavity(&s, id), -50.0); + s.execute("shape.edit", json!({"layer": id, "arrowConcavity": 50})).unwrap(); + assert_eq!(concavity(&s, id), 50.0); + + if let Some(LayerContent::Shape(sh)) = std::sync::Arc::make_mut(&mut s.active_mut().unwrap().doc).layer_mut(LayerId(id)).map(|l| &mut l.content) + && let Some(LiveShape::ArrowLine { concavity, .. }) = &mut sh.live + { + *concavity = 80.0; + } + s.execute("shape.edit", json!({"layer": id, "arrowWidth": 12})).unwrap(); + assert_eq!(concavity(&s, id), 50.0, "an old 0..100 value is clamped, not refused"); +} + #[test] fn headless_diagonal_arrow_preserves_geometry_after_nonuniform_scale() { let mut s = session(400, 400, 8); diff --git a/crates/io/src/vector_map.rs b/crates/io/src/vector_map.rs index 331d3edda7..006f892625 100644 --- a/crates/io/src/vector_map.rs +++ b/crates/io/src/vector_map.rs @@ -420,7 +420,8 @@ pub fn live_from_vogk(data: &[u8]) -> Option { // Missing or invalid PSD arrow sizes must not prevent later edits. let width = if width.is_finite() && width >= 1.0 { width } else { 52.0 }; let length = if length.is_finite() && length >= 1.0 { length } else { 50.0 }; - let concavity = if concavity.is_finite() { concavity.clamp(0.0, 100.0) } else { 0.0 }; + // Photoshop's range is -50..50 % (#13258): keep a negative value. + let concavity = if concavity.is_finite() { concavity.clamp(-50.0, 50.0) } else { 0.0 }; Some(LiveShape::ArrowLine { from, to, weight, start, end, width, length, concavity }) } else { Some(LiveShape::Line { from, to, weight }) @@ -747,6 +748,21 @@ mod tests { assert!(vogk_bytes(&LiveShape::Polygon { rect: [0.0; 4], sides: 5, star_ratio: 1.0, corner_radius: 0.0 }, 72.0).is_none()); } + /// A PSD arrow keeps a negative concavity, and one past 50 % opens clamped to 50 (#13258). + #[test] + fn vogk_arrow_concavity_keeps_negatives_and_clamps_to_fifty() { + let arrow = + |concavity| LiveShape::ArrowLine { from: [0.0, 10.0], to: [20.0, 0.0], weight: 3.0, start: false, end: true, width: 5.0, length: 10.0, concavity }; + let read = |c| match live_from_vogk(&vogk_bytes(&arrow(c), 72.0).unwrap()) { + Some(LiveShape::ArrowLine { concavity, .. }) => concavity, + other => panic!("{other:?}"), + }; + assert_eq!(read(-50.0), -50.0); + assert_eq!(read(-20.0), -20.0); + assert_eq!(read(80.0), 50.0); + assert_eq!(read(-90.0), -50.0); + } + #[test] fn shape_blocks_keep_unchanged_and_regenerate_changed() { let sh = ShapeLayer { diff --git a/crates/ui-egui/src/panels/layer_props_ui.rs b/crates/ui-egui/src/panels/layer_props_ui.rs index 9bba0ebf7e..677b332503 100644 --- a/crates/ui-egui/src/panels/layer_props_ui.rs +++ b/crates/ui-egui/src/panels/layer_props_ui.rs @@ -933,10 +933,10 @@ mod tests { ); // The next live-property edit must still be accepted after resizing. - s.execute("shape.edit", json!({"layer": id.0, "arrowConcavity": 60.0})).unwrap(); + s.execute("shape.edit", json!({"layer": id.0, "arrowConcavity": 40.0})).unwrap(); let layer = s.active().unwrap().doc.layer(id).unwrap(); let LayerContent::Shape(shape) = &layer.content else { panic!("expected shape layer") }; - assert!(matches!(shape.live.as_ref(), Some(photocraft_doc::vector::LiveShape::ArrowLine { concavity, .. }) if (*concavity - 60.0).abs() < 1e-9)); + assert!(matches!(shape.live.as_ref(), Some(photocraft_doc::vector::LiveShape::ArrowLine { concavity, .. }) if (*concavity - 40.0).abs() < 1e-9)); } /// A stroked shape's Transform fields show its path, not the stroke's pixels, and a W edit diff --git a/crates/ui-egui/src/panels/options_bar.rs b/crates/ui-egui/src/panels/options_bar.rs index 3e9034715e..111816d297 100644 --- a/crates/ui-egui/src/panels/options_bar.rs +++ b/crates/ui-egui/src/panels/options_bar.rs @@ -1014,7 +1014,7 @@ fn eraser_percent(ui: &mut egui::Ui, label: &str, value: &mut f32) -> bool { } /// Shows one of the range alerts as a modal with OK, once even if more than one pass asks. -fn range_alert(ui_state: &mut crate::state::UiState, text: &str) { +pub(crate) fn range_alert(ui_state: &mut crate::state::UiState, text: &str) { let message = tl!(text).to_owned(); let shown = ui_state.dialogs.iter().any(|d| d.kind == crate::state::DialogKind::Error && d.fields.get("message").and_then(|m| m.as_str()) == Some(&message)); diff --git a/crates/ui-egui/src/tools/vector_ui.rs b/crates/ui-egui/src/tools/vector_ui.rs index 01ff55fce0..4d6053fecf 100644 --- a/crates/ui-egui/src/tools/vector_ui.rs +++ b/crates/ui-egui/src/tools/vector_ui.rs @@ -114,7 +114,7 @@ fn copy_arrow_to_tool_defaults(app: &mut PhotocraftApp, id: photocraft_doc::Laye *end, bounded(*width, 1.0, 4096.0), bounded(*length, 1.0, 4096.0), - bounded(*concavity, 0.0, 100.0), + bounded(*concavity, -50.0, 50.0), bounded(*weight, 1.0, 10000.0), )) } diff --git a/crates/ui-egui/src/tools/vector_ui/line_arrow_concavity_field_tests.rs b/crates/ui-egui/src/tools/vector_ui/line_arrow_concavity_field_tests.rs new file mode 100644 index 0000000000..716ec56173 --- /dev/null +++ b/crates/ui-egui/src/tools/vector_ui/line_arrow_concavity_field_tests.rs @@ -0,0 +1,121 @@ +//! #13258: arrowhead Concavity takes whole numbers from -50 % to 50 % in the Properties panel and +//! the Line tool's gear menu; a value typed past the range becomes the closest end and, once the +//! field is left, the reference's "Closest value inserted" alert with OK says so. + +use egui::accesskit::Role; +use egui::vec2; +use egui_kittest::Harness; +use egui_kittest::kittest::{NodeT, Queryable}; +use photocraft_doc::{LayerContent, LayerId, LiveShape}; +use serde_json::json; + +use super::{CONCAVITY_RANGE_ALERT, shape_properties}; +use crate::PhotocraftApp; +use crate::state::{DialogKind, Tool}; + +/// An 800 x 600 document with a weight 4 End arrow (5 x 10 px head) from 400,300 to 600,300. +fn app_with_arrow() -> (PhotocraftApp, LayerId) { + let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default()); + app.run("file.new", json!({"width": 800, "height": 600})).unwrap(); + let made = app + .run("shape.create", json!({"kind": "line", "from": [400, 300], "to": [600, 300], "weight": 4, "arrowEnd": true, "arrowWidth": 5, "arrowLength": 10})) + .unwrap(); + let id = LayerId(made["layer"].as_u64().unwrap()); + (app, id) +} + +/// True once `setup_context` installed the app's fonts (the first frame runs before it). +fn fonts_ready(ui: &egui::Ui) -> bool { + ui.ctx().fonts(|f| f.families().contains(&egui::FontFamily::Name("medium".into()))) +} + +fn properties() -> (Harness<'static, PhotocraftApp>, LayerId) { + let (app, id) = app_with_arrow(); + let mut h = Harness::builder().with_size(vec2(400.0, 900.0)).build_ui_state( + move |ui, app| { + if fonts_ready(ui) { + shape_properties(app, ui, id); + } + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + h.run_steps(4); + (h, id) +} + +/// The options bar with the Line tool active, its arrowhead gear menu open. +fn gear() -> Harness<'static, PhotocraftApp> { + let (mut app, _) = app_with_arrow(); + app.ui.tool = Tool::Line; + let mut h = Harness::builder().with_size(vec2(1800.0, 400.0)).build_ui_state( + |ui, app| { + if fonts_ready(ui) { + crate::panels::options_bar(app, ui); + } + }, + app, + ); + PhotocraftApp::setup_context(&h.ctx, Default::default()); + h.run_steps(4); + h.query_by_label("Arrowhead options").expect("the arrowhead gear").click(); + h.run_steps(3); + h +} + +/// Types `text` into the Concavity field, then Tabs out of it. +fn type_concavity(h: &mut Harness<'static, PhotocraftApp>, text: &str) { + h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().label().as_deref() == Some("Concavity")).expect("the Concavity field").click(); + h.run_steps(1); + h.key_press_modifiers(egui::Modifiers::COMMAND, egui::Key::A); + h.event(egui::Event::Text(text.into())); + h.run_steps(1); + h.key_press(egui::Key::Tab); + h.run_steps(3); +} + +fn alerts(h: &Harness<'static, PhotocraftApp>) -> Vec { + h.state().ui.dialogs.iter().filter(|d| d.kind == DialogKind::Error).filter_map(|d| d.fields.get("message")?.as_str().map(str::to_owned)).collect() +} + +fn concavity(h: &Harness<'static, PhotocraftApp>, id: LayerId) -> f64 { + match h.state().session.active().and_then(|st| st.doc.layer(id)).map(|l| &l.content) { + Some(LayerContent::Shape(sh)) => match sh.live { + Some(LiveShape::ArrowLine { concavity, .. }) => concavity, + _ => panic!("expected a live arrow"), + }, + _ => panic!("expected a shape layer"), + } +} + +#[test] +fn properties_concavity_in_range_is_applied_without_an_alert() { + for (typed, want) in [("-50", -50.0), ("-12", -12.0), ("25", 25.0), ("50", 50.0)] { + let (mut h, id) = properties(); + type_concavity(&mut h, typed); + assert_eq!(concavity(&h, id), want, "{typed}"); + assert!(alerts(&h).is_empty(), "{typed} is in range"); + } +} + +#[test] +fn properties_concavity_past_the_range_takes_the_closest_value_and_alerts() { + for (typed, want) in [("-60", -50.0), ("60", 50.0)] { + let (mut h, id) = properties(); + type_concavity(&mut h, typed); + assert_eq!(concavity(&h, id), want, "{typed}"); + assert_eq!(alerts(&h), vec![CONCAVITY_RANGE_ALERT.to_string()], "{typed}: one alert"); + } +} + +#[test] +fn gear_concavity_past_the_range_takes_the_closest_value_and_alerts() { + for (typed, want) in [("-60", -50.0), ("60", 50.0), ("-20", -20.0)] { + let mut h = gear(); + assert!(h.query_all_by_role(Role::SpinButton).any(|n| n.accesskit_node().label().as_deref() == Some("Concavity")), "the gear menu is open"); + type_concavity(&mut h, typed); + assert_eq!(h.state().ui.tool_options.arrow_concavity, want, "{typed}"); + let expected: Vec = if typed == "-20" { vec![] } else { vec![CONCAVITY_RANGE_ALERT.to_string()] }; + assert_eq!(alerts(&h), expected, "{typed}"); + } +} diff --git a/crates/ui-egui/src/tools/vector_ui/options.rs b/crates/ui-egui/src/tools/vector_ui/options.rs index 28772ea0f9..b9fa61248b 100644 --- a/crates/ui-egui/src/tools/vector_ui/options.rs +++ b/crates/ui-egui/src/tools/vector_ui/options.rs @@ -147,7 +147,13 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo // Photoshop-style arrowhead settings at the right of Line options. if tool == Tool::Line { crate::widgets::vline(ui, 22.0); - ui.menu_image_button(crate::icons::image("settings", 18.0, t.icon), |ui| { + let mut concavity_alert = false; + // Stays open on clicks inside, like the Pen's gear: a click into a field to type a value + // would otherwise close the menu before the value was entered (#13258). + let config = egui::containers::menu::MenuConfig::new().close_behavior(egui::PopupCloseBehavior::CloseOnClickOutside); + let gear = egui::Button::image(crate::icons::image("settings", 18.0, t.icon)); + let menu = egui::containers::menu::MenuButton::from_button(gear).config(config); + let (gear, _) = menu.ui(ui, |ui| { let o = &mut app.ui.tool_options; ui.set_min_width(170.0); ui.label(tl!("Arrowheads")); @@ -165,16 +171,25 @@ pub fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool) -> bo ui.add(egui::DragValue::new(&mut o.arrow_length).range(1.0..=4096.0).suffix(" px")); }); ui.horizontal(|ui| { - ui.label(tl!("Concavity")); - ui.add(egui::DragValue::new(&mut o.arrow_concavity).range(0.0..=100.0).suffix(" %")); + let label = tl!("Concavity"); + ui.label(label); + concavity_alert = crate::widgets::value_field_whole_alerting(ui, label, &mut o.arrow_concavity, CONCAVITY_RANGE, "%", 52.0).1; }); - }) - .response - .on_hover_text(tl!("Arrowhead options")); + }); + gear.on_hover_text(tl!("Arrowhead options")); + if concavity_alert { + crate::panels::options_bar::range_alert(&mut app.ui, CONCAVITY_RANGE_ALERT); + } } true } +/// Arrowhead Concavity in percent of the head's length, as the reference takes it (#13258). +pub(crate) const CONCAVITY_RANGE: std::ops::RangeInclusive = -50.0..=50.0; + +/// The reference's alert for a Concavity typed past [`CONCAVITY_RANGE`] (#13258). +pub(crate) const CONCAVITY_RANGE_ALERT: &str = "An integer between -50% and 50% is required. Closest value inserted."; + /// Path mode's "Make:" row, as in Photoshop's options bar: Selection… (#5703), Mask (#12904) and /// Shape (#10934), from the path being drawn or the active path; all greyed without one. fn make_buttons(app: &mut PhotocraftApp, ui: &mut egui::Ui) { @@ -281,6 +296,7 @@ pub fn shape_properties(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: photocra }; let t = Tokens::get(ui.ctx()); let mut edit: Option = None; + let mut concavity_alert = false; // A swatch picked in a Fill/Stroke popover joins the Recently Used Colors once the edit took it. let mut recent: Option<[f32; 3]> = None; let doc_id = app.session.active().map(|st| st.doc.id); @@ -459,8 +475,12 @@ pub fn shape_properties(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: photocra } }); ui.horizontal(|ui| { + let label = tl!("Concavity"); + ui.label(egui::RichText::new(label).color(t.text_dim).size(12.0)); let mut v = *concavity as f32; - if num(ui, "Concavity", &mut v, 0.0..=100.0, "%") { + let (r, out_of_range) = crate::widgets::value_field_whole_alerting(ui, label, &mut v, CONCAVITY_RANGE, "%", 64.0); + concavity_alert |= out_of_range; + if r.changed() { edit = Some(json!({"arrowConcavity": v, "coalesce": key("arrow-concavity")})); } }); @@ -527,8 +547,15 @@ pub fn shape_properties(app: &mut PhotocraftApp, ui: &mut egui::Ui, id: photocra }); } } + if concavity_alert { + crate::panels::options_bar::range_alert(&mut app.ui, CONCAVITY_RANGE_ALERT); + } } +#[cfg(test)] +#[path = "line_arrow_concavity_field_tests.rs"] +mod line_arrow_concavity_field_tests; + #[cfg(test)] #[path = "pen_make_mask_tests.rs"] mod pen_make_mask_tests; diff --git a/crates/ui-egui/src/tools/vector_ui/shapes.rs b/crates/ui-egui/src/tools/vector_ui/shapes.rs index 958c35fe07..42ee105604 100644 --- a/crates/ui-egui/src/tools/vector_ui/shapes.rs +++ b/crates/ui-egui/src/tools/vector_ui/shapes.rs @@ -112,7 +112,8 @@ pub(super) fn shape_geometry(o: &ToolOptions, tool: Tool, start: [f64; 2], end: json!({"kind": "line", "from": from, "to": to, "weight": weight, "arrowStart": o.arrow_start, "arrowEnd": o.arrow_end, "arrowWidth": o.arrow_width, "arrowLength": o.arrow_length, - "arrowConcavity": o.arrow_concavity}) + // Settings saved with the old 0..100 range draw at the nearest value (#13258). + "arrowConcavity": if o.arrow_concavity.is_finite() { o.arrow_concavity.round().clamp(-50.0, 50.0) } else { 0.0 }}) } else { let (mut w, mut h) = (end[0] - start[0], end[1] - start[1]); if mods.shift { diff --git a/crates/vector/src/line_arrow_concavity_tests.rs b/crates/vector/src/line_arrow_concavity_tests.rs new file mode 100644 index 0000000000..9e35d5ff1c --- /dev/null +++ b/crates/vector/src/line_arrow_concavity_tests.rs @@ -0,0 +1,99 @@ +//! Arrowhead Concavity is -50..50 % of the head's length, as in Photoshop (#13258): the middle of +//! the head's rear edge bends toward the tip for a positive value and away from it for a negative +//! one, and the shaft ends where that bent edge crosses the shaft's edge. Joining the shaft and +//! the heads into one outline is #13260; these tests check the anchors the reference outline has. + +use super::*; + +/// The measured setup: weight 4, head width 5 and length 10, drag 400,300 to 600,300. +fn arrow(start: bool, end: bool, concavity: f64) -> Path { + arrow_line((400.0, 300.0), (600.0, 300.0), 4.0, start, end, 5.0, 10.0, concavity) +} + +fn anchors(sp: &Subpath) -> Vec<[f64; 2]> { + sp.knots.iter().map(|k| [k.anchor.x, k.anchor.y]).collect() +} + +fn close(a: [f64; 2], b: [f64; 2]) -> bool { + (a[0] - b[0]).abs() < 1e-9 && (a[1] - b[1]).abs() < 1e-9 +} + +fn same(sp: &Subpath, want: &[[f64; 2]], what: &str) { + let got = anchors(sp); + assert!(got.len() == want.len() && got.iter().zip(want).all(|(g, w)| close(*g, *w)), "{what}: {got:?} != {want:?}"); +} + +/// Every anchor of the reference's one-outline result is an anchor of `p`. +fn has_reference_anchors(p: &Path, reference: &[[f64; 2]]) { + let all: Vec<[f64; 2]> = p.subpaths.iter().flat_map(anchors).collect(); + for r in reference { + assert!(all.iter().any(|a| close(*a, *r)), "reference anchor {r:?} missing from {all:?}"); + } +} + +#[test] +fn minus_fifty_bends_the_base_away_from_the_tip_and_the_shaft_ends_where_it_crosses() { + let p = arrow(false, true, -50.0); + assert_eq!(p.subpaths.len(), 2); + same(&p.subpaths[0], &[[400.0, 302.0], [589.0, 302.0], [589.0, 298.0], [400.0, 298.0]], "shaft to 589"); + // Tip, outer corners, and the base's middle 5 px (50 % of 10) behind the base at 590. + same(&p.subpaths[1], &[[600.0, 300.0], [590.0, 302.5], [585.0, 300.0], [590.0, 297.5]], "end head"); + has_reference_anchors(&p, &[[400.0, 302.0], [400.0, 298.0], [589.0, 298.0], [590.0, 297.5], [600.0, 300.0], [590.0, 302.5], [589.0, 302.0]]); +} + +#[test] +fn fifty_bends_both_bases_toward_their_tips_by_five_px() { + let p = arrow(true, true, 50.0); + assert_eq!(p.subpaths.len(), 3); + same(&p.subpaths[0], &[[409.0, 302.0], [591.0, 302.0], [591.0, 298.0], [409.0, 298.0]], "shaft 409..591"); + same(&p.subpaths[1], &[[400.0, 300.0], [410.0, 302.5], [405.0, 300.0], [410.0, 297.5]], "start head"); + same(&p.subpaths[2], &[[600.0, 300.0], [590.0, 302.5], [595.0, 300.0], [590.0, 297.5]], "end head"); + has_reference_anchors( + &p, + &[ + [409.0, 302.0], + [410.0, 302.5], + [400.0, 300.0], + [410.0, 297.5], + [409.0, 298.0], + [591.0, 298.0], + [590.0, 297.5], + [600.0, 300.0], + [590.0, 302.5], + [591.0, 302.0], + ], + ); +} + +#[test] +fn zero_keeps_a_flat_base_and_the_shaft_ends_at_it() { + let p = arrow(false, true, 0.0); + assert!(close(anchors(&p.subpaths[0])[1], [590.0, 302.0])); + assert!(close(anchors(&p.subpaths[1])[2], [590.0, 300.0])); +} + +#[test] +fn values_past_fifty_draw_as_fifty_so_older_documents_still_open() { + assert_eq!(arrow(true, true, 80.0), arrow(true, true, 50.0)); + assert_eq!(arrow(true, true, 100.0), arrow(true, true, 50.0)); + assert_eq!(arrow(true, true, -90.0), arrow(true, true, -50.0)); + assert_eq!(arrow(true, true, f64::NAN), arrow(true, true, 0.0)); +} + +#[test] +fn a_head_no_wider_than_the_shaft_meets_it_at_the_base_whatever_the_concavity() { + for c in [-50.0, 0.0, 50.0] { + let p = arrow_line((400.0, 300.0), (600.0, 300.0), 6.0, false, true, 5.0, 10.0, c); + assert!(close(anchors(&p.subpaths[0])[1], [590.0, 303.0]), "concavity {c}"); + } +} + +#[test] +fn long_heads_bent_away_never_turn_the_shaft_inside_out() { + for (start, end) in [(true, true), (false, true), (true, false)] { + let p = arrow_line((0.0, 0.0), (20.0, 0.0), 4.0, start, end, 30.0, 50.0, -50.0); + let shaft = anchors(&p.subpaths[0]); + assert!(shaft[0][0] <= shaft[1][0], "{start} {end}: {shaft:?}"); + assert!(p.subpaths.iter().flat_map(anchors).all(|a| a[0].is_finite() && a[1].is_finite())); + } +} diff --git a/crates/vector/src/shapes.rs b/crates/vector/src/shapes.rs index 607531d5b3..0140f75e7d 100644 --- a/crates/vector/src/shapes.rs +++ b/crates/vector/src/shapes.rs @@ -235,8 +235,10 @@ pub fn line(a: (f64, f64), b: (f64, f64), weight: f64) -> Path { /// A filled vector line with optional arrowheads at its endpoints (#6408). /// `width` and `length` measure the head in document pixels, independently of the shaft weight. -/// `concavity` is 0..100 percent: 0 has a flat rear edge, 100 a deep V-shaped notch. -/// The shaft stops at the notch, so a concave head remains concave after filling. +/// `concavity` is -50..50 percent of `length`: the middle of the head's rear edge bends that far +/// toward the tip (positive) or away from it (negative); 0 is flat. Values outside are clamped, so +/// documents saved with the old 0..100 range still open (#13258). The shaft stops where the bent +/// rear edge crosses the shaft's edge, so a concave head stays open after filling. // The arguments correspond to the stored LiveShape::ArrowLine parameters. #[allow(clippy::too_many_arguments)] pub fn arrow_line(a: (f64, f64), b: (f64, f64), weight: f64, start: bool, end: bool, width: f64, length: f64, concavity: f64) -> Path { @@ -256,15 +258,16 @@ pub fn arrow_line(a: (f64, f64), b: (f64, f64), weight: f64, start: bool, end: b let (vx, vy) = (-uy, ux); let size = (if length.is_finite() { length.max(1.0) } else { 1.0 }).min(distance * if start && end { 0.49 } else { 0.9 }); let half = (if width.is_finite() { width.max(1.0) } else { 1.0 }) / 2.0; - let requested_notch = concavity.clamp(0.0, 100.0) / 100.0; - // Preserve 0..50%. Beyond that compress the usable range so the head never collapses. - let max_notch = 0.75; - let notch = if requested_notch <= 0.5 { requested_notch } else { 0.5 + (requested_notch - 0.5) * (max_notch - 0.5) / 0.5 }; - // Put the shaft up to the notch, leaving the head's concave edges visible. - let inner = size * (1.0 - notch); + // The rear edge's bend toward the tip as a fraction of `size` (negative: away from the tip). + let notch = if concavity.is_finite() { concavity.clamp(-50.0, 50.0) / 100.0 } else { 0.0 }; + let hw = weight.max(0.1) / 2.0; + // The rear edge runs straight from each outer corner to its bent middle, so where it crosses + // the shaft's edge it is bent by `notch` times how far that edge is from the corner; a head no + // wider than the shaft meets it at its base. A head bent away from its tip reaches past its + // base, so the shaft is capped to never turn inside out. + let inner = (size * (1.0 - notch * (1.0 - (hw / half).min(1.0)))).min(if start && end { distance / 2.0 } else { distance }); let shaft_a = if start { (a.0 + ux * inner, a.1 + uy * inner) } else { a }; let shaft_b = if end { (b.0 - ux * inner, b.1 - uy * inner) } else { b }; - let hw = weight.max(0.1) / 2.0; let mut pieces = vec![Subpath::polygon(&[ (shaft_a.0 + vx * hw, shaft_a.1 + vy * hw), (shaft_b.0 + vx * hw, shaft_b.1 + vy * hw), @@ -429,6 +432,10 @@ mod tests { #[path = "star_outer_corner_radius_tests.rs"] mod star_outer_corner_radius_tests; +#[cfg(test)] +#[path = "line_arrow_concavity_tests.rs"] +mod line_arrow_concavity_tests; + #[cfg(test)] mod line_arrow_6408_tests { use super::*;