mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-24 11:23:43 +01:00
Dimension tool: Alt over a path places its overall width or height
With the Linear Dimension tool and Alt (Option on macOS) held, hovering a
path shows a box through its outermost points (a Smart Guide when Smart
Guides are on), with its width and height beside the pointer when
Measurement Labels are on. A click on the path, then a placing click, or a
drag out from it, places a dimension of the whole path. With the pointer
above or below the path it measures the width, between the leftmost and
rightmost points; beside the path it measures the height, between the
topmost and bottommost points. The linear dimensions help page describes
the Alt hover; which side gives which measure is VectorCraft's own rule.
dimension.create takes a new source, {kind: extent, node}, for linear
dimensions. Its points are the outermost points of the segments the path
draws, curves included, and are read again whenever the path changes, so a
turned path shows its new overall width or height. The line keeps its
distance from the whole path when the path changes or is reflected, and
when dimension.update changes the orientation, which now reads the other
pair of points. When the box through the path's outermost points stays
where it was, as after Reverse Path Direction, the line stays on its side.
A version without the extent source does not open a file that holds one.
The measurement label beside the pointer while two points are picked now
keeps its distance in screen pixels at any zoom.
The Help Bar hint names Alt+Click. Docs: docs/dimensions.md and
docs/target-app-parity.md.
This commit is contained in:
1 parent
9fff48d88f
commit
5a26a9abd5
7 files changed
+530
-42
No files matched your search
+162
-23
@@ -389,6 +389,12 @@ pub enum DimensionSource {
|
||||
#[serde(default, rename = "freeB", skip_serializing_if = "Option::is_none")]
|
||||
free_b: Option<FreePoint>,
|
||||
},
|
||||
/// A whole path, measured between its outermost points ([`extent`]): the leftmost and the
|
||||
/// rightmost while the dimension is horizontal or aligned, the topmost and the bottommost while
|
||||
/// it is vertical. Versions without this source do not open the file.
|
||||
Extent {
|
||||
node: NodeId,
|
||||
},
|
||||
}
|
||||
|
||||
impl DimensionSource {
|
||||
@@ -396,7 +402,7 @@ impl DimensionSource {
|
||||
match self {
|
||||
Self::Segment { edge } | Self::Arc { edge } => vec![edge.node],
|
||||
Self::Angle { first, second } => vec![first.node, second.node],
|
||||
Self::Circle { node } => vec![*node],
|
||||
Self::Circle { node } | Self::Extent { node } => vec![*node],
|
||||
Self::Points { a, b, vertex, free_a, free_b } => [a, b, vertex]
|
||||
.into_iter()
|
||||
.filter_map(|p| p.as_ref().map(|r| r.node))
|
||||
@@ -407,7 +413,7 @@ impl DimensionSource {
|
||||
/// Anchor indexes cannot safely follow a topology replacement. Ordinary moves and handle
|
||||
/// edits keep their topology and remain linked.
|
||||
pub fn topology_changed(&self, before: &Document, after: &Document) -> bool {
|
||||
if matches!(self, Self::Circle { .. }) {
|
||||
if matches!(self, Self::Circle { .. } | Self::Extent { .. }) {
|
||||
return false;
|
||||
}
|
||||
self.nodes().iter().any(|id| {
|
||||
@@ -418,9 +424,18 @@ impl DimensionSource {
|
||||
old.is_some() && old != counts(after)
|
||||
})
|
||||
}
|
||||
/// Whether a path it measures differs between `before` and `after`, or is in only one of them.
|
||||
pub fn art_changed(&self, before: &Document, after: &Document) -> bool {
|
||||
self.nodes().into_iter().any(|id| match (before.node(id), after.node(id)) {
|
||||
(Some(old), Some(new)) => !std::ptr::eq(old, new) && old.path_data() != new.path_data(),
|
||||
(old, new) => old.is_some() != new.is_some(),
|
||||
})
|
||||
}
|
||||
/// The map that took the measured art from `before` to `after`, when every path it measures
|
||||
/// went through one [`art_transform`] that reflects it (a negative determinant). None when a
|
||||
/// measured path is unchanged, or when two of them went through different maps.
|
||||
/// measured path is unchanged, or when two of them went through different maps. None for a
|
||||
/// dimension of a whole path whose path's box through its outermost points stays where it
|
||||
/// was, as after its direction is reversed.
|
||||
pub fn reflection(&self, before: &Document, after: &Document) -> Option<Affine> {
|
||||
let mut first: Option<Affine> = None;
|
||||
for id in self.nodes() {
|
||||
@@ -429,6 +444,9 @@ impl DimensionSource {
|
||||
return None;
|
||||
}
|
||||
let xf = fitted(before, after, id, |xf| xf.determinant() < 0.0)?;
|
||||
if matches!(self, Self::Extent { .. }) && same_extents(before, after, id) {
|
||||
return None;
|
||||
}
|
||||
match first {
|
||||
None => first = Some(xf),
|
||||
Some(f) => {
|
||||
@@ -759,19 +777,22 @@ impl Dimension {
|
||||
/// outside them as it was, on the same side: the gap is measured from the outermost point
|
||||
/// on the line's side, so the line stays clear of art that turns. A line that lay between
|
||||
/// the two points keeps its distance from the first point.
|
||||
pub fn keep_gap(&mut self, old: &Dimension) {
|
||||
/// With `docs`, the documents `old` and this dimension were read from, the gap of a dimension of
|
||||
/// a whole path is measured from the whole path ([`Self::span`]), also when only parts of the
|
||||
/// path other than its measured points moved, and also when the dimension is aligned (each
|
||||
/// along its own normal).
|
||||
pub fn keep_gap(&mut self, old: &Dimension, docs: Option<(&Document, &Document)>) {
|
||||
let whole = docs.is_some() && matches!(self.source, Some(DimensionSource::Extent { .. }));
|
||||
if self.mode != DimensionMode::Linear
|
||||
|| self.orientation == Orientation::Aligned
|
||||
|| (self.orientation == Orientation::Aligned && !whole)
|
||||
|| old.orientation != self.orientation
|
||||
|| (self.a, self.b) == (old.a, old.b)
|
||||
|| ((self.a, self.b) == (old.a, old.b) && !whole)
|
||||
{
|
||||
return;
|
||||
}
|
||||
let n = self.normal();
|
||||
let across = |p: Point| p.to_vec2().dot(n);
|
||||
let line = across(old.a) + old.offset;
|
||||
let (low, high) = (across(old.a).min(across(old.b)), across(old.a).max(across(old.b)));
|
||||
let (new_low, new_high) = (across(self.a).min(across(self.b)), across(self.a).max(across(self.b)));
|
||||
let line = old.a.to_vec2().dot(old.normal()) + old.offset;
|
||||
let (low, high) = old.span(docs.map(|(before, _)| before));
|
||||
let (new_low, new_high) = self.span(docs.map(|(_, after)| after));
|
||||
let at = if line >= high {
|
||||
new_high + (line - high)
|
||||
} else if line <= low {
|
||||
@@ -779,7 +800,7 @@ impl Dimension {
|
||||
} else {
|
||||
return;
|
||||
};
|
||||
let offset = at - across(self.a);
|
||||
let offset = at - self.a.to_vec2().dot(self.normal());
|
||||
if offset.is_finite() && offset.abs() <= 1e6 {
|
||||
self.offset = offset;
|
||||
}
|
||||
@@ -787,8 +808,9 @@ impl Dimension {
|
||||
/// A linear dimension whose art was reflected, its points now moved from `old`'s: its line goes
|
||||
/// to the side of the points that `image` (where the reflection put `old`'s line) is on, as far
|
||||
/// past the outermost point on that side as `old`'s line was. A line that lay between the two
|
||||
/// points is left as it is.
|
||||
pub fn mirror_line(&mut self, old: &Dimension, image: Point) {
|
||||
/// points is left as it is. With `docs`, as in [`Self::keep_gap`], a dimension of a whole path
|
||||
/// measures from the whole path.
|
||||
pub fn mirror_line(&mut self, old: &Dimension, image: Point, docs: Option<(&Document, &Document)>) {
|
||||
if self.mode != DimensionMode::Linear || old.mode != DimensionMode::Linear {
|
||||
return;
|
||||
}
|
||||
@@ -796,7 +818,7 @@ impl Dimension {
|
||||
let n = old.normal();
|
||||
let across = |p: Point| p.to_vec2().dot(n);
|
||||
let line = across(old.a) + old.offset;
|
||||
let (low, high) = (across(old.a).min(across(old.b)), across(old.a).max(across(old.b)));
|
||||
let (low, high) = old.span(docs.map(|(before, _)| before));
|
||||
if line >= high {
|
||||
line - high
|
||||
} else if line <= low {
|
||||
@@ -807,13 +829,25 @@ impl Dimension {
|
||||
};
|
||||
let n = self.normal();
|
||||
let across = |p: Point| p.to_vec2().dot(n);
|
||||
let (low, high) = (across(self.a).min(across(self.b)), across(self.a).max(across(self.b)));
|
||||
let (low, high) = self.span(docs.map(|(_, after)| after));
|
||||
let at = if 2.0 * across(image) >= low + high { high + gap } else { low - gap };
|
||||
let offset = at - across(self.a);
|
||||
if offset.is_finite() && offset.abs() <= 1e6 {
|
||||
self.offset = offset;
|
||||
}
|
||||
}
|
||||
/// Where a linear dimension's art lies along its normal, lowest and highest: its two points,
|
||||
/// or, for a dimension of a whole path read from `doc`, the whole path ([`reach`]), so that
|
||||
/// the whole path is on one side of a line outside the span.
|
||||
fn span(&self, doc: Option<&Document>) -> (f64, f64) {
|
||||
let n = self.normal();
|
||||
let (a, b) = (self.a.to_vec2().dot(n), self.b.to_vec2().dot(n));
|
||||
let (low, high) = (a.min(b), a.max(b));
|
||||
match (doc, &self.source) {
|
||||
(Some(doc), Some(DimensionSource::Extent { node })) => reach(doc, *node, n).map_or((low, high), |(l, h)| (low.min(l), high.max(h))),
|
||||
_ => (low, high),
|
||||
}
|
||||
}
|
||||
/// Whether a linear dimension's line lies strictly between its two points along the normal.
|
||||
fn line_between_points(&self) -> bool {
|
||||
let n = self.normal();
|
||||
@@ -824,19 +858,36 @@ impl Dimension {
|
||||
/// Makes a linear dimension measure in `orientation`, with its line on the side of the points
|
||||
/// it was on. The line goes through the middle of the old line when that point lies outside
|
||||
/// the two points along the new normal; otherwise it lies as far past the outermost point on
|
||||
/// that side as the old line lay from its points.
|
||||
pub fn set_orientation(&mut self, orientation: Orientation) {
|
||||
/// that side as the old line lay from its points. A dimension of a whole path
|
||||
/// ([`DimensionSource::Extent`]) first reads from `doc` the outermost points it measures in the
|
||||
/// new orientation, and its line keeps its distance from the whole path ([`Self::span`]), on
|
||||
/// the side the middle of the old line is on.
|
||||
pub fn set_orientation(&mut self, orientation: Orientation, doc: &Document) -> Result<(), String> {
|
||||
if self.mode != DimensionMode::Linear || self.orientation == orientation {
|
||||
self.orientation = orientation;
|
||||
return;
|
||||
return Ok(());
|
||||
}
|
||||
let (handle, mut gap) = (self.handle(), self.offset.abs());
|
||||
if let Some(DimensionSource::Extent { .. }) = &self.source {
|
||||
// Measured from the whole path.
|
||||
let (low, high) = self.span(Some(doc));
|
||||
let line = self.a.to_vec2().dot(self.normal()) + self.offset;
|
||||
gap = if line >= high { line - high } else { (low - line).max(0.0) };
|
||||
}
|
||||
let (handle, gap) = (self.handle(), self.offset.abs());
|
||||
self.orientation = orientation;
|
||||
if let Some(DimensionSource::Extent { node }) = &self.source {
|
||||
(self.a, self.b) = extent(doc, *node, orientation == Orientation::Vertical).ok_or("Measured path no longer exists")?;
|
||||
}
|
||||
let n = self.normal();
|
||||
let across = |p: Point| p.to_vec2().dot(n);
|
||||
let (low, high) = (across(self.a).min(across(self.b)), across(self.a).max(across(self.b)));
|
||||
let (low, high) = self.span(Some(doc));
|
||||
let h = across(handle);
|
||||
let at = if h >= high || h <= low {
|
||||
let whole = matches!(self.source, Some(DimensionSource::Extent { .. }));
|
||||
let at = if whole && h >= high {
|
||||
high + gap
|
||||
} else if whole && h <= low {
|
||||
low - gap
|
||||
} else if h >= high || h <= low {
|
||||
h
|
||||
} else if 2.0 * h >= low + high {
|
||||
high + gap
|
||||
@@ -848,6 +899,7 @@ impl Dimension {
|
||||
self.offset = offset;
|
||||
}
|
||||
self.length = self.measured();
|
||||
Ok(())
|
||||
}
|
||||
fn bisector(&self) -> Vec2 {
|
||||
let start = (self.a - self.vertex).atan2();
|
||||
@@ -889,7 +941,7 @@ impl Dimension {
|
||||
self.offset = offset;
|
||||
}
|
||||
if self.line_between_points() && !old.line_between_points() {
|
||||
self.keep_gap(&old);
|
||||
self.keep_gap(&old, None);
|
||||
}
|
||||
} else if self.mode == DimensionMode::Linear && xf.determinant() < 0.0 && (self.b - self.a).hypot() > 1e-9 {
|
||||
// A reflection turns the left normal of a → b to the other side, so an aligned
|
||||
@@ -948,6 +1000,12 @@ impl Dimension {
|
||||
let (center, radius) = arc(doc, edge).ok_or("Choose a circle or a perfect arc")?;
|
||||
self.set_radial(center, radius);
|
||||
}
|
||||
Some(DimensionSource::Extent { node }) => {
|
||||
let (a, b) = extent(doc, *node, self.orientation == Orientation::Vertical).ok_or("Measured path no longer exists")?;
|
||||
self.a = a;
|
||||
self.b = b;
|
||||
self.length = self.measured();
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
self.validate()
|
||||
@@ -1048,6 +1106,87 @@ pub fn arc(doc: &Document, edge: &SegmentRef) -> Option<(Point, f64)> {
|
||||
Some((center, radius))
|
||||
}
|
||||
|
||||
/// The outermost points of a path's outline, read from its segments (an anchor that starts no
|
||||
/// segment is not part of it): the leftmost and the rightmost, then the topmost and the
|
||||
/// bottommost. Of points level with each other, the first point is the topmost or leftmost of
|
||||
/// them and the second the bottommost or rightmost, so a straight vertical line has two points
|
||||
/// across its width too. None for a node without a path or without segments.
|
||||
pub fn extents(doc: &Document, id: NodeId) -> Option<[(Point, Point); 2]> {
|
||||
use vectorcraft_geom::kurbo::{ParamCurve, ParamCurveExtrema};
|
||||
let path = doc.node(id)?.path_data()?;
|
||||
let before = |p: Point, q: Point, vertical: bool| {
|
||||
let key = |p: Point| if vertical { (p.y, p.x) } else { (p.x, p.y) };
|
||||
let (a, b) = (key(p), key(q));
|
||||
a.0.total_cmp(&b.0).then(a.1.total_cmp(&b.1)).is_lt()
|
||||
};
|
||||
let mut ends: Option<[(Point, Point); 2]> = None;
|
||||
let mut take = |p: Point| {
|
||||
let ends = ends.get_or_insert([(p, p); 2]);
|
||||
for (axis, (low, high)) in ends.iter_mut().enumerate() {
|
||||
if before(p, *low, axis == 1) {
|
||||
*low = p;
|
||||
}
|
||||
if before(*high, p, axis == 1) {
|
||||
*high = p;
|
||||
}
|
||||
}
|
||||
};
|
||||
for sp in &path.subpaths {
|
||||
for i in 0..sp.segment_count() {
|
||||
let seg = sp.segment(i);
|
||||
take(seg.p0);
|
||||
take(seg.p3);
|
||||
for t in seg.extrema() {
|
||||
take(seg.eval(t));
|
||||
}
|
||||
}
|
||||
}
|
||||
ends
|
||||
}
|
||||
|
||||
/// Whether the box through a path's outermost points ([`extents`]) is where it was in `before`,
|
||||
/// each side to within rounding against the larger coordinate on its axis.
|
||||
fn same_extents(before: &Document, after: &Document, id: NodeId) -> bool {
|
||||
let sides = |doc: &Document| extents(doc, id).map(|[(left, right), (top, bottom)]| [left.x, right.x, top.y, bottom.y]);
|
||||
let (Some(old), Some(new)) = (sides(before), sides(after)) else { return false };
|
||||
[0, 2].into_iter().all(|i| {
|
||||
let scale = old[i].abs().max(old[i + 1].abs()).max(1.0);
|
||||
(i..i + 2).all(|j| (old[j] - new[j]).abs() <= 1e-12 * scale)
|
||||
})
|
||||
}
|
||||
|
||||
/// [`extents`] along one axis: the leftmost and the rightmost points, or with `vertical` the
|
||||
/// topmost and the bottommost.
|
||||
pub fn extent(doc: &Document, id: NodeId, vertical: bool) -> Option<(Point, Point)> {
|
||||
extents(doc, id).map(|ends| ends[usize::from(vertical)])
|
||||
}
|
||||
|
||||
/// How far a path's outline reaches along the unit direction `u`: the lowest and the highest
|
||||
/// `p · u` over the points of its segments. None for a node without a path or without segments.
|
||||
pub fn reach(doc: &Document, id: NodeId, u: Vec2) -> Option<(f64, f64)> {
|
||||
use vectorcraft_geom::kurbo::{ParamCurve, ParamCurveExtrema};
|
||||
let path = doc.node(id)?.path_data()?;
|
||||
// Turns `u` onto the x axis, so the turned curve's extrema include those along `u`.
|
||||
let turn = Affine::new([u.x, -u.y, u.y, u.x, 0.0, 0.0]);
|
||||
let mut span: Option<(f64, f64)> = None;
|
||||
let mut take = |p: Point| {
|
||||
let v = p.to_vec2().dot(u);
|
||||
let (low, high) = span.get_or_insert((v, v));
|
||||
(*low, *high) = (low.min(v), high.max(v));
|
||||
};
|
||||
for sp in &path.subpaths {
|
||||
for i in 0..sp.segment_count() {
|
||||
let seg = sp.segment(i);
|
||||
take(seg.p0);
|
||||
take(seg.p3);
|
||||
for t in (turn * seg).extrema() {
|
||||
take(seg.eval(t));
|
||||
}
|
||||
}
|
||||
}
|
||||
span
|
||||
}
|
||||
|
||||
/// The two straight segments that meet at a corner anchor, if both are straight.
|
||||
pub fn corner(doc: &Document, node: NodeId, subpath: usize, anchor: usize) -> Option<(SegmentRef, SegmentRef)> {
|
||||
let sp = doc.node(node)?.path_data()?.subpaths.get(subpath)?;
|
||||
|
||||
@@ -14,7 +14,7 @@ pub fn specs() -> Vec<CommandSpec> {
|
||||
"Create Dimension",
|
||||
[],
|
||||
None,
|
||||
"{mode?: linear|angular|radius|diameter, a?: [x,y], b?: [x,y], vertex?: [x,y], source?: {kind: segment, edge: {node,subpath,segment}}|{kind: angle, first: edge, second: edge}|{kind: circle, node}|{kind: arc, edge}|{kind: points, a?, b?, vertex?: {node,subpath,anchor}, freeA?, freeB?: a point that is not an anchor, {kind: onSegment, edge: {node,subpath,segment}, t: 0..1 (curve parameter)}|{kind: anchors, node, anchors: [{subpath,anchor,part?: point|in|out (the anchor, default, or its in or out handle),weight}] (2 or 3 points of one path whose weights add up to 1), across?: (2 anchors only: times the first-to-second anchor vector (x,y) turned to (-y,x), which points down when the vector points right)} (an end is an anchor or a free point, not both)}, orientation?: aligned|horizontal|vertical (linear only: the distance between the points, or only its horizontal or vertical part; default aligned), offset?: pt (the line's distance from the first point: along the left normal of a → b when aligned, downward when horizontal, leftward when vertical; negative goes the other way), options?: {units: in|mm|pt|pc|px|cm|m|ft|yd, precision: 0-6, scale: drawing:real, hideUnits, lineWeight, lineType: solid|dashed|dotted, lineColor: [r,g,b], arrowStyle: filled|open|tick|none, arrowHead: null|a built-in stroke.set arrowhead name (Barbed, LineArrow…; drawn at both ends in place of arrowStyle's head; versions that have the stroke arrowhead but do not read arrowHead draw arrowStyle when they draw the dimension again; custom arrowheads are refused), arrowScale: %, extensionWeight, extensionType, extensionColor, extensionOffset, extensionLength, hideExtensions, fontFamily, fontStyle, fontSize, textColor, textPosition: away|between, textAlignment: left|center|right, textOffset}} → {id,label}; linked measurements follow source edits",
|
||||
"{mode?: linear|angular|radius|diameter, a?: [x,y], b?: [x,y], vertex?: [x,y], source?: {kind: segment, edge: {node,subpath,segment}}|{kind: angle, first: edge, second: edge}|{kind: circle, node}|{kind: arc, edge}|{kind: extent, node} (linear only: a whole path between its outermost points, leftmost and rightmost when horizontal or aligned, topmost and bottommost when vertical)|{kind: points, a?, b?, vertex?: {node,subpath,anchor}, freeA?, freeB?: a point that is not an anchor, {kind: onSegment, edge: {node,subpath,segment}, t: 0..1 (curve parameter)}|{kind: anchors, node, anchors: [{subpath,anchor,part?: point|in|out (the anchor, default, or its in or out handle),weight}] (2 or 3 points of one path whose weights add up to 1), across?: (2 anchors only: times the first-to-second anchor vector (x,y) turned to (-y,x), which points down when the vector points right)} (an end is an anchor or a free point, not both)}, orientation?: aligned|horizontal|vertical (linear only: the distance between the points, or only its horizontal or vertical part; default aligned), offset?: pt (the line's distance from the first point: along the left normal of a → b when aligned, downward when horizontal, leftward when vertical; negative goes the other way), options?: {units: in|mm|pt|pc|px|cm|m|ft|yd, precision: 0-6, scale: drawing:real, hideUnits, lineWeight, lineType: solid|dashed|dotted, lineColor: [r,g,b], arrowStyle: filled|open|tick|none, arrowHead: null|a built-in stroke.set arrowhead name (Barbed, LineArrow…; drawn at both ends in place of arrowStyle's head; versions that have the stroke arrowhead but do not read arrowHead draw arrowStyle when they draw the dimension again; custom arrowheads are refused), arrowScale: %, extensionWeight, extensionType, extensionColor, extensionOffset, extensionLength, hideExtensions, fontFamily, fontStyle, fontSize, textColor, textPosition: away|between, textAlignment: left|center|right, textOffset}} → {id,label}; linked measurements follow source edits",
|
||||
has_doc,
|
||||
create
|
||||
),
|
||||
@@ -80,6 +80,7 @@ fn recipe(s: &Session, p: &Value) -> Result<Dimension> {
|
||||
| (DimensionMode::Angular, DimensionSource::Angle { .. })
|
||||
| (DimensionMode::Radius | DimensionMode::Diameter, DimensionSource::Circle { .. } | DimensionSource::Arc { .. })
|
||||
| (DimensionMode::Linear | DimensionMode::Angular, DimensionSource::Points { .. })
|
||||
| (DimensionMode::Linear, DimensionSource::Extent { .. })
|
||||
);
|
||||
if !compatible {
|
||||
return Err(error("Dimension mode does not match its source"));
|
||||
@@ -174,7 +175,7 @@ fn update(s: &mut Session, p: &Value) -> Result<Value> {
|
||||
dim.options = o.clone();
|
||||
}
|
||||
if let Some(orientation) = orientation(p, dim.mode)? {
|
||||
dim.set_orientation(orientation);
|
||||
dim.set_orientation(orientation, doc).map_err(error)?;
|
||||
}
|
||||
dim.offset = distance(p, dim.offset)?;
|
||||
dim.resolve(doc).map_err(error)?;
|
||||
@@ -452,7 +453,14 @@ pub(crate) fn refresh(before: &Document, doc: &mut Document) -> Result<bool> {
|
||||
for (id, old) in dimensions {
|
||||
let mut next = old.clone();
|
||||
let moved = next.moved.take();
|
||||
if next.source.as_ref().is_some_and(|s| s.topology_changed(before, doc)) || next.resolve(doc).is_err() {
|
||||
// Whether the path a dimension of a whole path measures changed: when it did not, the
|
||||
// dimension keeps its points without reading the path again, and is only checked.
|
||||
let whole_changed = match &next.source {
|
||||
Some(s @ DimensionSource::Extent { .. }) => Some(s.art_changed(before, doc)),
|
||||
_ => None,
|
||||
};
|
||||
let unreadable = if whole_changed == Some(false) { next.validate().is_err() } else { next.resolve(doc).is_err() };
|
||||
if next.source.as_ref().is_some_and(|s| s.topology_changed(before, doc)) || unreadable {
|
||||
// The art it measured was deleted, or rebuilt with other anchors, or no longer fits
|
||||
// (an ellipse that was a circle): it stays where it was, no longer linked, in this
|
||||
// same undo step, rather than attaching to a different edge.
|
||||
@@ -465,13 +473,14 @@ pub(crate) fn refresh(before: &Document, doc: &mut Document) -> Result<bool> {
|
||||
changed = true;
|
||||
continue;
|
||||
}
|
||||
next.keep_gap(&old);
|
||||
next.keep_gap(&old, (whole_changed == Some(true)).then_some((before, doc)));
|
||||
if let Some(xf) = next.source.as_ref().and_then(|s| s.reflection(before, doc)) {
|
||||
next.mirror_line(&old, xf * old.handle());
|
||||
next.mirror_line(&old, xf * old.handle(), Some((before, doc)));
|
||||
}
|
||||
// Moved on its own (the art it measures stayed put): it keeps its new place.
|
||||
if let Some(v) = moved
|
||||
&& (next.a, next.b, next.vertex) == (old.a, old.b, old.vertex)
|
||||
&& whole_changed != Some(true)
|
||||
{
|
||||
next.place(old.handle() + v);
|
||||
if next.resolve(doc).is_err() {
|
||||
|
||||
@@ -466,6 +466,138 @@ fn turned_horizontal_dimensions_stay_horizontal() {
|
||||
assert_eq!(text(&s, id), "100.00 pt");
|
||||
}
|
||||
|
||||
/// A dimension of a whole path measures the path's overall width, or its height when vertical,
|
||||
/// between its outermost points, and follows the path when it turns. Turned 30°, a 100 × 60
|
||||
/// rectangle is 100 cos 30° + 60 sin 30° wide, more than either side; a turned ellipse is measured
|
||||
/// at the outermost points of its curves, which are not anchors.
|
||||
#[test]
|
||||
fn a_dimension_of_a_whole_path_measures_its_overall_width_and_height() {
|
||||
let value = |s: &Session, id: u64| text(s, id).trim_end_matches(" pt").parse::<f64>().unwrap();
|
||||
let mut s = session();
|
||||
let rect = run(&mut s, "shape.rectangle", json!({"x":100,"y":100,"width":100,"height":60}))["id"].as_u64().unwrap();
|
||||
let source = json!({"kind":"extent","node":rect});
|
||||
let id = run(&mut s, "dimension.create", json!({"source":source,"orientation":"horizontal","offset":-30}))["id"].as_u64().unwrap();
|
||||
assert_eq!(text(&s, id), "100.00 pt");
|
||||
run(&mut s, "select.set", json!({"ids":[rect]}));
|
||||
run(&mut s, "object.rotate", json!({"angle":30}));
|
||||
let wide = 100.0 * 30f64.to_radians().cos() + 60.0 * 30f64.to_radians().sin();
|
||||
assert!((value(&s, id) - wide).abs() < 0.01, "{} against {wide}", text(&s, id));
|
||||
// The rectangle's box: left, top, right, bottom.
|
||||
let bounds = |s: &Session| {
|
||||
let anchors = s.doc().unwrap().doc.node(NodeId(rect)).unwrap().path_data().unwrap().subpaths[0].anchors.clone();
|
||||
let (xs, ys): (Vec<f64>, Vec<f64>) = anchors.iter().map(|a| (a.p.x, a.p.y)).unzip();
|
||||
let low = |v: &[f64]| v.iter().copied().fold(f64::INFINITY, f64::min);
|
||||
let high = |v: &[f64]| v.iter().copied().fold(f64::NEG_INFINITY, f64::max);
|
||||
(low(&xs), low(&ys), high(&xs), high(&ys))
|
||||
};
|
||||
// The line stays 30 pt above the turned rectangle's topmost corner, clear of the art.
|
||||
let (left, top, right, _) = bounds(&s);
|
||||
let line = recipe(&s, id).line_ends().0.y;
|
||||
assert!((line - (top - 30.0)).abs() < 0.01, "line at y = {line}, top at {top}");
|
||||
run(&mut s, "dimension.update", json!({"ids":[id],"orientation":"vertical"}));
|
||||
let tall = 100.0 * 30f64.to_radians().sin() + 60.0 * 30f64.to_radians().cos();
|
||||
assert!((value(&s, id) - tall).abs() < 0.01, "{} against {tall}", text(&s, id));
|
||||
let d = recipe(&s, id);
|
||||
let (top, bottom) = (d.a.y.min(d.b.y), d.a.y.max(d.b.y));
|
||||
assert!(((bottom - top) - tall).abs() < 0.01, "the points are the topmost and bottommost: {:?} {:?}", d.a, d.b);
|
||||
// The line was 30 pt above the path; turned, it is 30 pt beside it.
|
||||
let line = d.line_ends().0.x;
|
||||
assert!((line - (left - 30.0)).abs() < 0.01 || (line - (right + 30.0)).abs() < 0.01, "line at x = {line}, path from {left} to {right}");
|
||||
run(&mut s, "edit.undo", json!({}));
|
||||
assert!((value(&s, id) - wide).abs() < 0.01, "{}", text(&s, id));
|
||||
// A linear dimension only.
|
||||
assert!(s.execute("dimension.create", &json!({"mode":"angular","source":source})).is_err());
|
||||
|
||||
let ellipse = run(&mut s, "shape.ellipse", json!({"x":300,"y":100,"width":100,"height":50}))["id"].as_u64().unwrap();
|
||||
let id = run(&mut s, "dimension.create", json!({"source":{"kind":"extent","node":ellipse},"orientation":"horizontal"}))["id"].as_u64().unwrap();
|
||||
run(&mut s, "select.set", json!({"ids":[ellipse]}));
|
||||
run(&mut s, "object.rotate", json!({"angle":45}));
|
||||
let anchors = s.doc().unwrap().doc.node(NodeId(ellipse)).unwrap().path_data().unwrap().subpaths[0].anchors.clone();
|
||||
let between_anchors = anchors.iter().map(|a| a.p.x).fold(f64::MIN, f64::max) - anchors.iter().map(|a| a.p.x).fold(f64::MAX, f64::min);
|
||||
// 2 √(50² cos² 45° + 25² sin² 45°)
|
||||
let across = 2.0 * (2500.0f64 * 0.5 + 625.0 * 0.5).sqrt();
|
||||
assert!(value(&s, id) > between_anchors + 1.0, "{} against the anchors' {between_anchors}", text(&s, id));
|
||||
assert!((value(&s, id) - across).abs() < 0.1, "{} against {across}", text(&s, id));
|
||||
}
|
||||
|
||||
/// A dimension of a whole path measures the segments the path draws: an anchor that starts no
|
||||
/// segment does not widen it. Its line stays clear of the whole path when only parts other than
|
||||
/// its measured points move, also when it is aligned or is scaled together with the path, when the
|
||||
/// path's direction is reversed or the path is reflected onto itself, and when it becomes aligned.
|
||||
/// A reflection that moves the path puts the line on the reflected side.
|
||||
#[test]
|
||||
fn a_dimension_of_a_whole_path_stays_clear_of_the_path_it_draws() {
|
||||
let mut s = session();
|
||||
let lone = run(&mut s, "path.create", json!({"d":"M100 300 L110 300 M200 400","closed":false}))["id"].as_u64().unwrap();
|
||||
assert_eq!(s.doc().unwrap().doc.node(NodeId(lone)).unwrap().path_data().unwrap().subpaths.len(), 2, "the lone anchor is kept");
|
||||
let id = run(&mut s, "dimension.create", json!({"source":{"kind":"extent","node":lone},"orientation":"horizontal"}))["id"].as_u64().unwrap();
|
||||
assert_eq!(text(&s, id), "10.00 pt");
|
||||
|
||||
// A triangle whose top rises while its leftmost and rightmost points stay: the line stays
|
||||
// 30 pt above the top.
|
||||
let tri = run(&mut s, "path.create", json!({"d":"M100 200 L150 120 L200 200 Z","closed":true}))["id"].as_u64().unwrap();
|
||||
let id = run(&mut s, "dimension.create", json!({"source":{"kind":"extent","node":tri},"orientation":"horizontal","offset":-110}))["id"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
assert!((recipe(&s, id).line_ends().0.y - 90.0).abs() < 1e-6);
|
||||
run(&mut s, "select.set", json!({"ids":[tri]}));
|
||||
run(&mut s, "object.scale", json!({"sx":100,"sy":150,"origin":[150,200]}));
|
||||
let line = recipe(&s, id).line_ends().0.y;
|
||||
assert!((line - 50.0).abs() < 1e-6, "line at y = {line}");
|
||||
// The same for an aligned dimension, and for a dimension scaled together with its path.
|
||||
for (x, orientation, with_dimension) in [(300.0, "aligned", false), (500.0, "horizontal", true)] {
|
||||
let d = format!("M{x} 200 L{} 120 L{} 200 Z", x + 50.0, x + 100.0);
|
||||
let tri = run(&mut s, "path.create", json!({"d":d,"closed":true}))["id"].as_u64().unwrap();
|
||||
let source = json!({"kind":"extent","node":tri});
|
||||
let id = run(&mut s, "dimension.create", json!({"source":source,"orientation":orientation,"offset":-110}))["id"].as_u64().unwrap();
|
||||
let ids = if with_dimension { vec![tri, id] } else { vec![tri] };
|
||||
run(&mut s, "select.set", json!({"ids":ids}));
|
||||
run(&mut s, "object.scale", json!({"sx":100,"sy":150,"origin":[x + 50.0, 200]}));
|
||||
let line = recipe(&s, id).line_ends().0.y;
|
||||
assert!((line - 50.0).abs() < 1e-6, "{orientation}: line at y = {line}");
|
||||
}
|
||||
// Reversing the path's direction draws the same outline: the line stays above it.
|
||||
let rect = run(&mut s, "shape.rectangle", json!({"x":100,"y":400,"width":100,"height":60}))["id"].as_u64().unwrap();
|
||||
let id = run(&mut s, "dimension.create", json!({"source":{"kind":"extent","node":rect},"orientation":"horizontal","offset":-30}))["id"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
run(&mut s, "path.reverse", json!({"ids":[rect]}));
|
||||
let line = recipe(&s, id).line_ends().0.y;
|
||||
assert!((line - 370.0).abs() < 1e-6, "line at y = {line}");
|
||||
// So does a reflection onto itself whose coordinates do not come out exactly, while a
|
||||
// reflection that moves the art puts the line on the reflected side.
|
||||
let rect = run(&mut s, "shape.rectangle", json!({"x":100,"y":500.2,"width":100,"height":60}))["id"].as_u64().unwrap();
|
||||
let id = run(&mut s, "dimension.create", json!({"source":{"kind":"extent","node":rect},"orientation":"horizontal","offset":-30}))["id"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
run(&mut s, "select.set", json!({"ids":[rect]}));
|
||||
run(&mut s, "object.reflect", json!({"axis":"horizontal","origin":[0,530.2]}));
|
||||
let line = recipe(&s, id).line_ends().0.y;
|
||||
assert!((line - 470.2).abs() < 1e-6, "line at y = {line}");
|
||||
let tri = run(&mut s, "path.create", json!({"d":"M100 700 L150 620 L200 700 Z","closed":true}))["id"].as_u64().unwrap();
|
||||
let id = run(&mut s, "dimension.create", json!({"source":{"kind":"extent","node":tri},"orientation":"horizontal","offset":-110}))["id"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
run(&mut s, "select.set", json!({"ids":[tri]}));
|
||||
run(&mut s, "object.reflect", json!({"axis":"horizontal","origin":[0,700]}));
|
||||
let line = recipe(&s, id).line_ends().0.y;
|
||||
assert!((line - 810.0).abs() < 1e-6, "line at y = {line}");
|
||||
|
||||
// Made aligned, the line runs from the leftmost to the rightmost point, with every corner of
|
||||
// the rectangle on one side of it and 40 pt from the nearest, as it was 40 pt above the top.
|
||||
let rect = run(&mut s, "shape.rectangle", json!({"x":300,"y":100,"width":100,"height":60}))["id"].as_u64().unwrap();
|
||||
let id = run(&mut s, "dimension.create", json!({"source":{"kind":"extent","node":rect},"orientation":"horizontal","offset":-40}))["id"]
|
||||
.as_u64()
|
||||
.unwrap();
|
||||
run(&mut s, "dimension.update", json!({"ids":[id],"orientation":"aligned"}));
|
||||
let (a, b) = recipe(&s, id).line_ends();
|
||||
let side = |x: f64, y: f64| (b - a).cross(vectorcraft_geom::Point::new(x, y) - a) / (b - a).hypot();
|
||||
let sides = [side(300.0, 100.0), side(400.0, 100.0), side(400.0, 160.0), side(300.0, 160.0)];
|
||||
assert!(sides.iter().all(|v| *v > 1e-6) || sides.iter().all(|v| *v < -1e-6), "{a:?} to {b:?}: {sides:?}");
|
||||
let nearest = sides.iter().map(|v| v.abs()).fold(f64::INFINITY, f64::min);
|
||||
assert!((nearest - 40.0).abs() < 1e-6, "nearest corner {nearest} pt from the line");
|
||||
}
|
||||
|
||||
/// The line of a linked horizontal dimension keeps its gap from the outermost point on its side
|
||||
/// when the art turns, so it stays clear of the art: after a half turn the line is still 50 pt
|
||||
/// above the upper point, which is now the other anchor.
|
||||
|
||||
+194
-10
@@ -1,7 +1,9 @@
|
||||
//! The Dimension tool. Hover a segment (linear), a corner (angular) or a circle or perfect arc
|
||||
//! (radial) and drag outwards: releasing places the linked dimension. Plain clicks pick what to
|
||||
//! measure instead: two points (linear) or two straight lines (angular), then a click places it;
|
||||
//! a click on a circle or arc gives its radius. Escape cancels without leaving any artwork.
|
||||
//! a click on a circle or arc gives its radius. With Alt (Option on macOS) held, a Linear click or
|
||||
//! drag on a path measures the whole path's width or height instead. Escape cancels without
|
||||
//! leaving any artwork.
|
||||
use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey};
|
||||
use serde_json::{Value, json};
|
||||
use std::collections::HashMap;
|
||||
@@ -39,12 +41,26 @@ impl Kind {
|
||||
}
|
||||
}
|
||||
|
||||
/// What the pointer is over.
|
||||
/// What the pointer is over. `Extent` is a path hovered with Alt held: its overall width or height.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
enum Target {
|
||||
Segment(SegmentRef),
|
||||
Corner { first: SegmentRef, second: SegmentRef, at: Point },
|
||||
Radial { source: DimensionSource, center: Point, radius: f64 },
|
||||
Extent { node: NodeId },
|
||||
}
|
||||
|
||||
/// A path and the document its outermost points ([`dimension::extents`]) were read from
|
||||
/// ([`whole_box_source`]), with the points.
|
||||
type WholeBox = ((NodeId, (u64, u64, usize)), Option<[(Point, Point); 2]>);
|
||||
|
||||
/// The document a path's box is read from, with what identifies it: while an interaction is in
|
||||
/// progress, the document as it began; otherwise the document `cx` shows, at its revision.
|
||||
fn whole_box_source<'a>(cx: &ToolContext<'a>, node: NodeId) -> (&'a vectorcraft_doc::Document, (NodeId, (u64, u64, usize))) {
|
||||
match cx.interaction_doc {
|
||||
Some(began) => (began, (node, (cx.revision.0, 0, std::ptr::from_ref(began).addr()))),
|
||||
None => (cx.doc, (node, (cx.revision.0, cx.revision.1, 0))),
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
@@ -106,6 +122,9 @@ pub struct DimensionTool {
|
||||
/// The document's next object id at the dimension's first preview: the id its preview takes
|
||||
/// (`dimension.create` gives the dimension the next id). The preview is not a level.
|
||||
preview_id: u64,
|
||||
/// A path's outermost points, for the path and the document they were read from: a path
|
||||
/// hovered with Alt held, or a dimension of a whole path being placed.
|
||||
whole_box: Option<WholeBox>,
|
||||
}
|
||||
|
||||
/// What a linear dimension between `a` and `b` measures with the pointer at `p` while it is
|
||||
@@ -140,6 +159,37 @@ fn orientation_at(a: Point, b: Point, p: Point) -> Orientation {
|
||||
.map_or(Orientation::Aligned, |(_, orientation)| orientation)
|
||||
}
|
||||
|
||||
/// The box through a path's outermost points ([`dimension::extents`]): left, top, right and
|
||||
/// bottom.
|
||||
fn extent_box([(left, right), (top, bottom)]: [(Point, Point); 2]) -> Rect {
|
||||
Rect::new(left.x, top.y, right.x, bottom.y)
|
||||
}
|
||||
|
||||
/// What a dimension of a whole path whose outermost points span `b` ([`extent_box`]) measures
|
||||
/// with the pointer at `p` while it is placed (VectorCraft's own rule): above or below the box,
|
||||
/// the path's width (horizontal); to the left or right of it, its height (vertical); past a
|
||||
/// corner, the side the pointer is farther out on. Inside the box, or as far out on both sides,
|
||||
/// it keeps `current`. A path with no height gives its width, and one with no width its height.
|
||||
fn extent_orientation(b: Option<Rect>, p: Point, current: Orientation) -> Orientation {
|
||||
let current = if current == Orientation::Aligned { Orientation::Horizontal } else { current };
|
||||
let Some(b) = b else { return current };
|
||||
match (b.width() > 1e-9, b.height() > 1e-9) {
|
||||
(true, false) => return Orientation::Horizontal,
|
||||
(false, true) => return Orientation::Vertical,
|
||||
(false, false) => return current,
|
||||
(true, true) => {}
|
||||
}
|
||||
let out_x = (b.x0 - p.x).max(p.x - b.x1).max(0.0);
|
||||
let out_y = (b.y0 - p.y).max(p.y - b.y1).max(0.0);
|
||||
if out_x > out_y {
|
||||
Orientation::Vertical
|
||||
} else if out_y > out_x {
|
||||
Orientation::Horizontal
|
||||
} else {
|
||||
current
|
||||
}
|
||||
}
|
||||
|
||||
/// How near an anchor (screen pixels) a pick snaps to it.
|
||||
const ANCHOR_REACH: f64 = 8.0;
|
||||
|
||||
@@ -747,9 +797,27 @@ impl DimensionTool {
|
||||
};
|
||||
Some(now.or(self.first_pick).unwrap_or(*at))
|
||||
}
|
||||
fn target(&self, cx: &ToolContext, p: Point) -> Option<Target> {
|
||||
/// The outermost points of `node` ([`dimension::extents`]), read again only when the path or
|
||||
/// the document changes. While an interaction is in progress they are read from the document
|
||||
/// as the interaction began, which each preview starts again from (as the levels in
|
||||
/// [`Self::preview`] are), so the previews themselves do not make the tool read the path again.
|
||||
fn whole_box(&mut self, cx: &ToolContext, node: NodeId) -> Option<[(Point, Point); 2]> {
|
||||
let (from, key) = whole_box_source(cx, node);
|
||||
if let Some((kept, ends)) = self.whole_box
|
||||
&& kept == key
|
||||
{
|
||||
return ends;
|
||||
}
|
||||
let ends = dimension::extents(from, node);
|
||||
self.whole_box = Some((key, ends));
|
||||
ends
|
||||
}
|
||||
/// What the pointer at `p` is over. A Linear path hovered with `alt` held, before any point
|
||||
/// is picked, is the whole path.
|
||||
fn target(&self, cx: &ToolContext, p: Point, alt: bool) -> Option<Target> {
|
||||
let edge = pick(cx, p)?;
|
||||
match self.kind {
|
||||
Kind::Linear if alt && self.points.is_empty() => Some(Target::Extent { node: edge.node }),
|
||||
Kind::Linear => Some(Target::Segment(edge)),
|
||||
Kind::Angular => {
|
||||
let (anchor, at) = anchor_near(cx, &edge, p)?;
|
||||
@@ -801,6 +869,12 @@ impl DimensionTool {
|
||||
let mode = if p.distance(*center) >= *radius { DimensionMode::Radius } else { DimensionMode::Diameter };
|
||||
self.recipe(mode, *center, p, Point::ZERO, Some(source.clone()))
|
||||
}
|
||||
Target::Extent { node } => {
|
||||
let mut d =
|
||||
self.recipe(DimensionMode::Linear, Point::ZERO, Point::new(1.0, 0.0), Point::ZERO, Some(DimensionSource::Extent { node: *node }));
|
||||
d.orientation = Orientation::Horizontal;
|
||||
d
|
||||
}
|
||||
};
|
||||
d.offset = 30.0;
|
||||
Some(d)
|
||||
@@ -817,13 +891,19 @@ impl DimensionTool {
|
||||
}
|
||||
fn preview(&mut self, cx: &ToolContext, p: Point) -> Vec<Action> {
|
||||
self.level_guide = None;
|
||||
let whole = match self.pending.as_ref().and_then(|d| d.source.as_ref()) {
|
||||
Some(DimensionSource::Extent { node }) => Some(self.whole_box(cx, *node)),
|
||||
_ => None,
|
||||
};
|
||||
let Some(d) = &mut self.pending else { return vec![] };
|
||||
if matches!(d.mode, DimensionMode::Radius | DimensionMode::Diameter)
|
||||
&& let Some(Target::Radial { center, radius, .. }) = self.press.as_ref().and_then(|(_, t)| t.as_ref())
|
||||
{
|
||||
d.mode = if p.distance(*center) >= *radius { DimensionMode::Radius } else { DimensionMode::Diameter };
|
||||
}
|
||||
if d.mode == DimensionMode::Linear {
|
||||
if let Some(ends) = whole {
|
||||
d.orientation = extent_orientation(ends.map(extent_box), p, d.orientation);
|
||||
} else if d.mode == DimensionMode::Linear {
|
||||
// The points the dimension measures: a dragged segment's ends, read from the art.
|
||||
let ends = match &d.source {
|
||||
Some(DimensionSource::Segment { edge }) => edge.endpoints(cx.doc),
|
||||
@@ -841,7 +921,17 @@ impl DimensionTool {
|
||||
if !matches!(d.mode, DimensionMode::Radius | DimensionMode::Diameter) {
|
||||
d.offset = 0.0;
|
||||
}
|
||||
if d.resolve(cx.doc).is_err() {
|
||||
// A dimension of a whole path takes the outermost points already read for it.
|
||||
let read = match whole {
|
||||
Some(Some(ends)) => {
|
||||
(d.a, d.b) = ends[usize::from(d.orientation == Orientation::Vertical)];
|
||||
d.length = d.measured();
|
||||
d.validate()
|
||||
}
|
||||
Some(None) => Err(String::new()),
|
||||
None => d.resolve(cx.doc),
|
||||
};
|
||||
if read.is_err() {
|
||||
return vec![];
|
||||
}
|
||||
// With Smart Guides on, a linear dimension's line lands on the level of a parallel
|
||||
@@ -906,11 +996,20 @@ impl DimensionTool {
|
||||
self.second = None;
|
||||
self.level_guide = None;
|
||||
self.levels.clear();
|
||||
// Alt may no longer be held: the box shows again only when the next move finds it is.
|
||||
if matches!(self.hover, Some(Target::Extent { .. })) {
|
||||
self.hover = None;
|
||||
}
|
||||
}
|
||||
/// A plain click: picks a point or a line, or measures a circle's radius.
|
||||
/// A plain click: picks a point or a line, or measures a circle's radius. A click on a path
|
||||
/// that Alt made the whole path starts placing its width or height.
|
||||
fn click(&mut self, cx: &ToolContext, p: Point, target: Option<Target>, mods: Mods) -> Vec<Action> {
|
||||
match self.kind {
|
||||
Kind::Linear => {
|
||||
if let Some(target @ Target::Extent { .. }) = target {
|
||||
self.pending = self.dimension_for(&target, p).filter(|d| d.clone().resolve(cx.doc).is_ok());
|
||||
return vec![];
|
||||
}
|
||||
let (mut at, mut reference) = self.snap_linear(cx, p);
|
||||
let mut corner = self.corner;
|
||||
if mods.shift
|
||||
@@ -1018,8 +1117,15 @@ impl Tool for DimensionTool {
|
||||
self.snapped = None;
|
||||
return self.preview(cx, ev.pos);
|
||||
}
|
||||
self.hover = self.target(cx, ev.pos);
|
||||
self.snapped = (self.kind == Kind::Linear && self.lines.is_empty()).then(|| self.snap_linear(cx, ev.pos));
|
||||
self.hover = self.target(cx, ev.pos, ev.mods.alt);
|
||||
let whole = match self.hover {
|
||||
Some(Target::Extent { node }) => {
|
||||
self.whole_box(cx, node);
|
||||
true
|
||||
}
|
||||
_ => false,
|
||||
};
|
||||
self.snapped = (self.kind == Kind::Linear && self.lines.is_empty() && !whole).then(|| self.snap_linear(cx, ev.pos));
|
||||
if self.snapped.is_none() {
|
||||
self.snap.clear();
|
||||
}
|
||||
@@ -1038,7 +1144,7 @@ impl Tool for DimensionTool {
|
||||
&& (anchor_under(cx, ev.pos).is_some()
|
||||
|| preview_corner(cx, ev.pos, &mut self.preview_boxes).is_some()
|
||||
|| on_dimensions(cx, ev.pos).is_some_and(|(_, end)| end));
|
||||
self.press = Some((ev.pos, self.target(cx, ev.pos)));
|
||||
self.press = Some((ev.pos, self.target(cx, ev.pos, ev.mods.alt)));
|
||||
vec![]
|
||||
}
|
||||
PointerKind::Drag => {
|
||||
@@ -1122,7 +1228,7 @@ impl Tool for DimensionTool {
|
||||
if cx.measurement_labels
|
||||
&& let Ok(text) = self.style.label(a.distance(b), false)
|
||||
{
|
||||
out.push(Overlay::Measure { p: self.at + Vec2::new(12.0, 12.0), text });
|
||||
out.push(Overlay::Measure { p: self.at + Vec2::new(cx.tol(12.0), cx.tol(12.0)), text });
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1138,6 +1244,29 @@ impl Tool for DimensionTool {
|
||||
out.push(Overlay::Line { a: *center, b: *center + toward / toward.hypot() * *radius, color, dashed: true });
|
||||
}
|
||||
}
|
||||
Some(Target::Extent { node }) => {
|
||||
// The box through the path's outermost points: a Smart Guide, or with Smart
|
||||
// Guides off a line in the tool's own color.
|
||||
// Read again when the path changed since the pointer last moved.
|
||||
let (from, at) = whole_box_source(cx, *node);
|
||||
let b = match self.whole_box {
|
||||
Some((key, ends)) if key == at => ends,
|
||||
_ => dimension::extents(from, *node),
|
||||
}
|
||||
.map(extent_box);
|
||||
if let Some(b) = b {
|
||||
let line = if cx.smart_guides { cx.smart_guide_color } else { color };
|
||||
let corners = [Point::new(b.x0, b.y0), Point::new(b.x1, b.y0), Point::new(b.x1, b.y1), Point::new(b.x0, b.y1)];
|
||||
for (i, a) in corners.iter().enumerate() {
|
||||
out.push(Overlay::Line { a: *a, b: corners[(i + 1) % 4], color: line, dashed: false });
|
||||
}
|
||||
if cx.measurement_labels
|
||||
&& let (Ok(w), Ok(h)) = (self.style.label(b.width(), false), self.style.label(b.height(), false))
|
||||
{
|
||||
out.push(Overlay::Measure { p: self.at + Vec2::new(cx.tol(12.0), cx.tol(12.0)), text: format!("W: {w}\nH: {h}") });
|
||||
}
|
||||
}
|
||||
}
|
||||
None => {}
|
||||
}
|
||||
}
|
||||
@@ -2201,6 +2330,61 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// With Alt held, hovering a path shows the box through its outermost points as a Smart Guide,
|
||||
/// and a click starts placing a dimension of the whole path: above or below it, its width;
|
||||
/// beside it, its height. A drag places it on release. Without Alt the same click picks a point.
|
||||
#[test]
|
||||
fn an_alt_click_or_drag_on_a_path_places_its_overall_width_or_height() {
|
||||
let (d, id) = doc_with_rect();
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let c = cx(&d, &s, &p);
|
||||
let alt = Mods { alt: true, ..Mods::default() };
|
||||
let held = |kind, x: f64, y: f64| PointerEvent::new(kind, x, y).with_mods(alt);
|
||||
let preview = |acts: Vec<Action>| match acts.last() {
|
||||
Some(Action::Preview(_, params)) => params.clone(),
|
||||
other => panic!("{other:?}"),
|
||||
};
|
||||
let mut t = DimensionTool::default();
|
||||
t.pointer(&c, &held(PointerKind::Move, 150.0, 100.0));
|
||||
assert_eq!(t.hover, Some(Target::Extent { node: id }));
|
||||
assert!(t.overlays(&c).iter().any(|o| matches!(o, Overlay::Line { color, .. } if *color == c.smart_guide_color)));
|
||||
// With Smart Guides off the box is not a Smart Guide, and at a high zoom the size stays by
|
||||
// the pointer.
|
||||
let mut zoomed = cx(&d, &s, &p);
|
||||
(zoomed.smart_guides, zoomed.measurement_labels, zoomed.zoom) = (false, true, 16.0);
|
||||
let o = t.overlays(&zoomed);
|
||||
assert!(
|
||||
o.iter().any(|o| matches!(o, Overlay::Line { .. }))
|
||||
&& !o.iter().any(|o| matches!(o, Overlay::Line { color, .. } if *color == c.smart_guide_color))
|
||||
);
|
||||
let near = |o: &Overlay| matches!(o, Overlay::Measure { p, text } if p.distance(Point::new(150.0, 100.0)) < zoomed.tol(20.0) && text.starts_with("W: "));
|
||||
assert!(o.iter().any(near), "{o:?}");
|
||||
t.pointer(&c, &held(PointerKind::Down, 150.0, 100.0));
|
||||
t.pointer(&c, &held(PointerKind::Up, 150.0, 100.0));
|
||||
assert!(t.pending.is_some() && t.points.is_empty());
|
||||
let above = preview(t.pointer(&c, &PointerEvent::new(PointerKind::Move, 150.0, 60.0)));
|
||||
assert_eq!(above["source"], json!({"kind":"extent","node":id}));
|
||||
assert_eq!(above["orientation"], json!("horizontal"));
|
||||
let beside = preview(t.pointer(&c, &PointerEvent::new(PointerKind::Move, 260.0, 150.0)));
|
||||
assert_eq!(beside["orientation"], json!("vertical"));
|
||||
t.pointer(&c, &PointerEvent::new(PointerKind::Down, 260.0, 150.0));
|
||||
let placed = t.pointer(&c, &PointerEvent::new(PointerKind::Up, 260.0, 150.0));
|
||||
assert!(matches!(placed.last(), Some(Action::Commit)), "{placed:?}");
|
||||
// Placed with Alt let go: the box does not show again.
|
||||
assert!(!t.overlays(&c).iter().any(|o| matches!(o, Overlay::Line { color, .. } if *color == c.smart_guide_color)));
|
||||
|
||||
let mut t = DimensionTool::default();
|
||||
t.pointer(&c, &held(PointerKind::Down, 200.0, 150.0));
|
||||
let dragged = preview(t.pointer(&c, &held(PointerKind::Drag, 150.0, 240.0)));
|
||||
assert_eq!((dragged["source"]["kind"].clone(), dragged["orientation"].clone()), (json!("extent"), json!("horizontal")));
|
||||
assert!(matches!(t.pointer(&c, &held(PointerKind::Up, 150.0, 240.0)).last(), Some(Action::Commit)));
|
||||
|
||||
let mut t = DimensionTool::default();
|
||||
t.pointer(&c, &PointerEvent::new(PointerKind::Down, 150.0, 100.0));
|
||||
t.pointer(&c, &PointerEvent::new(PointerKind::Up, 150.0, 100.0));
|
||||
assert!(t.pending.is_none() && t.points.len() == 1, "a plain click picks a point");
|
||||
}
|
||||
|
||||
/// A point that Smart Guides leave where the pointer already is (the pointer right in line
|
||||
/// with a target) stays on the guide the overlays show. It does not move to the nearest point
|
||||
/// of a segment within the pick's reach. Off the guides, a point near a segment still lands
|
||||
|
||||
@@ -8,6 +8,8 @@ fn hint_for(tool: &str) -> Option<&'static [(&'static str, bool)]> {
|
||||
(" out from a highlighted edge to place its dimension | ", false),
|
||||
("Click", true),
|
||||
(" two points, then move and click to place an aligned, horizontal or vertical dimension | ", false),
|
||||
("Alt+Click", true),
|
||||
(" a path, then move and click to place its overall width or height | ", false),
|
||||
("Esc", true),
|
||||
(" cancels | Double-click the tool for options", false),
|
||||
],
|
||||
|
||||
+25
-4
@@ -82,6 +82,22 @@ The **Dimension Tool** is in the Modify section of the toolbar. Its strip offers
|
||||
VectorCraft's own rule. With
|
||||
Alignment Guides on, a guide runs along the level across both lines while the dimension is
|
||||
placed.
|
||||
The
|
||||
[linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html)
|
||||
describes plotting an object's overall horizontal and vertical dimensions by holding Alt
|
||||
(Option on macOS) over its path. With Alt held, hovering a path shows a box through the path's
|
||||
outermost points, as a Smart Guide when Smart Guides are on and in the tool's own color when
|
||||
they are off, with its width and height beside the pointer when Measurement Labels are on.
|
||||
Clicking the path, then moving and clicking, places a dimension of the whole path; dragging out
|
||||
from the path places it on release. The rest is VectorCraft's own rule. With
|
||||
the pointer above or below the box the dimension measures the path's width, between its
|
||||
leftmost and rightmost points; to the left or right of the box it measures the height, between
|
||||
the topmost and bottommost points; past a corner, the side the pointer is farther out on
|
||||
decides. The points are read from the segments the path draws, curves included, and an anchor
|
||||
that starts no segment is left out. They are read again whenever the path changes, so a turned
|
||||
path shows its new overall width or height rather than that of its bounding box before the
|
||||
turn. The line keeps its distance from the whole path when the path changes or the dimension
|
||||
changes orientation. Alt has this effect only before the first point is clicked.
|
||||
- **Angular:** hover a corner where two straight segments meet and drag outwards. Or click two
|
||||
straight lines that meet (or would, extended), then click to place.
|
||||
- **Radial:** hover a circle, or a segment that is a perfect arc, and drag: outwards gives its
|
||||
@@ -112,7 +128,9 @@ Measurements follow the art they measure through moves, scaling and anchor and h
|
||||
undo and redo included. When the art is reflected, the line of a linked linear dimension goes to
|
||||
the reflected side, as far past the outermost point as before. This does not happen for art whose
|
||||
anchors and handles all lie on one line, such as a straight line, which a half turn puts in the
|
||||
same place as a reflection. An unlinked aligned dimension that is reflected, or scaled by a
|
||||
same place as a reflection, nor for a dimension of a whole path whose box through the path's
|
||||
outermost points stays where it was, as after Reverse Path Direction or a reflection across the
|
||||
middle of that box. An unlinked aligned dimension that is reflected, or scaled by a
|
||||
negative factor, has its line on the reflected side of its points. Deleting the art, changing its number of anchors or whether it is
|
||||
closed, turning an angle's arm into a curve, or making a measured circle or arc no longer circular
|
||||
leaves its dimensions where they were, no longer linked, in the same undo step, rather than
|
||||
@@ -150,9 +168,12 @@ another document.
|
||||
|
||||
## Commands
|
||||
|
||||
- `dimension.create`: two points, or a source (segment, angle, circle, arc, points), the mode,
|
||||
the orientation of a linear dimension (`aligned`, the default, `horizontal` or `vertical`),
|
||||
offset and style; returns the group id and label. `offset` is the distance of the dimension
|
||||
- `dimension.create`: two points, or a source (segment, angle, circle, arc, points, extent), the
|
||||
mode, the orientation of a linear dimension (`aligned`, the default, `horizontal` or
|
||||
`vertical`), offset and style; returns the group id and label. `{"kind":"extent","node":<id>}`
|
||||
measures a whole path, linear only: between its leftmost and rightmost points when horizontal
|
||||
or aligned, and its topmost and bottommost points when vertical. A version without the extent
|
||||
source does not open a file that holds one. `offset` is the distance of the dimension
|
||||
line from the first point: along the left normal of a → b for an aligned dimension, downward
|
||||
for a horizontal one and leftward for a vertical one. A negative offset goes the other way.
|
||||
- `dimension.update`: restyle or move existing dimensions, or change the orientation of linear
|
||||
|
||||
@@ -684,6 +684,7 @@ since 2026-10-01.
|
||||
**Drawing tools, Ellipse tool circle from its center sized to touch a path:** By VectorCraft's own rule, with Smart Guides and Snap to Tangent on, a circle drawn from its center (Alt and Shift) snaps its radius so that the circle touches a nearby path whenever the radius comes within the snapping tolerance of that size. The touch point is where the line from the center meets a straight segment or a curve square, inside a segment or at an anchor where the path runs smoothly, also where a curve's handle lies on that anchor. A circle can touch another circle from outside or touch it from inside, and a center inside a closed path gives a circle that touches the path from within. A corner or an open path's end is not offered, nor a curve around the same center. The touch point shows the "tangent" label and the line from the center as guides; the radius is measured along the Constrain Angle's axes, as the drawn box is, and Space moves the circle at the size it snapped to, which it keeps when Space is let go. The snap does not apply to an ellipse (no Shift). When an anchor, center or crossing is within the snapping tolerance of the pointer, or the dragged corner snapped onto one, the circle is not resized to touch a path. Snap to Grid and pixel snapping place the drawn point instead, also when turned on during the drag, and turning Snap to Tangent off during the drag stops the snap. A press with a small jitter is still a click rather than a drag. At most 256 segments near that radius are measured per pointer move, the ones nearest the pointer. `a_circle_from_its_center_snaps_its_radius_to_touch_a_line`, `a_circle_from_its_center_snaps_to_touch_another_circle_from_outside_and_inside`, `a_circle_from_its_center_snaps_to_touch_a_curve`, `a_circle_from_its_center_keeps_its_radius_without_the_snap_or_a_smooth_touch`, `a_circle_from_its_center_prefers_an_anchor_and_measures_the_segments_nearest_the_pointer`, `a_circle_snapped_to_touch_keeps_to_the_constrain_angle`, `a_circle_from_its_center_does_not_snap_to_touch_with_the_grid_or_pixels`, `a_jittered_alt_shift_press_beside_a_path_is_a_click`, `a_circle_from_its_center_prefers_an_anchor_or_a_crossing_at_the_pointer` and `a_circle_from_its_center_touches_a_path_at_an_anchor_with_retracted_handles` cover it.
|
||||
**Drawing tools, selected Dimension extension-line style (#7078):** Properties › Dimension exposes the selected editable dimension's existing extension-line color and weight. Both extension lines share that style, independently of the main dimension line and label. Apply to All keeps its full-style behavior for editable dimensions, leaving a protected dimension unchanged; Set as Default keeps the whole style for a new dimension created without explicit options, without changing existing dimensions. The dimension remains editable. Four cases in `crates/ui-egui/tests/dimension_extension_properties.rs` verify actual Properties input, both canvas extension lines, independent main-line/label styling, full-style Apply to All, locked and unselected controls, defaults/new dimensions, Undo/Redo, and native save/reopen with further editing. Existing document-color conversion is unchanged. The measured geometry and existing snapping behavior are unchanged; no whole-Dimension completion or score/hour change is claimed.
|
||||
**Drawing tools, Dimension tool horizontal and vertical linear dimensions:** A linear dimension between two clicked points or dragged out from a segment is aligned, horizontal or vertical, chosen by where the pointer moves while it is placed, and a click again by the second point gives aligned; `dimension.create` and `dimension.update` take `orientation`, and the dimension stays linked to the anchors it measures, keeps its orientation when it or the art turns, with a line that lay outside the points kept outside them; an unlinked horizontal or vertical dimension that is reflected has its line on the reflected side. `the_pointer_chooses_aligned_horizontal_or_vertical`, `two_points_measure_horizontally_vertically_or_aligned`, `clicking_again_by_the_second_point_places_an_aligned_dimension`, `a_segment_drag_measures_horizontally_vertically_or_aligned`, `points_on_a_vertical_line_measure_aligned`, `horizontal_and_vertical_dimensions_draw_lines_along_their_axis`, `turned_horizontal_dimensions_stay_horizontal`, `a_linked_horizontal_dimension_keeps_its_gap_from_turned_art`, `a_linked_horizontal_dimension_below_or_between_its_points_follows_turned_art`, `a_reflected_horizontal_dimension_keeps_its_line_on_the_reflected_side`, `a_dimension_without_an_orientation_reads_as_aligned`, `dimension_orientation_is_checked` and `a_turned_dimension_keeps_its_line_on_its_side` cover it.
|
||||
**Drawing tools, Dimension tool overall width and height of a path (#5590):** With Alt (Option on macOS) held, hovering a path shows a box through its outermost points (a Smart Guide when Smart Guides are on), and a click then a placing click, or a drag out from the path, places a linear dimension of the whole path, as the [linear dimensions help](https://helpx.adobe.com/illustrator/desktop/measure-and-align/plot-and-measure/plot-linear-dimensions-of-objects.html) describes; by VectorCraft's own rule the pointer above or below the path gives its width and beside it its height. `dimension.create` takes the `extent` source, whose points are the outermost points of the path's curves, read again after every edit, so a turned path shows its new overall size, and the line keeps its distance from the whole path. `an_alt_click_or_drag_on_a_path_places_its_overall_width_or_height`, `a_dimension_of_a_whole_path_measures_its_overall_width_and_height` and `a_dimension_of_a_whole_path_stays_clear_of_the_path_it_draws` cover it.
|
||||
**Drawing tools, Dimension tool points that are not anchors follow the art:** A clicked point on a segment stays at its place along the segment, also when the segment curves, and a point off the art is linked to anchors (or, when the anchors lie on one line, anchors and handles) of the path, so both ends of the dimension follow when the art is moved, scaled, turned or reflected, also when the point was placed by a Smart Guide and when the dimension is saved and opened again; a linked linear dimension of reflected art (other than art on one line) has its line on the reflected side; deleting the art, changing its anchor count or whether it is closed, turning an angle's arm into a curve, or making a measured circle or arc no longer circular leaves the dimension where it was, no longer linked, instead of removing it. `a_dimension_to_a_point_on_a_segment_follows_the_art_at_both_ends`, `a_dimension_to_a_point_off_the_art_moves_with_the_art`, `a_dimension_whose_art_changes_its_anchors_stays_where_it_was`, `a_dimension_whose_art_is_opened_stays_where_it_was`, `angle_and_arc_dimensions_whose_art_no_longer_fits_stay_where_they_were`, `a_dimension_that_cannot_be_drawn_again_keeps_its_art`, `a_linked_dimension_of_reflected_art_has_its_line_on_the_reflected_side`, `a_dimension_to_a_point_off_a_line_follows_the_line`, `a_point_off_an_arch_is_reflected_with_the_arch`, `a_point_beside_an_almost_straight_curve_follows_it`, `a_point_off_a_loop_with_its_anchors_in_one_place_follows_it`, `a_point_beside_a_reflected_line_moves_as_a_half_turn_would`, `a_point_on_a_segment_stays_on_it_when_the_segment_curves`, `a_linked_dimension_of_a_reflected_curve_has_its_line_on_the_reflected_side`, `a_dimension_of_art_reflected_across_its_points_changes_sides`, `a_dimension_between_paths_reflected_each_in_its_own_way_keeps_its_offset`, `free_points_survive_a_native_file`, `dimension_free_points_are_checked`, `points_off_anchors_are_held_against_the_path` and `a_point_smart_guides_place_is_held_against_the_path` cover it.
|
||||
**Drawing tools, Dimension tool points on a Smart Guide stay on the guide:** By VectorCraft's own rule, a clicked point that lies on a Smart Guide already, such as one in line with an object's center, stays where the pointer is when no anchor is within 8 pixels and no segment is within the Smart Guides snapping tolerance, instead of moving onto a segment farther than that tolerance and within 8 pixels; with Snap to Grid or Snap to Pixel on, a point stays on the grid or the whole pixel those options give. `a_point_on_a_guide_stays_on_the_guide` covers it.
|
||||
**Drawing tools, Dimension tool second point without construction guides through a first point off the anchors:** By VectorCraft's own rule, with Smart Guides on, the second Linear point does not snap to the construction guides through a first point that is not on an anchor, so a click beside a segment straight below such a first point lands on the segment; after a first point picked on an anchor, the construction guides through it still apply. The second point still snaps to anchors, centers and alignment lines, and with Snap to Perpendicular or Snap to Tangent on, it lands where the line from the first point meets a segment square or grazes a curve. `a_point_on_a_guide_stays_on_the_guide`, `the_second_point_after_an_anchor_lands_on_construction_guides`, `the_second_point_lands_square_to_a_segment_or_grazing_a_curve` and `linear_picks_show_and_snap_to_smart_guides` cover it.
|
||||
|
||||
Reference in new issue
Block a user