Add W and H fields to the Line tool's options bar

The Line tool's options bar now shows W, a link button and H after the
stroke controls (#13250): the active line's length and thickness in its
own rotated frame, 0 px with no line. A typed W scales the line along
itself about its start, a typed H across itself about the edge of its
box on the start's side, through the new engine helper
`line_frame_scale`, as one "Scale Paths" History step that keeps the line
live. The link is shown off and does nothing (not measured).
This commit is contained in:
qvest-ssels committed 2026-11-22 15:24:52 +01:00
1 parent 911cbd3723
commit 39ffff7fd3
4 files changed
+392 -2

No files matched your search

+1 -1
View File
@@ -82,7 +82,7 @@ use shape::{
can_paste_shape_fill, can_paste_shape_stroke, combine_shapes, copy_shape_fill, copy_shape_stroke, has_shape_fill, has_shape_stroke, merge_components,
paste_shape_fill, paste_shape_stroke, path_to_shape, selection_to_shape, shape_create, shape_edit, shape_info, shape_rasterize,
};
pub use shape::{preview_shape_stroke, refresh_shape, shape_path, transform_shape, translate_vectors};
pub use shape::{line_frame_scale, line_frame_size, preview_shape_stroke, refresh_shape, shape_path, transform_shape, translate_vectors};
use vector_mask::{toggle_vector_mask, vector_mask_add, vector_mask_delete, vector_mask_edit, vector_mask_info, vector_mask_rasterize, with};
pub(crate) fn leak(s: String) -> &'static str {
+94 -1
View File
@@ -187,6 +187,95 @@ fn arrow_axis_scales(a: &Affine, from: [f64; 2], to: [f64; 2]) -> Option<(f64, f
(dot.abs() <= 1e-10 * axial * perpendicular).then_some((axial, perpendicular))
}
/// A live line's own frame.
struct LineFrame {
/// The start.
from: [f64; 2],
/// The unit direction from the start to the end.
u: [f64; 2],
/// The normal, `(-u.y, u.x)`.
n: [f64; 2],
length: f64,
/// The weight, or the arrowhead width when it is wider and an arrowhead is on.
thickness: f64,
}
/// A live line's own frame; `None` for another live shape or a degenerate or non-finite line.
fn line_frame(live: &LiveShape) -> Option<LineFrame> {
let (from, to, thickness) = match live {
LiveShape::Line { from, to, weight } => (*from, *to, *weight),
LiveShape::ArrowLine { from, to, weight, start, end, width, .. } => (*from, *to, if *start || *end { weight.max(*width) } else { *weight }),
_ => return None,
};
let (dx, dy) = (to[0] - from[0], to[1] - from[1]);
let length = dx.hypot(dy);
if !length.is_finite() || length <= 1e-12 || !thickness.is_finite() || !from.iter().all(|v| v.is_finite()) {
return None;
}
let u = [dx / length, dy / length];
Some(LineFrame { from, u, n: [-u[1], u[0]], length, thickness })
}
/// The size of a live line in its own rotated frame, as the Line tool's W and H fields show it
/// (#13250): `(length, thickness)`, the thickness being the weight, or the arrowhead width when an
/// arrowhead is on and wider. `None` for another live shape or a degenerate line.
pub fn line_frame_size(live: &LiveShape) -> Option<(f64, f64)> {
line_frame(live).map(|f| (f.length, f.thickness))
}
/// The transform that resizes a live line in its own rotated frame to `new_length` (W) by
/// `new_thickness` (H), for `shape.edit {"transform": m}` (#13250; the Properties Transform of a
/// line, #13265, builds on it). Along the line it scales about the start, so the start stays put
/// and the angle is kept; across it, it scales about the edge of the rotated box on the start's
/// side opposite the normal, `from - (thickness / 2) * n` with `n = (-u.y, u.x)`: the measured
/// reference moves the start of a 15 px thick line from 400,300 to 398.88,302.24 for H 20.
/// [`transform_shape`] keeps the line live under it and scales the weight and arrowhead width by
/// the thickness factor and the arrowhead length by the length factor.
///
/// `None` (no edit) for another live shape, a degenerate line, or a size that is not finite and
/// positive. Never panics.
pub fn line_frame_scale(live: &LiveShape, new_length: f64, new_thickness: f64) -> Option<Affine> {
if !new_length.is_finite() || !new_thickness.is_finite() || new_length <= 0.0 || new_thickness <= 0.0 {
return None;
}
let LineFrame { from, u, n, length, thickness } = line_frame(live)?;
if thickness <= 1e-12 {
return None;
}
let (sa, sp) = (new_length / length, new_thickness / thickness);
if !sa.is_finite() || !sp.is_finite() {
return None;
}
// M = I + (sa - 1) u u^T + (sp - 1) n n^T, about the pivot P: x' = M x + (P - M P).
let (ka, kp) = (sa - 1.0, sp - 1.0);
let a = 1.0 + ka * u[0] * u[0] + kp * n[0] * n[0];
let b = ka * u[0] * u[1] + kp * n[0] * n[1];
let d = 1.0 + ka * u[1] * u[1] + kp * n[1] * n[1];
let pivot = [from[0] - thickness / 2.0 * n[0], from[1] - thickness / 2.0 * n[1]];
let e = pivot[0] - (a * pivot[0] + b * pivot[1]);
let f = pivot[1] - (b * pivot[0] + d * pivot[1]);
let m = [a, b, b, d, e, f];
m.iter().all(|v| v.is_finite()).then_some(Affine { m })
}
/// Whether `m` scales a live line only along and across itself (a non-trivial [`line_frame_scale`]):
/// its direction and normal map onto themselves with positive factors, not both 1.
fn is_line_frame_scale(live: &LiveShape, m: &[f64; 6]) -> bool {
let Some(LineFrame { u, n, .. }) = line_frame(live) else { return false };
let [a, b, c, d, _, _] = *m;
let map = |v: [f64; 2]| [a * v[0] + c * v[1], b * v[0] + d * v[1]];
let factor = |v: [f64; 2]| {
let w = map(v);
let along = w[0] * v[0] + w[1] * v[1];
let across = w[0] * -v[1] + w[1] * v[0];
(along.is_finite() && along > 1e-12 && across.abs() <= 1e-9 * along.max(1.0)).then_some(along)
};
match (factor(u), factor(n)) {
(Some(sa), Some(sp)) => (sa - 1.0).abs() > 1e-12 || (sp - 1.0).abs() > 1e-12,
_ => false,
}
}
/// Applies an affine transform to a shape's path, keeping the live shape when the transform
/// is a translation plus axis-aligned scale (otherwise the shape stops being parametric).
pub fn transform_shape(sh: &mut ShapeLayer, a: &Affine) {
@@ -552,7 +641,9 @@ pub(super) fn path_to_shape(s: &mut Session, p: &Value) -> Result<Value> {
/// End and Width; Start, Length and Concavity follow the same pattern. Rounding a live triangle
/// alone is "Change Rounded Triangle" (#13354); a three-sided Polygon is not a Triangle and keeps
/// "Edit Shape" until the Polygon naming issue lands. Any other edit, several keys at once, or
/// these keys sent to another shape stay "Edit Shape".
/// these keys sent to another shape stay "Edit Shape". A lone `transform` of a line that only scales
/// it along and across itself (the options bar's W and H, [`line_frame_scale`]) is "Scale Paths"
/// (#13250).
fn edit_history_name(s: &Session, id: LayerId, p: &Value) -> &'static str {
const EDIT: &str = "Edit Shape";
let live = s.active().and_then(|st| st.doc.layer(id)).and_then(|l| match &l.content {
@@ -569,6 +660,8 @@ fn edit_history_name(s: &Session, id: LayerId, p: &Value) -> &'static str {
(Some("arrowLength"), None) if line => "Change Arrowhead Length",
(Some("arrowConcavity"), None) if line => "Change Arrowhead Concavity",
(Some("cornerRadius"), None) if matches!(live, Some(LiveShape::Triangle { .. })) => "Change Rounded Triangle",
// The options bar's W and H of a line (#13250): a resize in the line's own frame.
(Some("transform"), None) if live.zip(nums::<6>(p, "transform")).is_some_and(|(l, m)| is_line_frame_scale(l, &m)) => "Scale Paths",
_ => EDIT,
}
}
@@ -0,0 +1,227 @@
//! #13250: the Line tool's options bar shows W, a link button and H after the stroke controls. With
//! no line active they read 0 px and the link is off; with a line active W is its length and H its
//! thickness (the weight, or the arrowhead width when wider). Typing W or H resizes the line in its
//! own rotated frame as one "Scale Paths" step, keeping it a live line; the tool's own Weight and
//! arrowhead options for the next line do not change.
//!
//! H follows the measured numbers: the start of a 15 px thick line moves from 400,300 to
//! 398.88,302.24 for H 20, a scale about the edge of the line's box on the start's side, not its
//! centre line (a scale about the centre line would keep the start at 400,300).
use egui::accesskit::{Role, Toggled};
use egui::vec2;
use egui_kittest::Harness;
use egui_kittest::kittest::{NodeT, Queryable};
use photocraft_doc::{LayerContent, LayerId, LiveShape};
use serde_json::json;
use crate::PhotocraftApp;
use crate::canvas::{ToolEvent, tool_event};
use crate::state::Tool;
type H = Harness<'static, Box<PhotocraftApp>>;
/// An 800 x 600 document with the Line tool picked, its options bar in a harness; `drawn` drags a
/// line from 400,300 to 600,400 with the tool first.
fn bar(drawn: bool) -> H {
let mut app = PhotocraftApp::new(photocraft_engine::Session::new(), crate::Services::default());
app.run("file.new", json!({"width": 800, "height": 600})).unwrap();
app.sync_views();
app.ui.tool = Tool::Line;
if drawn {
let none = egui::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: 500.0, y: 350.0, pressure: 1.0 }, none);
tool_event(&mut app, ToolEvent::Move { x: 600.0, y: 400.0, pressure: 1.0 }, none);
tool_event(&mut app, ToolEvent::Up { x: 600.0, y: 400.0 }, none);
}
let mut h =
Harness::builder().with_context(app.ctx().clone()).with_size(vec2(2400.0, 300.0)).build_ui_state(|ui, app| crate::panels::options_bar(app, ui), app);
h.run_steps(4);
h
}
/// The drawn line with the End arrowhead on, 15 px wide and 10 px long, set as the Properties panel sets it.
fn arrow_bar() -> (H, LayerId) {
let mut h = bar(true);
let id = active(&h);
h.state_mut().run("shape.edit", json!({"layer": id.0, "arrowEnd": true, "arrowWidth": 15, "arrowLength": 10})).unwrap();
h.run_steps(3);
(h, id)
}
fn active(h: &H) -> LayerId {
h.state().session.active().unwrap().active_layer.unwrap()
}
/// The SpinButton labelled `label`.
fn field<'h>(h: &'h H, label: &'h str) -> egui_kittest::Node<'h> {
h.query_all_by_role(Role::SpinButton).find(|n| n.accesskit_node().label().as_deref() == Some(label)).unwrap_or_else(|| panic!("the {label} field"))
}
/// The number the field labelled `label` shows.
fn shown(h: &H, label: &str) -> f64 {
let text = field(h, label).value().unwrap_or_else(|| panic!("the {label} field shows a value"));
// The decimal mark follows the locale the test runs in.
let number = text.trim_end_matches("px").trim().replace(',', ".");
number.parse().unwrap_or_else(|e| panic!("the {label} field shows a number, not {text:?} ({e})"))
}
/// Types `text` into the field labelled `label`, then Tabs out of it.
fn type_into(h: &mut H, label: &str, text: &str) {
field(h, label).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);
}
/// Whether the link button is on.
fn link_on(h: &H) -> bool {
h.get_by_role_and_label(Role::Button, "Maintain aspect ratio").accesskit_node().toggled() == Some(Toggled::True)
}
/// The live arrow line of layer `id`: from, to, weight, width, length.
fn arrow(h: &H, id: LayerId) -> ([f64; 2], [f64; 2], f64, f64, f64) {
match &h.state().session.active().unwrap().doc.layer(id).unwrap().content {
LayerContent::Shape(sh) => match &sh.live {
Some(LiveShape::ArrowLine { from, to, weight, width, length, end: true, .. }) => (*from, *to, *weight, *width, *length),
other => panic!("a live line with its End arrowhead, got {other:?}"),
},
_ => panic!("a shape layer"),
}
}
fn steps(h: &H) -> usize {
h.state().session.active().unwrap().history.past_len()
}
fn undo_label(h: &H) -> Option<String> {
h.state().session.active().unwrap().history.undo_label().map(str::to_owned)
}
fn near(a: f64, b: f64, tol: f64) -> bool {
(a - b).abs() <= tol
}
fn assert_pt(got: [f64; 2], want: [f64; 2], what: &str) {
assert!(near(got[0], want[0], 0.01) && near(got[1], want[1], 0.01), "{what}: {got:?}, want {want:?}");
}
/// The tool's own settings the next line is drawn with.
fn tool_settings(h: &H) -> (f32, bool, bool, f32, f32) {
let o = &h.state().ui.tool_options;
(o.line_weight, o.arrow_start, o.arrow_end, o.arrow_width, o.arrow_length)
}
#[test]
fn no_line_reads_zero_and_the_link_is_off() {
let h = bar(false);
assert_eq!(shown(&h, "W:"), 0.0);
assert_eq!(shown(&h, "H:"), 0.0);
assert!(!link_on(&h), "the link is off");
}
#[test]
fn a_drawn_line_reads_its_length_and_thickness() {
let h = bar(true);
assert!(near(shown(&h, "W:"), 223.61, 0.006), "W {}", shown(&h, "W:"));
assert_eq!(shown(&h, "H:"), 1.0);
assert!(!link_on(&h), "the link is off");
}
#[test]
fn w_then_h_scale_the_line_in_its_own_frame_as_scale_paths_steps() {
let (mut h, id) = arrow_bar();
let tool = tool_settings(&h);
assert_eq!(shown(&h, "H:"), 15.0, "the thickness includes the 15 px arrowhead");
let before_w = (arrow(&h, id), steps(&h));
type_into(&mut h, "W:", "300");
let (from, to, weight, width, length) = arrow(&h, id);
assert_pt(from, [400.0, 300.0], "W keeps the start");
assert_pt(to, [668.33, 434.16], "W moves the end along the line");
assert!(near(length, 13.416, 0.001), "arrowhead length {length}");
assert!(near(weight, 1.0, 1e-9) && near(width, 15.0, 1e-9), "weight {weight}, width {width}");
assert_eq!(steps(&h), before_w.1 + 1, "one step");
assert_eq!(undo_label(&h).as_deref(), Some("Scale Paths"));
assert!(near(shown(&h, "W:"), 300.0, 0.006));
let before_h = (arrow(&h, id), steps(&h));
type_into(&mut h, "H:", "20");
let (from, to, weight, width, length) = arrow(&h, id);
assert!(near(weight, 1.333, 0.001), "weight {weight}");
assert!(near(width, 20.0, 1e-9), "arrowhead width {width}");
assert!(near(length, 13.416, 0.001), "arrowhead length {length}");
assert_pt(from, [398.88, 302.24], "H moves the start across the line");
assert!(near((to[0] - from[0]).hypot(to[1] - from[1]), 300.0, 1e-6), "H keeps the length");
assert_eq!(steps(&h), before_h.1 + 1, "one step");
assert_eq!(undo_label(&h).as_deref(), Some("Scale Paths"));
assert_eq!(shown(&h, "H:"), 20.0);
assert_eq!(tool_settings(&h), tool, "the tool's Weight and arrowhead options are unchanged");
// Each edit undoes in one step.
h.state_mut().session.undo();
h.run_steps(2);
assert_eq!((arrow(&h, id), steps(&h)), before_h);
h.state_mut().session.undo();
h.run_steps(2);
assert_eq!((arrow(&h, id), steps(&h)), before_w);
}
#[test]
fn zero_negative_or_no_number_changes_nothing() {
let (mut h, id) = arrow_bar();
let before = (arrow(&h, id), steps(&h));
for typed in ["0", "-5", "abc", "NaN", "inf"] {
for label in ["W:", "H:"] {
type_into(&mut h, label, typed);
assert_eq!((arrow(&h, id), steps(&h)), before, "{label} {typed}");
}
}
}
#[test]
fn typing_without_a_line_edits_nothing() {
let mut h = bar(false);
let n = h.state().session.active().unwrap().doc.layers.len();
type_into(&mut h, "W:", "300");
type_into(&mut h, "H:", "20");
assert_eq!(h.state().session.active().unwrap().doc.layers.len(), n);
assert_eq!((shown(&h, "W:"), shown(&h, "H:")), (0.0, 0.0));
}
#[test]
fn the_frame_scale_helper_refuses_sizes_that_are_not_positive_and_finite() {
use photocraft_engine::vector_cmds::{line_frame_scale, line_frame_size};
let line =
LiveShape::ArrowLine { from: [400.0, 300.0], to: [600.0, 400.0], weight: 1.0, start: false, end: true, width: 15.0, length: 10.0, concavity: 0.0 };
let (len, thick) = line_frame_size(&line).unwrap();
assert!(near(len, 223.607, 0.001) && thick == 15.0);
for (l, t) in [(0.0, 15.0), (300.0, 0.0), (f64::NAN, 15.0), (300.0, f64::INFINITY), (-1.0, 15.0)] {
assert!(line_frame_scale(&line, l, t).is_none(), "{l} x {t}");
}
let flat = LiveShape::ArrowLine { from: [1.0, 1.0], to: [1.0, 1.0], weight: 1.0, start: false, end: false, width: 15.0, length: 10.0, concavity: 0.0 };
assert!(line_frame_size(&flat).is_none() && line_frame_scale(&flat, 300.0, 20.0).is_none());
let rect = LiveShape::Rect { rect: [0.0, 0.0, 10.0, 10.0], radii: [0.0; 4] };
assert!(line_frame_size(&rect).is_none() && line_frame_scale(&rect, 300.0, 20.0).is_none());
// A plain line's thickness is its weight, whatever the (hidden) arrowhead width.
let plain =
LiveShape::ArrowLine { from: [400.0, 300.0], to: [600.0, 400.0], weight: 1.0, start: false, end: false, width: 15.0, length: 10.0, concavity: 0.0 };
assert_eq!(line_frame_size(&plain).map(|s| s.1), Some(1.0));
}
#[test]
fn another_transform_of_a_line_keeps_its_history_name() {
let (mut h, id) = arrow_bar();
// A rotation is no scale in the line's frame.
let (s, c) = 0.3f64.sin_cos();
h.state_mut().run("shape.edit", json!({"layer": id.0, "transform": [c, s, -s, c, 0.0, 0.0]})).unwrap();
assert_ne!(undo_label(&h).as_deref(), Some("Scale Paths"));
// A move is none either.
h.state_mut().run("shape.edit", json!({"layer": id.0, "transform": [1.0, 0.0, 0.0, 1.0, 5.0, 5.0]})).unwrap();
assert_ne!(undo_label(&h).as_deref(), Some("Scale Paths"));
}
+70
View File
@@ -175,6 +175,71 @@ fn paint_dialog_target<C>(which: ShapePaint, fg: C, bg: C) -> Option<(crate::sha
}
}
/// The value a W or H field's event proposes, as [`proposal`] reads the bar's events.
fn number_proposal(event: &EditEvent<Option<f64>>) -> Option<f64> {
match event {
EditEvent::Update { value, .. } => *value,
EditEvent::Commit { after, .. } | EditEvent::Set { after, .. } => *after,
EditEvent::Cancel { before: Some(Mixed::Same(value)), .. } => *value,
_ => None,
}
}
/// The Line tool's W, link and H fields (#13250; nothing for another tool): the active line's length and thickness in its own
/// rotated frame, 0 px with no live line. A typed W or H resizes the line along or across itself
/// (`shape.edit {transform}`, one "Scale Paths" step per gesture); the tool's own Weight and
/// arrowhead settings for the next line stay as they are. What the link does was not measured: it
/// shows off and changes nothing.
fn line_size_fields(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool, target: Option<&SelectedShape>) {
use craft::ui::contract::{ShowContainer as _, SideLabel};
use craft::ui::form::Field;
use craft::ui::runtime::env::{Label, UnitKind};
use craft::ui::text::NumberField;
if tool != Tool::Line {
return;
}
let live = target.and_then(|s| s.live.as_ref().map(|l| (s.doc, s.layer, l.clone())));
let size = live.as_ref().and_then(|(_, _, l)| photocraft_engine::vector_cmds::line_frame_size(l));
let (w, h) = size.unwrap_or((0.0, 0.0));
let field = |ui: &mut egui::Ui, key: &str, caption: &str, value: f64| {
let caption = Label::from(caption.to_owned());
Field::new(caption.clone())
.id_salt(key)
.side(SideLabel::new().scrub(true))
.show(ui, |ui, _| {
// Two decimals, as the reference shows a line's length (223.61 px); a whole number shows none.
let codec = craft::behavior::NumberCodec::new(Env::of(ui).units().reader(Some(UnitKind::Pixels)), 2);
NumberField::new(caption.clone(), Bind::given(Some(value))).unit_kind(UnitKind::Pixels).codec(codec).scrub_by_label().show(ui).edit.events
})
.inner
.unwrap_or_default()
};
Divider::vertical().show(ui);
let w_events = field(ui, "line-w", tl!("W:"), w);
let _ = craft::ui::text::link_toggle(Label::from(tl!("Maintain aspect ratio").to_owned()), Bind::given(false)).show(ui);
let h_events = field(ui, "line-h", tl!("H:"), h);
let (Some((doc, layer, live)), Some((w, h))) = (live, size) else { return };
for (axis, events) in [("w", w_events), ("h", h_events)] {
for event in &events {
let Some(value) = number_proposal(event) else { continue };
let (length, thickness) = if axis == "w" { (value, h) } else { (w, value) };
// A cleared, zero, negative or non-finite value is not a size: no edit.
let Some(m) = photocraft_engine::vector_cmds::line_frame_scale(&live, length, thickness) else { continue };
if m == photocraft_geom::Affine::IDENTITY {
continue;
}
let key = crate::history_keys::coalesce(&format!("line-size-{doc:?}-{}-{axis}", layer.0), event);
if let Err(e) = app.run("shape.edit", json!({"layer": layer.0, "transform": m.m, "coalesce": key})) {
app.ui.status = e;
app.ui.status_error = true;
}
// The first value applied changes the line: later events of this pass would scale from stale sizes.
return;
}
}
}
pub(crate) fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool, paint: bool) {
// Path mode edits only the next outline: an active shape layer is not the target.
let target = if paint { selected_shape(&app.session) } else { None };
@@ -224,6 +289,7 @@ pub(crate) fn options_bar(app: &mut PhotocraftApp, ui: &mut egui::Ui, tool: Tool
.chips(|which, chip, chip_ui| decorate_chip(chip, which, &mut library, chip_ui))
.show(ui);
let (fill_gradient, stroke_gradient) = (library.gradient(ShapePaint::Fill), library.gradient(ShapePaint::Stroke));
line_size_fields(app, ui, tool, target.as_ref());
if tool == Tool::Triangle {
Divider::vertical().show(ui);
// Only a shape layer has pixel edges to align: greyed in Path mode (#13370).
@@ -383,3 +449,7 @@ mod rectangle_radius_target_tests;
#[cfg(test)]
#[path = "polygon_sides_alert_tests.rs"]
mod polygon_sides_alert_tests;
#[cfg(test)]
#[path = "line_wh_fields_tests.rs"]
mod line_wh_fields_tests;