mirror of
https://github.com/storytold/vectorcraft.git
synced 2026-11-19 16:55:55 +00:00
Merge main into feat/width-point-edit-all-selected
This commit is contained in:
+575
-20
@@ -4,11 +4,12 @@
|
||||
//! a click on a circle or arc gives its radius. 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;
|
||||
use vectorcraft_doc::{
|
||||
Node, NodeId,
|
||||
Node, NodeId, NodeKind,
|
||||
dimension::{self, Dimension, DimensionMode, DimensionOptions, DimensionSource, FreePoint, Orientation, PointRef, SegmentRef},
|
||||
};
|
||||
use vectorcraft_geom::{BezPath, Point, Vec2};
|
||||
use vectorcraft_geom::{BezPath, Point, Rect, Vec2};
|
||||
|
||||
/// The three kinds of dimension the tool draws.
|
||||
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
|
||||
@@ -68,14 +69,22 @@ pub struct DimensionTool {
|
||||
/// Where the next Linear pick lands, as last worked out for the pointer (for the overlays).
|
||||
snapped: Option<(Point, Option<PointRef>)>,
|
||||
/// Whether the last Linear pick worked out landed on the end of a line of a dimension already
|
||||
/// drawn (shown as an anchor).
|
||||
/// drawn, or on a corner of a path's preview bounds (shown as an anchor).
|
||||
on_end: bool,
|
||||
/// The path that holds the last Linear pick worked out, when it landed on a corner of that
|
||||
/// path's preview bounds.
|
||||
corner: Option<NodeId>,
|
||||
/// The path that holds the first Linear point, when it was picked on a corner of that path's
|
||||
/// preview bounds.
|
||||
first_corner: Option<NodeId>,
|
||||
/// Whether the press under way began on an anchor a Linear click picks.
|
||||
press_on_anchor: bool,
|
||||
/// The second point clicked for the Linear dimension being placed, and where the pointer was
|
||||
/// for that click (a snap or Shift can move the point away from it): placed with the pointer
|
||||
/// still at either, it is aligned.
|
||||
second: Option<(Point, Point)>,
|
||||
/// The preview bounds the Linear picks measured, for the document's revision.
|
||||
preview_boxes: PreviewBoxes,
|
||||
/// While a Linear dimension is placed with its line on the level of another dimension's line:
|
||||
/// the ends of that other line. A Smart Guide runs along the level across both lines.
|
||||
level_guide: Option<(Point, Point)>,
|
||||
@@ -176,9 +185,14 @@ fn anchor_near(cx: &ToolContext, edge: &SegmentRef, p: Point) -> Option<(usize,
|
||||
/// The anchor nearest `p` within reach, on any editable path (the topmost on a tie), as a link to
|
||||
/// its path. Bounded work, and dimension artwork is skipped, as in [`pick`].
|
||||
fn anchor_under(cx: &ToolContext, p: Point) -> Option<(Point, PointRef)> {
|
||||
anchor_under_where(cx, p, |_| true)
|
||||
}
|
||||
|
||||
/// [`anchor_under`] outside the objects `keep` turns down, and outside everything in them.
|
||||
fn anchor_under_where(cx: &ToolContext, p: Point, keep: impl Fn(NodeId) -> bool) -> Option<(Point, PointRef)> {
|
||||
type Best = Option<(f64, Point, PointRef)>;
|
||||
fn visit(n: &Node, p: Point, reach: f64, budget: &mut usize, best: &mut Best) {
|
||||
if *budget == 0 || !n.visible || n.locked || n.extras().dimension.is_some() {
|
||||
fn visit(n: &Node, p: Point, reach: f64, keep: &dyn Fn(NodeId) -> bool, budget: &mut usize, best: &mut Best) {
|
||||
if *budget == 0 || !n.visible || n.locked || n.extras().dimension.is_some() || !keep(n.id) {
|
||||
return;
|
||||
}
|
||||
if let Some(path) = n.path_data() {
|
||||
@@ -197,17 +211,178 @@ fn anchor_under(cx: &ToolContext, p: Point) -> Option<(Point, PointRef)> {
|
||||
}
|
||||
if let Some(ch) = n.children() {
|
||||
for c in ch.iter().rev() {
|
||||
visit(c, p, reach, budget, best);
|
||||
visit(c, p, reach, keep, budget, best);
|
||||
}
|
||||
}
|
||||
}
|
||||
let (reach, mut budget, mut best) = (cx.tol(ANCHOR_REACH), 20_000usize, None);
|
||||
for n in cx.doc.layers.iter().rev() {
|
||||
visit(n, p, reach, &mut budget, &mut best);
|
||||
visit(n, p, reach, &keep, &mut budget, &mut best);
|
||||
}
|
||||
best.map(|(_, at, r)| (at, r))
|
||||
}
|
||||
|
||||
/// The geometric bounds of the paths [`preview_corner`] looked at, and the preview bounds of
|
||||
/// those it measured, kept while the document is unchanged, so that the pointer moving over the
|
||||
/// art measures each path once.
|
||||
#[derive(Default)]
|
||||
struct PreviewBoxes {
|
||||
revision: Option<(u64, u64)>,
|
||||
geometric: HashMap<NodeId, Option<Rect>>,
|
||||
preview: HashMap<NodeId, Option<Rect>>,
|
||||
/// Whether a point at each corner (by object and corner number) can be held against its path.
|
||||
holdable: HashMap<(NodeId, usize), bool>,
|
||||
}
|
||||
|
||||
/// A corner of an object's preview bounds that a Linear pick can land on.
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
struct PreviewCorner {
|
||||
at: Point,
|
||||
/// The path the point is held against.
|
||||
holder: NodeId,
|
||||
/// The same corner of the object's geometric bounds: an anchor of `holder` there is the
|
||||
/// anchor the corner stands in for.
|
||||
stands_for: Point,
|
||||
}
|
||||
|
||||
/// With Use Preview Bounds on, the corner of a path's or compound path's preview bounds (its
|
||||
/// strokes and effects included) nearest `p` within reach, on any editable one whose preview
|
||||
/// bounds differ from its geometric bounds. In a compound path, the member whose own box reaches
|
||||
/// nearest to the corner holds it. The work is bounded, and dimension artwork is skipped, as in
|
||||
/// [`pick`]. `cache` keeps the bounds measured for the document's revision.
|
||||
fn preview_corner(cx: &ToolContext, p: Point, cache: &mut PreviewBoxes) -> Option<PreviewCorner> {
|
||||
struct Walk<'a, 'c> {
|
||||
symbols: Option<vectorcraft_doc::SymbolBoxes<'a>>,
|
||||
doc: &'a vectorcraft_doc::Document,
|
||||
cache: &'c mut PreviewBoxes,
|
||||
p: Point,
|
||||
reach: f64,
|
||||
budget: usize,
|
||||
best: Option<(f64, PreviewCorner)>,
|
||||
}
|
||||
fn visit(n: &Node, w: &mut Walk) {
|
||||
if w.budget == 0 || !n.visible || n.locked || n.extras().dimension.is_some() {
|
||||
return;
|
||||
}
|
||||
w.budget -= 1;
|
||||
// Only effects, on the object or on one of its fills or strokes, paint further out than
|
||||
// its strokes reach.
|
||||
let effects = !n.appearance.effects.is_empty() || n.appearance.items.iter().any(|i| !i.effects().is_empty());
|
||||
let reach = n.appearance.outset() + w.reach;
|
||||
let corners = |r: Rect| [Point::new(r.x0, r.y0), Point::new(r.x1, r.y0), Point::new(r.x1, r.y1), Point::new(r.x0, r.y1)];
|
||||
// A path is its own member; a compound path's members are its paths.
|
||||
let compound = match &n.kind {
|
||||
NodeKind::Compound { children, .. } => Some(children.as_slice()),
|
||||
_ => None,
|
||||
};
|
||||
let members =
|
||||
|| compound.into_iter().flatten().map(|c| c.as_ref()).chain(compound.is_none().then_some(n)).filter(|m| m.path_data().is_some());
|
||||
// A path made into a guide draws as a guide, without its strokes or effects. The pointer
|
||||
// test includes the right and bottom edges, as the distance test below does.
|
||||
let within = |r: Rect| (r.x0..=r.x1).contains(&w.p.x) && (r.y0..=r.y1).contains(&w.p.y);
|
||||
if !n.is_guide()
|
||||
&& members().next().is_some()
|
||||
&& let Some(geometric) = *w.cache.geometric.entry(n.id).or_insert_with(|| n.geometric_bounds())
|
||||
&& (effects || within(geometric.inflate(reach, reach)))
|
||||
{
|
||||
let doc = w.doc;
|
||||
let measured = match w.cache.preview.get(&n.id) {
|
||||
Some(r) => *r,
|
||||
None => {
|
||||
let symbols = w.symbols.get_or_insert_with(|| doc.symbol_boxes());
|
||||
let r = vectorcraft_effects::preview::visual_bounds(symbols, n);
|
||||
w.cache.preview.insert(n.id, r);
|
||||
r
|
||||
}
|
||||
};
|
||||
if let Some(r) = measured
|
||||
&& r != geometric
|
||||
{
|
||||
for (k, q) in corners(r).into_iter().enumerate() {
|
||||
let d = q.distance(w.p);
|
||||
if d > w.reach || w.best.is_some_and(|(nearest, ..)| d >= nearest) {
|
||||
continue;
|
||||
}
|
||||
// The path whose own box reaches furthest towards the corner holds it: in a
|
||||
// compound path, the member that puts that corner where it is. A hidden or
|
||||
// locked member gives no corner.
|
||||
let mut holder: Option<(f64, NodeId, bool)> = None;
|
||||
for m in members() {
|
||||
let Some(b) = *w.cache.geometric.entry(m.id).or_insert_with(|| m.geometric_bounds()) else { continue };
|
||||
let gap = corners(b).get(k).map_or(f64::INFINITY, |c| c.distance(q));
|
||||
let editable = m.visible && !m.locked;
|
||||
if holder.is_none_or(|(near, _, was)| gap < near || (gap == near && editable && !was)) {
|
||||
holder = Some((gap, m.id, editable));
|
||||
}
|
||||
}
|
||||
let holder = holder.filter(|(.., editable)| *editable).map(|(gap, id, _)| (gap, id));
|
||||
// A path that cannot hold a point at the corner (a stroked dot, whose anchors
|
||||
// all coincide) gives no corner.
|
||||
let holdable = |id: NodeId, cache: &mut PreviewBoxes| {
|
||||
*cache.holdable.entry((n.id, k)).or_insert_with(|| FreePoint::on(doc, id, q).is_some())
|
||||
};
|
||||
let holder = holder.filter(|(_, id)| holdable(*id, w.cache));
|
||||
if let Some(((_, holder), stands_for)) = holder.zip(corners(geometric).get(k).copied()) {
|
||||
w.best = Some((d, PreviewCorner { at: q, holder, stands_for }));
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// A compound path draws its members with its own appearance: they give no corners of
|
||||
// their own.
|
||||
if compound.is_none()
|
||||
&& let Some(ch) = n.children()
|
||||
{
|
||||
for c in ch.iter().rev() {
|
||||
visit(c, w);
|
||||
}
|
||||
}
|
||||
}
|
||||
// Anchors take a pick whatever the snapping options, and so do the corners standing in for them.
|
||||
if !cx.preview_bounds {
|
||||
return None;
|
||||
}
|
||||
if cache.revision != Some(cx.revision) {
|
||||
*cache = PreviewBoxes { revision: Some(cx.revision), ..Default::default() };
|
||||
}
|
||||
let mut w = Walk { symbols: None, doc: cx.doc, cache, p, reach: cx.tol(ANCHOR_REACH), budget: 20_000, best: None };
|
||||
for n in cx.doc.layers.iter().rev() {
|
||||
visit(n, &mut w);
|
||||
}
|
||||
w.best.map(|(_, corner)| corner)
|
||||
}
|
||||
|
||||
/// The anchor a pick at `p` lands on instead of `corner`, given `anchor`, the nearest anchor
|
||||
/// within reach; `None` when the corner takes it (VectorCraft's own rule). The corner takes the
|
||||
/// pick from the anchors of the path holding it at the same corner of the object's geometric
|
||||
/// bounds, which sit on the stroke's centerline. An anchor right on the corner takes it, and so
|
||||
/// does the nearest other anchor, of this object or of other art, when it is nearer the pointer
|
||||
/// than the corner. The holder's anchors and the other art are searched with a budget each, and
|
||||
/// `anchor` wins a tie, as the topmost.
|
||||
fn anchor_over_corner(cx: &ToolContext, p: Point, corner: &PreviewCorner, anchor: Option<(Point, PointRef)>) -> Option<(Point, PointRef)> {
|
||||
if anchor.as_ref().is_some_and(|(at, _)| at.distance(corner.at) <= 1e-9) {
|
||||
return anchor;
|
||||
}
|
||||
let stands_in = |(at, nearest): &(Point, PointRef)| nearest.node == corner.holder && at.distance(corner.stands_for) <= 1e-9;
|
||||
let first = anchor.filter(|a| !stands_in(a));
|
||||
let reach = cx.tol(ANCHOR_REACH);
|
||||
let own = cx.doc.node(corner.holder).and_then(|n| n.path_data()).and_then(|path| {
|
||||
let anchors = path.subpaths.iter().enumerate().flat_map(|(subpath, sp)| sp.anchors.iter().enumerate().map(move |(i, a)| (subpath, i, a.p)));
|
||||
anchors
|
||||
.take(20_000)
|
||||
.filter(|(.., q)| q.distance(p) <= reach && q.distance(corner.stands_for) > 1e-9)
|
||||
.min_by(|(.., a), (.., b)| a.distance(p).total_cmp(&b.distance(p)))
|
||||
.map(|(subpath, anchor, q)| (q, PointRef { node: corner.holder, subpath, anchor }))
|
||||
});
|
||||
let other = anchor_under_where(cx, p, |id| id != corner.holder);
|
||||
first
|
||||
.into_iter()
|
||||
.chain(other)
|
||||
.chain(own)
|
||||
.filter(|(q, _)| q.distance(p) < corner.at.distance(p) || q.distance(corner.at) <= 1e-9)
|
||||
.min_by(|(a, _), (b, _)| a.distance(p).total_cmp(&b.distance(p)))
|
||||
}
|
||||
|
||||
/// Where a pick at `p` lands on the artwork of the visible, unlocked dimensions already drawn,
|
||||
/// with no link to it: the nearest end of one of their lines (dimension and extension lines)
|
||||
/// within the anchor reach, as an anchor (`true`); else the nearest point of one of those lines
|
||||
@@ -361,10 +536,23 @@ fn nearest_on(cx: &ToolContext, edge: &SegmentRef, p: Point) -> Option<Point> {
|
||||
/// A point on a segment keeps its place along the segment. Any other point is held
|
||||
/// against the anchors of the path under it, or, with no path under it, the path of the other
|
||||
/// point, so that it moves with that path. None when neither point has a path to link to.
|
||||
fn points_source(cx: &ToolContext, (a, ra): (Point, &Option<PointRef>), (b, rb): (Point, &Option<PointRef>)) -> Option<DimensionSource> {
|
||||
let (edge_a, edge_b) = (pick(cx, a), pick(cx, b));
|
||||
let node = |r: &Option<PointRef>, e: &Option<SegmentRef>| r.as_ref().map(|r| r.node).or_else(|| e.as_ref().map(|e| e.node));
|
||||
let (path_a, path_b) = (node(ra, &edge_a), node(rb, &edge_b));
|
||||
/// `held_a` and `held_b` name the path holding a point picked on a corner of that path's
|
||||
/// preview bounds: such a point is held against that path, however far its strokes or effects
|
||||
/// put the corner from the path and whatever other segment lies there.
|
||||
fn points_source(
|
||||
cx: &ToolContext,
|
||||
(a, ra, held_a): (Point, &Option<PointRef>, Option<NodeId>),
|
||||
(b, rb, held_b): (Point, &Option<PointRef>, Option<NodeId>),
|
||||
) -> Option<DimensionSource> {
|
||||
// A path deleted since the pick holds nothing.
|
||||
let holder = |held: Option<NodeId>| held.filter(|node| cx.doc.node(*node).is_some());
|
||||
let (corner_a, corner_b) = (holder(held_a), holder(held_b));
|
||||
let edge = |p: Point, corner: Option<NodeId>| if corner.is_some() { None } else { pick(cx, p) };
|
||||
let (edge_a, edge_b) = (edge(a, corner_a), edge(b, corner_b));
|
||||
let node = |r: &Option<PointRef>, corner: Option<NodeId>, e: &Option<SegmentRef>| {
|
||||
r.as_ref().map(|r| r.node).or(corner).or_else(|| e.as_ref().map(|e| e.node))
|
||||
};
|
||||
let (path_a, path_b) = (node(ra, corner_a, &edge_a), node(rb, corner_b, &edge_b));
|
||||
let free = |p: Point, r: &Option<PointRef>, edge: &Option<SegmentRef>, own: Option<NodeId>, other: Option<NodeId>| {
|
||||
if r.is_some() {
|
||||
return None;
|
||||
@@ -382,7 +570,10 @@ fn points_source(cx: &ToolContext, (a, ra): (Point, &Option<PointRef>), (b, rb):
|
||||
}
|
||||
|
||||
impl DimensionTool {
|
||||
/// Where a Linear pick at `p` lands: on the nearest anchor of any path, within reach (kept as
|
||||
/// Where a Linear pick at `p` lands: with Use Preview Bounds on, on the nearest corner of a
|
||||
/// path's preview bounds within reach, where they differ from its anchors, unless another
|
||||
/// anchor is nearer (held against the path, labeled "anchor"; [`anchor_over_corner`]); else on the
|
||||
/// nearest anchor of any path, within reach (kept as
|
||||
/// a link to its path), labeled "anchor"; else on the nearest end of a line of a dimension
|
||||
/// already drawn, within the same reach (no link), also labeled "anchor"; else where Smart Guides put it (another object's anchor or centre, in
|
||||
/// line with one, or for the second point square to a segment or grazing a curve from the
|
||||
@@ -399,7 +590,18 @@ impl DimensionTool {
|
||||
});
|
||||
let guided = self.snap.hover(cx, p, &[], leave.as_ref());
|
||||
self.on_end = false;
|
||||
if let Some((point, reference)) = anchor_under(cx, p) {
|
||||
self.corner = None;
|
||||
let mut anchor = anchor_under(cx, p);
|
||||
if let Some(corner) = preview_corner(cx, p, &mut self.preview_boxes) {
|
||||
anchor = anchor_over_corner(cx, p, &corner, anchor);
|
||||
if anchor.is_none() {
|
||||
self.on_end = true;
|
||||
self.corner = Some(corner.holder);
|
||||
self.snap.label(corner.at, "anchor");
|
||||
return (corner.at, None);
|
||||
}
|
||||
}
|
||||
if let Some((point, reference)) = anchor {
|
||||
self.snap.label(point, "anchor");
|
||||
return (point, Some(reference));
|
||||
}
|
||||
@@ -555,6 +757,8 @@ impl DimensionTool {
|
||||
self.press = None;
|
||||
self.press_on_anchor = false;
|
||||
self.on_end = false;
|
||||
self.corner = None;
|
||||
self.first_corner = None;
|
||||
self.points.clear();
|
||||
self.lines.clear();
|
||||
self.dragging = false;
|
||||
@@ -570,15 +774,22 @@ impl DimensionTool {
|
||||
match self.kind {
|
||||
Kind::Linear => {
|
||||
let (mut at, mut reference) = self.snap_linear(cx, p);
|
||||
let mut corner = self.corner;
|
||||
if mods.shift
|
||||
&& let Some((last, _)) = self.points.last()
|
||||
{
|
||||
let snapped = at;
|
||||
at = constrained(cx, *last, at);
|
||||
reference = reference.filter(|r| r.position(cx.doc) == Some(at));
|
||||
corner = corner.filter(|_| at.distance(snapped) <= 1e-9);
|
||||
}
|
||||
self.points.push((at, reference));
|
||||
if self.points.len() == 1 {
|
||||
self.first_corner = corner;
|
||||
}
|
||||
if let [(a, ra), (b, rb)] = self.points.as_slice() {
|
||||
let source = points_source(cx, (*a, ra), (*b, rb));
|
||||
let source = points_source(cx, (*a, ra, self.first_corner), (*b, rb, corner));
|
||||
self.first_corner = None;
|
||||
let mut d = self.recipe(DimensionMode::Linear, *a, *b, Point::ZERO, source);
|
||||
if d.resolve(cx.doc).is_ok() {
|
||||
self.second = Some((*b, p));
|
||||
@@ -678,11 +889,14 @@ impl Tool for DimensionTool {
|
||||
self.press = Some((ev.pos, None));
|
||||
return self.preview(cx, ev.pos);
|
||||
}
|
||||
// A Linear press on an anchor, or on the end of a dimension's line, picks it unless
|
||||
// it drags past the anchor's reach: moving a few pixels before the release does not
|
||||
// drag out the dimension of a segment under the pointer.
|
||||
self.press_on_anchor =
|
||||
self.kind == Kind::Linear && (anchor_under(cx, ev.pos).is_some() || on_dimensions(cx, ev.pos).is_some_and(|(_, end)| end));
|
||||
// A Linear press on an anchor, on a corner of preview bounds or on the end of a
|
||||
// dimension's line, picks it unless it drags past the anchor's reach: moving a few
|
||||
// pixels before the release does not drag out the dimension of a segment under the
|
||||
// pointer.
|
||||
self.press_on_anchor = self.kind == Kind::Linear
|
||||
&& (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)));
|
||||
vec![]
|
||||
}
|
||||
@@ -797,7 +1011,7 @@ impl Tool for DimensionTool {
|
||||
let linear_pick = self.kind == Kind::Linear && self.pending.is_none() && self.lines.is_empty();
|
||||
let snapped = self.snapped.clone().filter(|_| linear_pick);
|
||||
if let Some((q, reference)) = &snapped
|
||||
&& (reference.is_some() || q.distance(self.at) > 1e-9)
|
||||
&& (reference.is_some() || self.on_end || q.distance(self.at) > 1e-9)
|
||||
{
|
||||
let on_anchor = reference.is_some() || self.on_end;
|
||||
out.push(Overlay::Anchor { p: *q, color, filled: !on_anchor, size: if on_anchor { 10.0 } else { 6.0 } });
|
||||
@@ -1037,6 +1251,347 @@ mod tests {
|
||||
assert!(at.distance(pending.b) < 1e-9, "{at:?} {:?}", pending.b);
|
||||
}
|
||||
|
||||
/// With Use Preview Bounds on, clicks by the corners of a stroked path land on the corners of
|
||||
/// its preview bounds, held against the path, so the dimension measures the outside of the
|
||||
/// stroke as W and H do. Without a stroke, or with the preference off, the anchors are picked.
|
||||
#[test]
|
||||
fn with_preview_bounds_points_land_on_the_corners_of_the_stroke() {
|
||||
use vectorcraft_doc::dimension::FreePoint;
|
||||
let (d, id) = doc_with_rect();
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let pick = |c: &ToolContext| {
|
||||
let mut t = DimensionTool::default();
|
||||
for (x, y) in [(101.0, 101.0), (199.0, 199.0)] {
|
||||
t.pointer(c, &PointerEvent::new(PointerKind::Move, x, y));
|
||||
t.pointer(c, &PointerEvent::new(PointerKind::Down, x, y));
|
||||
t.pointer(c, &PointerEvent::new(PointerKind::Up, x, y));
|
||||
}
|
||||
t.pending.expect("both points were picked")
|
||||
};
|
||||
let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) };
|
||||
let pending = pick(&c);
|
||||
let near = |a: Point, b: Point| a.distance(b) < 1e-9;
|
||||
assert!(near(pending.a, Point::new(99.5, 99.5)) && near(pending.b, Point::new(200.5, 200.5)), "{:?} {:?}", pending.a, pending.b);
|
||||
let Some(DimensionSource::Points { a: None, b: None, free_a: Some(free_a), free_b: Some(free_b), .. }) = &pending.source else {
|
||||
panic!("{:?}", pending.source)
|
||||
};
|
||||
for (free, at) in [(free_a, pending.a), (free_b, pending.b)] {
|
||||
assert!(matches!(free, FreePoint::Anchors { node, .. } if *node == id), "{free:?}");
|
||||
assert!(free.position(&d).expect("the anchors that hold it exist").distance(at) < 1e-9);
|
||||
}
|
||||
// A line of another path through the corner leaves the point held against the rectangle.
|
||||
let mut crossed = d.clone();
|
||||
let (l, line) = (crossed.layers[0].id, crossed.alloc_id());
|
||||
let path = vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&[Point::new(0.0, 99.5), Point::new(300.0, 99.5)], false));
|
||||
crossed.insert(Some(l), 1, Node::path(line, path, vectorcraft_doc::Appearance::default_art())).expect("the line");
|
||||
let pending = pick(&ToolContext { preview_bounds: true, ..cx(&crossed, &s, &p) });
|
||||
assert!(near(pending.a, Point::new(99.5, 99.5)), "{:?}", pending.a);
|
||||
let Some(DimensionSource::Points { free_a: Some(free_a), .. }) = &pending.source else { panic!("{:?}", pending.source) };
|
||||
assert!(matches!(free_a, FreePoint::Anchors { node, .. } if *node == id), "{free_a:?}");
|
||||
let anchors = |pending: &Dimension| (pending.a, pending.b, pending.source.clone());
|
||||
let anchor = |anchor| Some(PointRef { node: id, subpath: 0, anchor });
|
||||
let linked = DimensionSource::Points { a: anchor(0), b: anchor(2), vertex: None, free_a: None, free_b: None };
|
||||
let off = pick(&cx(&d, &s, &p));
|
||||
assert_eq!(anchors(&off), (Point::new(100.0, 100.0), Point::new(200.0, 200.0), Some(linked.clone())), "preference off");
|
||||
let mut bare = d.clone();
|
||||
bare.node_mut(id).expect("the rectangle").appearance = vectorcraft_doc::Appearance::default().into();
|
||||
let c = ToolContext { preview_bounds: true, ..cx(&bare, &s, &p) };
|
||||
assert_eq!(anchors(&pick(&c)), (Point::new(100.0, 100.0), Point::new(200.0, 200.0), Some(linked)), "no stroke");
|
||||
// A compound path's stroke: the points are held against the member that reaches the
|
||||
// corner, not the small hole drawn first.
|
||||
let mut compound = vectorcraft_doc::Document::new(500.0, 500.0);
|
||||
let (l, hole, part, whole) = (compound.layers[0].id, compound.alloc_id(), compound.alloc_id(), compound.alloc_id());
|
||||
let square = |id, a: f64, b: f64| {
|
||||
std::sync::Arc::new(Node::path(id, vectorcraft_geom::shapes::rectangle(vectorcraft_geom::Rect::new(a, a, b, b)), Default::default()))
|
||||
};
|
||||
let children = vec![square(hole, 140.0, 160.0), square(part, 100.0, 200.0)];
|
||||
let mut n = Node::new(whole, NodeKind::Compound { children, rule: Default::default() });
|
||||
n.appearance = vectorcraft_doc::Appearance::default_art().into();
|
||||
compound.insert(Some(l), 0, n).expect("the compound path");
|
||||
let pending = pick(&ToolContext { preview_bounds: true, ..cx(&compound, &s, &p) });
|
||||
assert!(near(pending.a, Point::new(99.5, 99.5)) && near(pending.b, Point::new(200.5, 200.5)), "{:?} {:?}", pending.a, pending.b);
|
||||
let Some(DimensionSource::Points { free_a: Some(free_a), free_b: Some(free_b), .. }) = &pending.source else {
|
||||
panic!("{:?}", pending.source)
|
||||
};
|
||||
for free in [free_a, free_b] {
|
||||
assert!(matches!(free, FreePoint::Anchors { node, .. } if *node == part), "{free:?}");
|
||||
}
|
||||
// A 40 point stroke, and an Offset Path effect on the fill, put the corners further from
|
||||
// the path than a click on the path reaches: the points still land there and stay linked.
|
||||
let mut wide = vectorcraft_doc::Appearance::default_art();
|
||||
wide.stroke_mut().expect("a stroke").width = 40.0;
|
||||
let mut offset = vectorcraft_doc::Appearance::default_art();
|
||||
let effect =
|
||||
vectorcraft_doc::Effect { id: "path.offsetPath".into(), params: serde_json::json!({"offset": 30, "joins": "miter"}), visible: true };
|
||||
offset.effects_mut(Some(0)).expect("the fill").push(effect);
|
||||
for (appearance, out) in [(wide, 20.0), (offset, 30.0)] {
|
||||
let mut d = d.clone();
|
||||
d.node_mut(id).expect("the rectangle").appearance = appearance.into();
|
||||
let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) };
|
||||
let mut t = DimensionTool::default();
|
||||
for (x, y) in [(101.0 - out, 101.0 - out), (199.0 + out, 199.0 + out)] {
|
||||
t.pointer(&c, &PointerEvent::new(PointerKind::Move, x, y));
|
||||
t.pointer(&c, &PointerEvent::new(PointerKind::Down, x, y));
|
||||
t.pointer(&c, &PointerEvent::new(PointerKind::Up, x, y));
|
||||
}
|
||||
let pending = t.pending.expect("both points were picked");
|
||||
let (a, b) = (Point::new(100.0 - out, 100.0 - out), Point::new(200.0 + out, 200.0 + out));
|
||||
assert!(near(pending.a, a) && near(pending.b, b), "{out}: {:?} {:?}", pending.a, pending.b);
|
||||
let Some(DimensionSource::Points { free_a: Some(free_a), free_b: Some(free_b), .. }) = &pending.source else {
|
||||
panic!("{out}: {:?}", pending.source)
|
||||
};
|
||||
for free in [free_a, free_b] {
|
||||
assert!(matches!(free, FreePoint::Anchors { node, .. } if *node == id), "{out}: {free:?}");
|
||||
}
|
||||
}
|
||||
// A press on a corner over another path's segment picks the corner when the pointer moves
|
||||
// a few pixels before the release, as on an anchor.
|
||||
let mut d = d.clone();
|
||||
let mut wide = vectorcraft_doc::Appearance::default_art();
|
||||
wide.stroke_mut().expect("a stroke").width = 40.0;
|
||||
d.node_mut(id).expect("the rectangle").appearance = wide.into();
|
||||
let (l, line) = (d.layers[0].id, d.alloc_id());
|
||||
let path = vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&[Point::new(0.0, 82.0), Point::new(95.0, 82.0)], false));
|
||||
d.insert(Some(l), 1, Node::path(line, path, Default::default())).expect("the line");
|
||||
let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) };
|
||||
let mut t = DimensionTool::default();
|
||||
assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, 81.0, 81.0)).is_empty());
|
||||
assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Drag, 85.0, 81.0)).is_empty(), "no segment dimension is dragged out");
|
||||
assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 85.0, 81.0)).is_empty());
|
||||
assert!(t.points.first().is_some_and(|(q, _)| near(*q, Point::new(80.0, 80.0))), "{:?}", t.points);
|
||||
}
|
||||
|
||||
/// With Use Preview Bounds on, hovering by a corner of a stroked path's preview bounds, or
|
||||
/// right on it, shows the anchor ring there.
|
||||
#[test]
|
||||
fn hovering_a_corner_of_the_preview_bounds_shows_the_anchor_ring() {
|
||||
let (d, _) = doc_with_rect();
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) };
|
||||
for (x, y) in [(101.0, 101.0), (99.5, 99.5)] {
|
||||
let mut t = DimensionTool::default();
|
||||
t.pointer(&c, &PointerEvent::new(PointerKind::Move, x, y));
|
||||
let ring = t
|
||||
.overlays(&c)
|
||||
.into_iter()
|
||||
.any(|o| matches!(o, Overlay::Anchor { p, filled: false, size, .. } if p.distance(Point::new(99.5, 99.5)) < 1e-9 && size == 10.0));
|
||||
assert!(ring, "({x}, {y})");
|
||||
let label = t
|
||||
.snap
|
||||
.guides()
|
||||
.iter()
|
||||
.any(|o| matches!(o, Overlay::Label { p, text, .. } if text == "anchor" && p.distance(Point::new(99.5, 99.5)) < 1e-9));
|
||||
assert!(label, "({x}, {y}): {:?}", t.snap.guides());
|
||||
}
|
||||
}
|
||||
|
||||
/// With Use Preview Bounds on, a corner of the preview bounds takes a pick with Smart Guides and
|
||||
/// Snap to Point off, as an anchor does, and an anchor of other art nearer the pointer than the
|
||||
/// corner takes it from the corner. The point moves with the path, and a later change to the
|
||||
/// stroke weight leaves it where it was.
|
||||
#[test]
|
||||
fn preview_bounds_corners_take_picks_as_anchors_do() {
|
||||
let (d, id) = doc_with_rect();
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let near = |a: Point, b: Point| a.distance(b) < 1e-9;
|
||||
let pick = |c: &ToolContext, at: [(f64, f64); 2]| {
|
||||
let mut t = DimensionTool::default();
|
||||
for (x, y) in at {
|
||||
t.pointer(c, &PointerEvent::new(PointerKind::Move, x, y));
|
||||
t.pointer(c, &PointerEvent::new(PointerKind::Down, x, y));
|
||||
t.pointer(c, &PointerEvent::new(PointerKind::Up, x, y));
|
||||
}
|
||||
t.pending.expect("both points were picked")
|
||||
};
|
||||
let unsnapped = ToolContext { preview_bounds: true, smart_guides: false, snap_to_point: false, ..cx(&d, &s, &p) };
|
||||
let pending = pick(&unsnapped, [(101.0, 101.0), (199.0, 199.0)]);
|
||||
assert!(near(pending.a, Point::new(99.5, 99.5)) && near(pending.b, Point::new(200.5, 200.5)), "{:?} {:?}", pending.a, pending.b);
|
||||
// An unstroked line whose end lies 2.5 points outside the corner.
|
||||
let mut other = d.clone();
|
||||
let (l, line) = (other.layers[0].id, other.alloc_id());
|
||||
let path = vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&[Point::new(97.0, 97.0), Point::new(50.0, 50.0)], false));
|
||||
other.insert(Some(l), 1, Node::path(line, path, Default::default())).expect("the line");
|
||||
let c = ToolContext { preview_bounds: true, ..cx(&other, &s, &p) };
|
||||
let pending = pick(&c, [(97.5, 97.5), (199.0, 199.0)]);
|
||||
assert!(near(pending.a, Point::new(97.0, 97.0)), "the line's end is nearer: {:?}", pending.a);
|
||||
let Some(DimensionSource::Points { a: Some(a), .. }) = &pending.source else { panic!("{:?}", pending.source) };
|
||||
assert_eq!(a.node, line);
|
||||
let pending = pick(&c, [(99.0, 99.0), (199.0, 199.0)]);
|
||||
assert!(near(pending.a, Point::new(99.5, 99.5)), "the corner is nearer: {:?}", pending.a);
|
||||
// Right on the rectangle's anchor, with another path's anchor nearer than the corner: that
|
||||
// anchor takes the point, not the rectangle's own anchor on the stroke's centerline.
|
||||
let mut beside = d.clone();
|
||||
let (l, line) = (beside.layers[0].id, beside.alloc_id());
|
||||
let path =
|
||||
vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&[Point::new(100.5, 100.0), Point::new(150.0, 50.0)], false));
|
||||
beside.insert(Some(l), 1, Node::path(line, path, Default::default())).expect("the line");
|
||||
let pending = pick(&ToolContext { preview_bounds: true, ..cx(&beside, &s, &p) }, [(100.0, 100.0), (199.0, 199.0)]);
|
||||
let Some(DimensionSource::Points { a: Some(a), .. }) = &pending.source else { panic!("{:?}", pending.source) };
|
||||
assert!(near(pending.a, Point::new(100.5, 100.0)) && a.node == line, "{:?} {a:?}", pending.a);
|
||||
// The point held against the rectangle moves with it and stays put when the stroke changes.
|
||||
let pending = pick(&ToolContext { preview_bounds: true, ..cx(&d, &s, &p) }, [(101.0, 101.0), (199.0, 199.0)]);
|
||||
let Some(DimensionSource::Points { free_a: Some(free), .. }) = &pending.source else { panic!("{:?}", pending.source) };
|
||||
let mut moved = d.clone();
|
||||
moved.node_mut(id).expect("the rectangle").transform(vectorcraft_geom::Affine::translate((10.0, 0.0)), false);
|
||||
assert!(free.position(&moved).is_some_and(|q| near(q, Point::new(109.5, 99.5))), "{:?}", free.position(&moved));
|
||||
let mut wider = d.clone();
|
||||
let mut wide = vectorcraft_doc::Appearance::default_art();
|
||||
wide.stroke_mut().expect("a stroke").width = 40.0;
|
||||
wider.node_mut(id).expect("the rectangle").appearance = wide.into();
|
||||
assert!(free.position(&wider).is_some_and(|q| near(q, Point::new(99.5, 99.5))), "{:?}", free.position(&wider));
|
||||
// Scaled 200% with Scale Strokes off, the point moves with the anchors and no longer sits
|
||||
// on the corner of the preview bounds, which the 1 point stroke puts at (199.5, 199.5).
|
||||
let mut scaled = d.clone();
|
||||
scaled.node_mut(id).expect("the rectangle").transform(vectorcraft_geom::Affine::scale(2.0), false);
|
||||
assert!(free.position(&scaled).is_some_and(|q| near(q, Point::new(199.0, 199.0))), "{:?}", free.position(&scaled));
|
||||
}
|
||||
|
||||
/// With Use Preview Bounds on, a corner takes the pick only from the anchors at the same corner
|
||||
/// of its object's geometric bounds. The other anchors of a small stroked circle stay
|
||||
/// pickable, so does the end of another line lying on the anchor the corner stands in for, and
|
||||
/// of two stroked rectangles sharing an edge, each corner of the shared anchors is held against
|
||||
/// its own rectangle.
|
||||
#[test]
|
||||
fn a_corner_takes_only_the_anchor_it_stands_for() {
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let near = |a: Point, b: Point| a.distance(b) < 1e-9;
|
||||
let mut d = vectorcraft_doc::Document::new(500.0, 500.0);
|
||||
let (l, circle) = (d.layers[0].id, d.alloc_id());
|
||||
let path = vectorcraft_geom::shapes::ellipse(Rect::new(296.0, 296.0, 304.0, 304.0));
|
||||
d.insert(Some(l), 0, Node::path(circle, path, vectorcraft_doc::Appearance::default_art())).expect("the circle");
|
||||
let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) };
|
||||
let mut t = DimensionTool::default();
|
||||
let (q, reference) = t.snap_linear(&c, Point::new(300.0, 296.0));
|
||||
assert!(near(q, Point::new(300.0, 296.0)) && reference.is_some_and(|r| r.node == circle), "{q:?}");
|
||||
let (q, reference) = t.snap_linear(&c, Point::new(296.5, 296.5));
|
||||
assert!(near(q, Point::new(295.5, 295.5)) && reference.is_none() && t.corner == Some(circle), "{q:?}");
|
||||
// An unstroked line ending right on the rectangle's anchor: a click there picks the line's
|
||||
// end, and a click nearer the corner picks the corner.
|
||||
let (mut d, id) = doc_with_rect();
|
||||
let (l, line) = (d.layers[0].id, d.alloc_id());
|
||||
let path =
|
||||
vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&[Point::new(100.0, 100.0), Point::new(50.0, 20.0)], false));
|
||||
d.insert(Some(l), 1, Node::path(line, path, Default::default())).expect("the line");
|
||||
let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) };
|
||||
let mut t = DimensionTool::default();
|
||||
let (q, reference) = t.snap_linear(&c, Point::new(100.0, 100.0));
|
||||
assert!(near(q, Point::new(100.0, 100.0)) && reference.is_some_and(|r| r.node == line), "{q:?}");
|
||||
let (q, reference) = t.snap_linear(&c, Point::new(99.6, 99.6));
|
||||
assert!(near(q, Point::new(99.5, 99.5)) && reference.is_none() && t.corner == Some(id), "{q:?}");
|
||||
// Another path's end right on the corner: a click on the rectangle's anchor picks that end.
|
||||
let (mut d, _) = doc_with_rect();
|
||||
let (l, line) = (d.layers[0].id, d.alloc_id());
|
||||
let path = vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&[Point::new(99.5, 99.5), Point::new(50.0, 20.0)], false));
|
||||
d.insert(Some(l), 0, Node::path(line, path, Default::default())).expect("the line");
|
||||
let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) };
|
||||
let mut t = DimensionTool::default();
|
||||
let (q, reference) = t.snap_linear(&c, Point::new(100.0, 100.0));
|
||||
assert!(near(q, Point::new(99.5, 99.5)) && reference.as_ref().is_some_and(|r| r.node == line), "{q:?} {reference:?}");
|
||||
// A stroked dot, a path whose two anchors coincide, cannot hold a point at a corner: a
|
||||
// click by it picks its anchor.
|
||||
let mut d = vectorcraft_doc::Document::new(500.0, 500.0);
|
||||
let (l, dot) = (d.layers[0].id, d.alloc_id());
|
||||
let path =
|
||||
vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&[Point::new(300.0, 300.0), Point::new(300.0, 300.0)], false));
|
||||
let mut round = vectorcraft_doc::Appearance::default_art();
|
||||
let stroke = round.stroke_mut().expect("a stroke");
|
||||
(stroke.width, stroke.cap) = (10.0, vectorcraft_doc::LineCap::Round);
|
||||
d.insert(Some(l), 0, Node::path(dot, path, round)).expect("the dot");
|
||||
let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) };
|
||||
let mut t = DimensionTool::default();
|
||||
let (q, reference) = t.snap_linear(&c, Point::new(296.0, 296.0));
|
||||
assert!(near(q, Point::new(300.0, 300.0)) && reference.is_some_and(|r| r.node == dot) && t.corner.is_none(), "{q:?}");
|
||||
// A stroked rectangle made into a guide, and a stroked member of a compound path without
|
||||
// a stroke of its own, give no corners.
|
||||
for kind in ["guide", "member"] {
|
||||
let (mut d, id) = doc_with_rect();
|
||||
let mut wide = vectorcraft_doc::Appearance::default_art();
|
||||
wide.stroke_mut().expect("a stroke").width = 40.0;
|
||||
if kind == "guide" {
|
||||
let n = d.node_mut(id).expect("the rectangle");
|
||||
n.appearance = wide.into();
|
||||
if let NodeKind::Path { guide, .. } = &mut n.kind {
|
||||
*guide = true;
|
||||
}
|
||||
} else {
|
||||
let mut fresh = vectorcraft_doc::Document::new(500.0, 500.0);
|
||||
let (l, part, whole) = (fresh.layers[0].id, fresh.alloc_id(), fresh.alloc_id());
|
||||
let mut member = Node::path(part, vectorcraft_geom::shapes::rectangle(Rect::new(100.0, 100.0, 200.0, 200.0)), Default::default());
|
||||
member.appearance = wide.into();
|
||||
let n = Node::new(whole, NodeKind::Compound { children: vec![std::sync::Arc::new(member)], rule: Default::default() });
|
||||
fresh.insert(Some(l), 0, n).expect("the compound path");
|
||||
d = fresh;
|
||||
}
|
||||
let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) };
|
||||
let mut t = DimensionTool::default();
|
||||
let (q, _) = t.snap_linear(&c, Point::new(81.0, 81.0));
|
||||
assert!(!near(q, Point::new(80.0, 80.0)) && t.corner.is_none(), "{kind}: {q:?}");
|
||||
}
|
||||
// Two stroked rectangles sharing the edge x = 200; the right one is on top.
|
||||
let (mut d, left) = doc_with_rect();
|
||||
let (l, right) = (d.layers[0].id, d.alloc_id());
|
||||
let path = vectorcraft_geom::shapes::rectangle(Rect::new(200.0, 100.0, 300.0, 200.0));
|
||||
d.insert(Some(l), 1, Node::path(right, path, vectorcraft_doc::Appearance::default_art())).expect("the right rectangle");
|
||||
let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) };
|
||||
for (pointer, corner, holder) in [((200.4, 99.6), (200.5, 99.5), left), ((199.6, 99.6), (199.5, 99.5), right)] {
|
||||
let mut t = DimensionTool::default();
|
||||
for kind in [PointerKind::Move, PointerKind::Down, PointerKind::Up] {
|
||||
t.pointer(&c, &PointerEvent::new(kind, pointer.0, pointer.1));
|
||||
}
|
||||
for kind in [PointerKind::Move, PointerKind::Down, PointerKind::Up] {
|
||||
t.pointer(&c, &PointerEvent::new(kind, 250.0, 300.0));
|
||||
}
|
||||
let pending = t.pending.expect("both points were picked");
|
||||
assert!(near(pending.a, Point::new(corner.0, corner.1)), "{pointer:?}: {:?}", pending.a);
|
||||
let Some(DimensionSource::Points { a: None, free_a: Some(free), .. }) = &pending.source else { panic!("{:?}", pending.source) };
|
||||
assert!(matches!(free, FreePoint::Anchors { node, .. } if *node == holder), "{pointer:?}: {free:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// A point is held against a path for a corner of its preview bounds only when it was picked
|
||||
/// there: the same position picked another way links to the segment under it.
|
||||
#[test]
|
||||
fn a_point_is_held_for_a_corner_only_when_picked_on_it() {
|
||||
let (mut d, id) = doc_with_rect();
|
||||
let (l, line) = (d.layers[0].id, d.alloc_id());
|
||||
let path = vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&[Point::new(0.0, 99.5), Point::new(300.0, 99.5)], false));
|
||||
d.insert(Some(l), 1, Node::path(line, path, Default::default())).expect("the line");
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let c = ToolContext { preview_bounds: true, ..cx(&d, &s, &p) };
|
||||
let (corner, b) = (Point::new(99.5, 99.5), Point::new(250.0, 99.5));
|
||||
for (held, node) in [(Some(id), id), (None, line)] {
|
||||
let source = points_source(&c, (corner, &None, held), (b, &None, None));
|
||||
let Some(DimensionSource::Points { free_a: Some(free), .. }) = &source else { panic!("{source:?}") };
|
||||
let linked = match free {
|
||||
FreePoint::Anchors { node, .. } => *node,
|
||||
FreePoint::OnSegment { edge, .. } => edge.node,
|
||||
};
|
||||
assert_eq!(linked, node, "{held:?}: {free:?}");
|
||||
}
|
||||
}
|
||||
|
||||
/// Hovering right on the end of a dimension's line shows the anchor ring there.
|
||||
#[test]
|
||||
fn hovering_right_on_a_dimension_lines_end_shows_the_anchor_ring() {
|
||||
let mut d = vectorcraft_doc::Document::new(500.0, 500.0);
|
||||
let (l, id) = (d.layers[0].id, d.alloc_id());
|
||||
let path =
|
||||
vectorcraft_geom::PathData::single(vectorcraft_geom::SubPath::polyline(&[Point::new(300.0, 300.0), Point::new(400.0, 300.0)], false));
|
||||
let mut n = Node::path(id, path, Default::default());
|
||||
let recipe = DimensionTool::default().recipe(DimensionMode::Linear, Point::new(0.0, 0.0), Point::new(50.0, 0.0), Point::ZERO, None);
|
||||
n.extras_mut().dimension = Some(Box::new(recipe));
|
||||
d.insert(Some(l), 0, n).expect("the dimension's line");
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let c = ToolContext { smart_guides: true, snap_to_point: true, ..cx(&d, &s, &p) };
|
||||
let mut t = DimensionTool::default();
|
||||
t.pointer(&c, &PointerEvent::new(PointerKind::Move, 300.0, 300.0));
|
||||
let ring = t
|
||||
.overlays(&c)
|
||||
.into_iter()
|
||||
.any(|o| matches!(o, Overlay::Anchor { p, filled: false, size, .. } if p.distance(Point::new(300.0, 300.0)) < 1e-9 && size == 10.0));
|
||||
assert!(ring, "{:?}", t.overlays(&c));
|
||||
}
|
||||
|
||||
/// The anchors of a live rectangle are picked the same way.
|
||||
#[test]
|
||||
fn a_press_on_a_live_shapes_anchor_picks_it() {
|
||||
|
||||
@@ -37,7 +37,7 @@ use std::collections::{BTreeMap, BTreeSet};
|
||||
use std::sync::Arc;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_brush::{Calligraphic, Variation};
|
||||
use vectorcraft_brush::{BristleShape, BrushKind, Calligraphic, Variation};
|
||||
use vectorcraft_doc::{NodeId, NodeKind};
|
||||
use vectorcraft_geom::{Affine, BezPath, FillRule, ParamCurve, PathData, PathSeg, Point, Rect, Vec2, shapes};
|
||||
use vectorcraft_pathops as po;
|
||||
@@ -200,6 +200,12 @@ pub struct GestureTool {
|
||||
/// Where the Blob Brush's or the Eraser's tip outline shows: the pointer over the canvas,
|
||||
/// unless Cmd/Ctrl lends a selection tool or Alt the Smooth tool.
|
||||
tip_at: Option<Point>,
|
||||
/// Alt as it was at the last pointer event; the release can select a new path after the tool
|
||||
/// returns, so the Bristle tip checks the current selection when overlays are drawn.
|
||||
tip_alt: bool,
|
||||
/// The last rotation-capable pen over the Paintbrush's Bristle tip; a mouse or a pen without
|
||||
/// barrel rotation has no tip annotator.
|
||||
bristle_pen: Option<(PenPose, f64)>,
|
||||
/// A pen pressed less than fully at a point of the stroke whose pressure is kept.
|
||||
light: bool,
|
||||
/// Which way the pen leaned at the last point of the stroke where it leaned 1° or more from
|
||||
@@ -899,6 +905,8 @@ impl GestureTool {
|
||||
snap: DrawSnap::default(),
|
||||
pressed: Point::ZERO,
|
||||
tip_at: None,
|
||||
tip_alt: false,
|
||||
bristle_pen: None,
|
||||
light: false,
|
||||
bearing: None,
|
||||
bearings: vec![],
|
||||
@@ -1088,12 +1096,50 @@ impl GestureTool {
|
||||
p
|
||||
}
|
||||
|
||||
fn pointer_tip(&mut self, cx: &ToolContext, ev: &PointerEvent) {
|
||||
if self.varies_size() {
|
||||
self.tip_at = (!ev.mods.cmd && !self.blob_alt_smooths(ev.mods)).then_some(ev.pos);
|
||||
} else if self.id == "paintbrush" {
|
||||
self.tip_alt = ev.mods.alt;
|
||||
self.bristle_pen =
|
||||
ev.pen.filter(|pen| pen.rotation.is_some()).map(|pen| (pen, if ev.kind == PointerKind::Move { 0.5 } else { f64::from(ev.pressure) }));
|
||||
let borrows_smooth = !self.active && ev.mods.alt && has_selected_smooth_path(cx);
|
||||
self.tip_at = self.bristle_pen.filter(|_| !ev.mods.cmd && !borrows_smooth).map(|_| ev.pos);
|
||||
}
|
||||
}
|
||||
|
||||
/// The Blob Brush's or the Eraser's tip at the pointer, before and while painting: its outline
|
||||
/// `size` across at its angle and roundness (the Eraser's as the pen varies them while it
|
||||
/// erases, [`Self::tip_now`]), at the zoom, black on a white halo so it reads on
|
||||
/// any art. Precise cursors show only the crosshair, and smoothing shows no tip.
|
||||
fn tip_outline(&self, cx: &ToolContext) -> Vec<Overlay> {
|
||||
let Some(at) = self.tip_at.filter(|_| !self.smoothing && !cx.precise_cursors) else { return vec![] };
|
||||
if self.id == "paintbrush" {
|
||||
if !self.active && self.tip_alt && has_selected_smooth_path(cx) {
|
||||
return vec![];
|
||||
}
|
||||
let Some((pose, pressure)) = self.bristle_pen else { return vec![] };
|
||||
let Some(name) = vectorcraft_brush::current(cx.doc) else { return vec![] };
|
||||
let Some(brush) = vectorcraft_brush::find(cx.doc, &name) else { return vec![] };
|
||||
let BrushKind::Bristle(bristle) = brush.kind else { return vec![] };
|
||||
let [pressure, tilt, bearing, rotation] = super::pen_controls(pressure, Some(pose), super::pen_bearing(pose));
|
||||
let size = bristle.size.max(0.1) * cx.paint.stroke_width.max(0.0) * (0.5 + pressure) * (1.25 - 0.5 * tilt);
|
||||
if size <= 0.0 {
|
||||
return vec![];
|
||||
}
|
||||
let roundness = match bristle.shape {
|
||||
BristleShape::RoundFan | BristleShape::FlatFan => 0.25,
|
||||
BristleShape::FlatPoint | BristleShape::FlatBlunt | BristleShape::FlatCurve | BristleShape::FlatAngle => 0.45,
|
||||
_ => 0.8,
|
||||
};
|
||||
let angle = std::f64::consts::TAU * (bearing + rotation - 1.0);
|
||||
let circle = kurbo::Shape::to_path(&kurbo::Circle::new(Point::ORIGIN, size / 2.0), size.max(0.1) * 0.05);
|
||||
let path = Affine::translate(at.to_vec2()) * Affine::rotate(-angle) * Affine::scale_non_uniform(1.0, roundness) * circle;
|
||||
return vec![
|
||||
Overlay::Path { path: path.clone(), color: [0xff, 0xff, 0xff], width: 3.0, dashed: false },
|
||||
Overlay::Path { path, color: [0, 0, 0], width: 1.0, dashed: false },
|
||||
];
|
||||
}
|
||||
let [angle, roundness, size] = self.tip_now();
|
||||
let tip = if self.id == "blobBrush" { blob_tip(angle, roundness) } else { eraser_tip(angle, roundness) };
|
||||
let r = size / 2.0;
|
||||
@@ -1587,9 +1633,7 @@ impl Tool for GestureTool {
|
||||
}
|
||||
fn pointer(&mut self, cx: &ToolContext, ev: &PointerEvent) -> Vec<Action> {
|
||||
let p = ev.pos;
|
||||
if self.varies_size() {
|
||||
self.tip_at = (!ev.mods.cmd && !self.blob_alt_smooths(ev.mods)).then_some(p);
|
||||
}
|
||||
self.pointer_tip(cx, ev);
|
||||
if let Some(out) = self.marquee_pointer(cx, ev) {
|
||||
return out;
|
||||
}
|
||||
@@ -1762,6 +1806,10 @@ impl Tool for GestureTool {
|
||||
self.close_to = None;
|
||||
self.connect_to.clear();
|
||||
self.redraw = None;
|
||||
if self.id == "paintbrush" {
|
||||
// The release can change a drawing stroke into an Alt-borrowed Smooth hover.
|
||||
self.pointer_tip(cx, ev);
|
||||
}
|
||||
out
|
||||
}
|
||||
_ => vec![],
|
||||
|
||||
@@ -3043,6 +3043,103 @@ fn the_blob_brush_and_the_eraser_show_their_tip_at_the_pointer() {
|
||||
}
|
||||
}
|
||||
|
||||
/// A rotation-capable pen shows the current Bristle brush's tip before and during a Paintbrush
|
||||
/// stroke. A mouse, a pen without rotation, precise cursors and a borrowed selection tool do not.
|
||||
#[test]
|
||||
fn bristle_tip_annotator_follows_a_rotation_capable_pen() {
|
||||
let (mut d, id) = doc_with_rect();
|
||||
d.unknown.insert(vectorcraft_brush::CURRENT_KEY.into(), json!("Bristle Flat Fan"));
|
||||
let s = Selection::default();
|
||||
let p = paint();
|
||||
let view = cx(&d, &s, &p);
|
||||
let bounds = |t: &GestureTool, cx: &ToolContext| {
|
||||
let overlays = t.overlays(cx);
|
||||
let Some(Overlay::Path { path, color: [0, 0, 0], width: 1.0, .. }) = overlays.last() else { return None };
|
||||
assert!(matches!(overlays.get(overlays.len() - 2), Some(Overlay::Path { color: [0xff, 0xff, 0xff], width: 3.0, .. })));
|
||||
Some(vectorcraft_geom::Shape::bounding_box(path))
|
||||
};
|
||||
let mut tool = GestureTool::new("paintbrush");
|
||||
let at =
|
||||
|rotation| PointerEvent { pen: Some(PenPose { tilt: Some([30.0, 0.0]), rotation }), ..PointerEvent::new(PointerKind::Move, 100.0, 50.0) };
|
||||
assert!(bounds(&tool, &view).is_none());
|
||||
tool.pointer(&view, &PointerEvent::new(PointerKind::Move, 100.0, 50.0));
|
||||
assert!(bounds(&tool, &view).is_none(), "mouse");
|
||||
tool.pointer(&view, &at(None));
|
||||
assert!(bounds(&tool, &view).is_none(), "pen without rotation");
|
||||
tool.pointer(&view, &at(Some(0.0)));
|
||||
let horizontal = bounds(&tool, &view).expect("rotating pen shows a tip");
|
||||
let mut selected = Selection::default();
|
||||
selected.set([id]);
|
||||
let selected_view = cx(&d, &selected, &p);
|
||||
tool.pointer(&selected_view, &at(Some(0.0)).with_mods(Mods { alt: true, ..Default::default() }));
|
||||
assert!(bounds(&tool, &selected_view).is_none(), "Alt borrows Smooth for a selected path");
|
||||
tool.pointer(&view, &at(Some(0.0)));
|
||||
let mut wider_paint = p.clone();
|
||||
wider_paint.stroke_width = 10.0;
|
||||
let wider_view = cx(&d, &s, &wider_paint);
|
||||
let wider = bounds(&tool, &wider_view).expect("stroke width scales the tip");
|
||||
assert!((wider.width() - horizontal.width() * 10.0).abs() < 1e-6, "{horizontal:?}, {wider:?}");
|
||||
wider_paint.stroke_width = 0.0;
|
||||
assert!(bounds(&tool, &cx(&d, &s, &wider_paint)).is_none(), "a zero-width stroke has no tip");
|
||||
tool.pointer(&view, &at(Some(90.0)));
|
||||
let vertical = bounds(&tool, &view).expect("tip turns with the barrel");
|
||||
assert!(horizontal.width() > horizontal.height() * 2.0, "{horizontal:?}");
|
||||
assert!(vertical.height() > vertical.width() * 2.0, "{vertical:?}");
|
||||
let mut light = at(Some(0.0));
|
||||
light.kind = PointerKind::Down;
|
||||
light.pressure = 0.1;
|
||||
tool.pointer(&view, &light);
|
||||
let light_tip = bounds(&tool, &view).expect("light pressure shows a smaller tip");
|
||||
let mut heavy = light;
|
||||
heavy.kind = PointerKind::Drag;
|
||||
heavy.pressure = 0.9;
|
||||
tool.pointer(&view, &heavy);
|
||||
let heavy_tip = bounds(&tool, &view).expect("heavy pressure shows a larger tip");
|
||||
assert!(heavy_tip.width() > light_tip.width() * 1.5, "{light_tip:?}, {heavy_tip:?}");
|
||||
let mut release = heavy;
|
||||
release.kind = PointerKind::Up;
|
||||
tool.pointer(&view, &release);
|
||||
let mut alt_stroke = light;
|
||||
alt_stroke.pressure = 0.5;
|
||||
tool.pointer(&selected_view, &alt_stroke);
|
||||
alt_stroke.kind = PointerKind::Drag;
|
||||
alt_stroke.mods.alt = true;
|
||||
tool.pointer(&selected_view, &alt_stroke);
|
||||
assert!(bounds(&tool, &selected_view).is_some(), "Alt during a drawing stroke keeps the tip");
|
||||
alt_stroke.kind = PointerKind::Up;
|
||||
tool.pointer(&selected_view, &alt_stroke);
|
||||
assert_eq!(tool.cursor(&selected_view, alt_stroke.pos, alt_stroke.mods), Cursor::Smooth);
|
||||
assert!(bounds(&tool, &selected_view).is_none(), "Alt release borrows Smooth without a stale tip");
|
||||
// A completed stroke can select its new path after `pointer` returns its actions. The overlay
|
||||
// must use that current selection even without a further pointer move.
|
||||
let mut newly_selected = GestureTool::new("paintbrush");
|
||||
let mut new_stroke = light;
|
||||
newly_selected.pointer(&view, &new_stroke);
|
||||
new_stroke.kind = PointerKind::Drag;
|
||||
new_stroke.mods.alt = true;
|
||||
newly_selected.pointer(&view, &new_stroke);
|
||||
new_stroke.kind = PointerKind::Up;
|
||||
newly_selected.pointer(&view, &new_stroke);
|
||||
assert!(bounds(&newly_selected, &view).is_some(), "no selected path borrows Smooth yet");
|
||||
assert_eq!(newly_selected.cursor(&selected_view, new_stroke.pos, new_stroke.mods), Cursor::Smooth);
|
||||
assert!(bounds(&newly_selected, &selected_view).is_none(), "post-commit selection also hides the tip");
|
||||
tool.pointer(&view, &at(Some(0.0)));
|
||||
assert!(bounds(&tool, &view).is_some(), "a normal pen hover shows the tip before Precise Cursors hides it");
|
||||
let precise = ToolContext { precise_cursors: true, ..cx(&d, &s, &p) };
|
||||
assert!(bounds(&tool, &precise).is_none());
|
||||
tool.pointer(&view, &at(Some(0.0)).with_mods(Mods { cmd: true, ..Default::default() }));
|
||||
assert!(bounds(&tool, &view).is_none(), "selection tool borrowed by Cmd");
|
||||
tool.pointer(&view, &at(Some(0.0)));
|
||||
tool.hover_ended(&view);
|
||||
assert!(bounds(&tool, &view).is_none(), "leaving the canvas");
|
||||
|
||||
let (mut d, _) = doc_with_rect();
|
||||
d.unknown.insert(vectorcraft_brush::CURRENT_KEY.into(), json!("3 pt. Round"));
|
||||
let calligraphic = cx(&d, &s, &p);
|
||||
tool.pointer(&calligraphic, &at(Some(0.0)));
|
||||
assert!(bounds(&tool, &calligraphic).is_none(), "other brush types keep their cursor");
|
||||
}
|
||||
|
||||
/// Eraser Tool Options' Angle, Roundness and Size variation menus: the Eraser keeps each mode and
|
||||
/// Variation, the release sends them with the pen's readings along the drag, and while it erases
|
||||
/// its tip outline at the pointer takes the angle, roundness and size the pen gives there. The Blob
|
||||
|
||||
@@ -42,6 +42,7 @@ pub mod select;
|
||||
pub mod settings;
|
||||
pub mod shape;
|
||||
pub mod shaperwidget;
|
||||
pub mod sidewidget;
|
||||
pub mod slice;
|
||||
pub mod symbolism;
|
||||
pub mod text;
|
||||
@@ -104,6 +105,10 @@ pub enum Overlay {
|
||||
Swatch { p: Point, color: [u8; 4], selected: bool },
|
||||
/// A hairline in a translucent colour (perspective gridlines), RGBA.
|
||||
GridLine { a: Point, b: Point, color: [u8; 4] },
|
||||
/// Hover text for the disc of `radius` (document units) around `center`: while the pointer
|
||||
/// rests there and nothing is being dragged, the UI shows `text`, an English UI string it
|
||||
/// translates, as a tooltip. Nothing is drawn for it.
|
||||
HoverText { center: Point, radius: f64, text: &'static str },
|
||||
}
|
||||
|
||||
/// What an IME's "delete the text around the cursor" counts: UTF-8 bytes (winit's raw
|
||||
@@ -674,6 +679,19 @@ pub(crate) mod testutil {
|
||||
global_edit: &[],
|
||||
}
|
||||
}
|
||||
|
||||
/// Held for reading by tests that count the layouts the Type tool keeps, and for writing by
|
||||
/// tests that change what layout reads (fonts, hyphenation exceptions): tests run in parallel,
|
||||
/// and a count must not include a refresh another test caused.
|
||||
static LAYOUT_INPUTS: std::sync::RwLock<()> = std::sync::RwLock::new(());
|
||||
|
||||
pub fn steady_layout_inputs() -> std::sync::RwLockReadGuard<'static, ()> {
|
||||
LAYOUT_INPUTS.read().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
|
||||
pub fn changing_layout_inputs() -> std::sync::RwLockWriteGuard<'static, ()> {
|
||||
LAYOUT_INPUTS.write().unwrap_or_else(|e| e.into_inner())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
||||
@@ -54,6 +54,7 @@ use crate::pathtype::{self, BracketDrag, over_bracket};
|
||||
use crate::pie::{self, PieDrag};
|
||||
use crate::rulerguide::GuideEdit;
|
||||
use crate::shaperwidget;
|
||||
use crate::sidewidget::{self, SideDrag};
|
||||
use crate::typewidget;
|
||||
use crate::{Action, Cursor, Mods, Overlay, PixelOp, PointerEvent, PointerKind, Tool, ToolContext, ToolKey, json_ids};
|
||||
|
||||
@@ -134,6 +135,8 @@ enum State {
|
||||
Corner(CornerDrag),
|
||||
/// Dragging a live ellipse's pie widget.
|
||||
Pie(PieDrag),
|
||||
/// Dragging a live polygon's side widget.
|
||||
Sides(SideDrag),
|
||||
/// Dragging a selected blend's Appearance or Easing widget.
|
||||
BlendWidget(BlendWidgetDrag),
|
||||
/// Dragging an Objects on Path group's Rotate All widget.
|
||||
@@ -827,7 +830,7 @@ impl Tool for SelectionTool {
|
||||
|
||||
/// E during a marquee drag switches the marquee between the objects it touches and only the
|
||||
/// objects inside it. Escape during a drag (a move or an Alt-drag copy, a bounding-box scale or
|
||||
/// rotation, a marquee, a corner widget, a pie widget, a blend widget, the Rotate All, Space, Move All or Select/Move widget, the brackets of type on a path, a mirror
|
||||
/// rotation, a marquee, a corner widget, a pie widget, a polygon's side widget, a blend widget, the Rotate All, Space, Move All or Select/Move widget, the brackets of type on a path, a mirror
|
||||
/// axis, a grid repeat's handles, a ruler guide) cancels it: what it changed goes back, no copy
|
||||
/// is left, and the tool waits for the next press. With the pointer loaded with text, Escape
|
||||
/// drops the text.
|
||||
@@ -864,6 +867,12 @@ impl Tool for SelectionTool {
|
||||
{
|
||||
return d.cancel();
|
||||
}
|
||||
if key == ToolKey::Escape
|
||||
&& matches!(self.state, State::Sides(_))
|
||||
&& let State::Sides(d) = std::mem::take(&mut self.state)
|
||||
{
|
||||
return d.cancel();
|
||||
}
|
||||
if key == ToolKey::Escape
|
||||
&& matches!(self.state, State::NineSlice(_))
|
||||
&& let State::NineSlice(d) = std::mem::take(&mut self.state)
|
||||
@@ -896,11 +905,15 @@ impl Tool for SelectionTool {
|
||||
out
|
||||
}
|
||||
|
||||
/// Switching tools during a blend widget's drag cancels it, as Escape does: its value goes back.
|
||||
/// Switching tools during a drag of a blend widget, a corner widget, a pie widget or a
|
||||
/// polygon's side widget cancels it, as Escape does: its value goes back.
|
||||
fn deactivate(&mut self, _cx: &ToolContext) -> Vec<Action> {
|
||||
match std::mem::take(&mut self.state) {
|
||||
State::BlendWidget(d) if d.adjusting() => vec![Action::Cancel],
|
||||
State::BlendWidget(_) => vec![],
|
||||
State::Corner(c) if c.adjusting() => vec![Action::Cancel],
|
||||
State::Pie(d) if d.adjusting() => vec![Action::Cancel],
|
||||
State::Sides(d) => d.cancel(),
|
||||
State::BlendWidget(_) | State::Corner(_) | State::Pie(_) => vec![],
|
||||
other => {
|
||||
self.state = other;
|
||||
vec![]
|
||||
@@ -947,6 +960,7 @@ impl Tool for SelectionTool {
|
||||
State::Moving { began: true, .. } | State::Scaling { .. } | State::Rotating { .. } => true,
|
||||
State::Corner(c) => c.adjusting(),
|
||||
State::Pie(d) => d.adjusting(),
|
||||
State::Sides(d) => d.adjusting(),
|
||||
State::BlendWidget(d) => d.adjusting(),
|
||||
State::RotateAll(d) => d.adjusting(),
|
||||
State::Space(d) => d.adjusting(),
|
||||
@@ -1126,6 +1140,15 @@ impl Tool for SelectionTool {
|
||||
self.state = State::Idle;
|
||||
d.finish()
|
||||
}
|
||||
(PointerKind::Drag, State::Sides(mut d)) => {
|
||||
let out = d.drag(cx, p);
|
||||
self.state = State::Sides(d);
|
||||
out
|
||||
}
|
||||
(PointerKind::Up, State::Sides(d)) => {
|
||||
self.state = State::Idle;
|
||||
d.finish()
|
||||
}
|
||||
(PointerKind::Drag, State::BlendWidget(mut d)) => {
|
||||
let out = d.drag(cx, p);
|
||||
self.state = State::BlendWidget(d);
|
||||
@@ -1233,6 +1256,7 @@ impl Tool for SelectionTool {
|
||||
}),
|
||||
State::Corner(c) => o.extend(c.overlays(cx)),
|
||||
State::Pie(d) => o.extend(d.overlays(cx)),
|
||||
State::Sides(d) => o.extend(d.overlays(cx)),
|
||||
State::BlendWidget(d) => o.extend(d.overlays(cx)),
|
||||
State::RotateAll(d) => o.extend(d.overlays(cx)),
|
||||
State::Space(d) => o.extend(d.overlays(cx)),
|
||||
@@ -1292,7 +1316,7 @@ impl Tool for SelectionTool {
|
||||
State::Moving { began: true, .. } if m.alt => return Cursor::SelectionCopy,
|
||||
State::Moving { began: true, .. } => return if self.snapped { Cursor::ArrowHollow } else { Cursor::Arrow },
|
||||
State::Corner(_) => return Cursor::CornerRadius,
|
||||
State::Pie(_) | State::BlendWidget(_) => return Cursor::ArrowHollow,
|
||||
State::Pie(_) | State::Sides(_) | State::BlendWidget(_) => return Cursor::ArrowHollow,
|
||||
State::RotateAll(_) => return Cursor::Rotate,
|
||||
State::Space(_) => return Cursor::ArrowHollow,
|
||||
State::MoveAll(_) | State::Member(_) => return Cursor::Move,
|
||||
@@ -1323,6 +1347,9 @@ impl Tool for SelectionTool {
|
||||
if near_selected && pie::over_widget(cx, p) {
|
||||
return Cursor::ArrowHollow;
|
||||
}
|
||||
if sidewidget::over_widget(cx, p) {
|
||||
return Cursor::ArrowHollow;
|
||||
}
|
||||
if blendwidget::over_widget(cx, p) {
|
||||
return Cursor::ArrowHollow;
|
||||
}
|
||||
@@ -1689,6 +1716,10 @@ impl SelectionTool {
|
||||
if blendwidget::over_widget(cx, p) {
|
||||
return vec![];
|
||||
}
|
||||
// A live polygon's side widget takes a plain double-click the same way.
|
||||
if sidewidget::over_widget(cx, p) {
|
||||
return vec![];
|
||||
}
|
||||
if crate::rulerguide::guide_at(cx, p).is_some() {
|
||||
return vec![];
|
||||
}
|
||||
@@ -1728,7 +1759,7 @@ impl SelectionTool {
|
||||
self.state = State::Loaded { from, before: port == crate::text::Port::In, press: None };
|
||||
return Some(vec![]);
|
||||
}
|
||||
// 1. Live Corners widgets, pie widgets, blend widgets, the Rotate All, Space, Move All and Select/Move widgets and type on a path's brackets, then the
|
||||
// 1. Live Corners widgets, pie widgets, a polygon's side widget, blend widgets, the Rotate All, Space, Move All and Select/Move widgets and type on a path's brackets, then the
|
||||
// bounding-box handles of the current selection.
|
||||
if let Some(c) = CornerDrag::hit(cx, ev, false) {
|
||||
self.state = State::Corner(c);
|
||||
@@ -1738,6 +1769,10 @@ impl SelectionTool {
|
||||
self.state = State::Pie(d);
|
||||
return Some(vec![]);
|
||||
}
|
||||
if let Some(d) = SideDrag::hit(cx, ev) {
|
||||
self.state = State::Sides(d);
|
||||
return Some(vec![]);
|
||||
}
|
||||
if let Some(d) = BlendWidgetDrag::hit(cx, ev) {
|
||||
self.state = State::BlendWidget(d);
|
||||
return Some(vec![]);
|
||||
|
||||
@@ -25,7 +25,8 @@
|
||||
//! The selection keeps its bounding box and its Live Shape widgets on show with the Rectangle,
|
||||
//! Rounded Rectangle, Ellipse, Polygon and Star tools, so a shape just drawn can be adjusted at
|
||||
//! once: a drag on a live rectangle's or polygon's corner widget rounds its corners and a drag on
|
||||
//! a live ellipse's pie widget sets its pie angle, as with the Selection tool; a drag on one of the
|
||||
//! a live ellipse's pie widget sets its pie angle and a drag on a live polygon's side widget sets
|
||||
//! its number of sides, as with the Selection tool; a drag on one of the
|
||||
//! box's eight handles scales the selection, a press on the selection's centre point (Show Center)
|
||||
//! moves it, and one just outside a corner of its box turns it about that centre, as the Selection
|
||||
//! tool's handles, centre point and rotate zone do; a press anywhere else draws a new shape (#5477).
|
||||
@@ -43,6 +44,7 @@ use crate::corners::{self, CornerDrag};
|
||||
use crate::guides::{DrawSnap, Leave, PointSnap, TangentLine, Targets, square};
|
||||
use crate::pie::{self, PieDrag};
|
||||
use crate::select::{MoveSnap, handle_cursor, hit_center, is_area_type, matrix_json, rotate_zone, shown_box};
|
||||
use crate::sidewidget::{self, SideDrag};
|
||||
use crate::{Action, Cursor, Mods, Overlay, PointerEvent, PointerKind, Tool, ToolContext, ToolKey};
|
||||
|
||||
/// The largest corner radius the Rounded Rectangle tool draws, points: the range of General ›
|
||||
@@ -84,6 +86,7 @@ pub fn shows_shape_widgets(id: &str) -> bool {
|
||||
enum WidgetDrag {
|
||||
Corner(CornerDrag),
|
||||
Pie(PieDrag),
|
||||
Sides(SideDrag),
|
||||
}
|
||||
|
||||
/// A drag of the selection itself, taken by a shape tool: a handle of its box scales it, the centre
|
||||
@@ -294,18 +297,21 @@ impl ShapeTool {
|
||||
self.star_ratio = o.star_ratio;
|
||||
}
|
||||
|
||||
/// A press on a corner or pie widget of the selection: the drag adjusts it.
|
||||
/// A press on a corner, pie or side widget of the selection: the drag adjusts it.
|
||||
fn press_widget(&mut self, cx: &ToolContext, ev: &PointerEvent) -> bool {
|
||||
if !shows_shape_widgets(self.id) {
|
||||
return false;
|
||||
}
|
||||
self.widget = CornerDrag::hit(cx, ev, false).map(WidgetDrag::Corner).or_else(|| PieDrag::hit(cx, ev).map(WidgetDrag::Pie));
|
||||
self.widget = CornerDrag::hit(cx, ev, false)
|
||||
.map(WidgetDrag::Corner)
|
||||
.or_else(|| PieDrag::hit(cx, ev).map(WidgetDrag::Pie))
|
||||
.or_else(|| SideDrag::hit(cx, ev).map(WidgetDrag::Sides));
|
||||
self.widget.is_some()
|
||||
}
|
||||
|
||||
/// Is `p` over a corner or pie widget of the selection that a press would drag?
|
||||
/// Is `p` over a corner, pie or side widget of the selection that a press would drag?
|
||||
fn over_widget(&self, cx: &ToolContext, p: Point) -> bool {
|
||||
shows_shape_widgets(self.id) && (corners::over_widget(cx, p, false) || pie::over_widget(cx, p))
|
||||
shows_shape_widgets(self.id) && (corners::over_widget(cx, p, false) || pie::over_widget(cx, p) || sidewidget::over_widget(cx, p))
|
||||
}
|
||||
|
||||
/// The selection's box, while this tool shows it (the tools that draw a box, with a selection
|
||||
@@ -481,10 +487,12 @@ impl ShapeTool {
|
||||
PointerKind::Drag => match w {
|
||||
WidgetDrag::Corner(c) => c.drag(cx, ev.pos),
|
||||
WidgetDrag::Pie(d) => d.drag(cx, ev.pos),
|
||||
WidgetDrag::Sides(d) => d.drag(cx, ev.pos),
|
||||
},
|
||||
PointerKind::Up => match self.widget.take() {
|
||||
Some(WidgetDrag::Corner(c)) => c.finish(),
|
||||
Some(WidgetDrag::Pie(d)) => d.finish(),
|
||||
Some(WidgetDrag::Sides(d)) => d.finish(),
|
||||
None => vec![],
|
||||
},
|
||||
_ => vec![],
|
||||
@@ -823,6 +831,12 @@ impl Tool for ShapeTool {
|
||||
_ => vec![],
|
||||
}
|
||||
}
|
||||
/// Switching tools during a drag of a corner, pie or side widget cancels it, as Escape does:
|
||||
/// the shape goes back.
|
||||
fn deactivate(&mut self, cx: &ToolContext) -> Vec<Action> {
|
||||
if self.widget.is_some() { self.key(cx, ToolKey::Escape, Mods::default()) } else { vec![] }
|
||||
}
|
||||
|
||||
/// ↑/↓ change a polygon's sides, a star's points or the rounded rectangle's radius while it is
|
||||
/// drawn; Escape turns a widget or selection drag back.
|
||||
fn key(&mut self, cx: &ToolContext, key: ToolKey, _mods: Mods) -> Vec<Action> {
|
||||
@@ -838,6 +852,7 @@ impl Tool for ShapeTool {
|
||||
(ToolKey::Escape, _) => match self.widget.take() {
|
||||
Some(WidgetDrag::Corner(c)) if c.adjusting() => vec![Action::Cancel],
|
||||
Some(WidgetDrag::Pie(d)) if d.adjusting() => vec![Action::Cancel],
|
||||
Some(WidgetDrag::Sides(d)) => d.cancel(),
|
||||
_ => vec![],
|
||||
},
|
||||
_ => vec![],
|
||||
@@ -920,6 +935,7 @@ impl Tool for ShapeTool {
|
||||
match &self.widget {
|
||||
Some(WidgetDrag::Corner(c)) => c.adjusting(),
|
||||
Some(WidgetDrag::Pie(d)) => d.adjusting(),
|
||||
Some(WidgetDrag::Sides(d)) => d.adjusting(),
|
||||
None => match &self.selection {
|
||||
Some(SelectionDrag::Move { began, .. }) => *began,
|
||||
Some(SelectionDrag::Rotate { .. } | SelectionDrag::Scale { .. }) => true,
|
||||
@@ -956,6 +972,7 @@ impl Tool for ShapeTool {
|
||||
match &self.widget {
|
||||
Some(WidgetDrag::Corner(c)) => return c.overlays(cx),
|
||||
Some(WidgetDrag::Pie(d)) => return d.overlays(cx),
|
||||
Some(WidgetDrag::Sides(d)) => return d.overlays(cx),
|
||||
None => {}
|
||||
}
|
||||
// A line on a common tangent shows that snap's guides, and its length and angle.
|
||||
@@ -1017,7 +1034,7 @@ impl Tool for ShapeTool {
|
||||
let idle = self.start.is_none();
|
||||
match &self.widget {
|
||||
Some(WidgetDrag::Corner(_)) => return Cursor::CornerRadius,
|
||||
Some(WidgetDrag::Pie(_)) => return Cursor::ArrowHollow,
|
||||
Some(WidgetDrag::Pie(_) | WidgetDrag::Sides(_)) => return Cursor::ArrowHollow,
|
||||
None => {}
|
||||
}
|
||||
// Alt-dragging the selection leaves a copy behind; otherwise the arrow, hollow while the
|
||||
|
||||
@@ -1309,6 +1309,114 @@ fn a_shape_tool_drags_the_selected_shapes_widgets() {
|
||||
assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, 200.0, 20.0)), vec![Action::Commit]);
|
||||
}
|
||||
|
||||
/// With a shape tool, a drag down on a selected live polygon's side widget adds sides instead of
|
||||
/// drawing, and Escape puts the count back; Line Segment draws from the widget.
|
||||
#[test]
|
||||
fn a_shape_tool_drags_a_polygons_side_widget() {
|
||||
use vectorcraft_doc::{Appearance, LiveShape, Node, NodeKind};
|
||||
let shape =
|
||||
LiveShape::Polygon { radius: 80.0, sides: 5, xf: Affine::translate((250.0, 250.0)), radii: vec![], kinds: vec![], radii_relative: false };
|
||||
let mut d = vectorcraft_doc::Document::new(500.0, 500.0);
|
||||
let (l, id) = (d.layers[0].id, d.alloc_id());
|
||||
let mut n = Node::path(id, shape.to_path(), Appearance::default_art());
|
||||
if let NodeKind::Path { live: slot, .. } = &mut n.kind {
|
||||
*slot = Some(Box::new(shape));
|
||||
}
|
||||
d.insert(Some(l), 0, n).unwrap();
|
||||
let mut s = Selection::default();
|
||||
s.add(id);
|
||||
let p = paint();
|
||||
let c = cx(&d, &s, &p);
|
||||
let (w, _) = crate::sidewidget::SideWidget::for_tool(&c).expect("a side widget");
|
||||
let down = |px: f64| PointerEvent::new(PointerKind::Drag, w.at.x, w.at.y + px);
|
||||
for tool in ["rectangle", "roundedRectangle", "ellipse", "polygon", "star"] {
|
||||
let mut t = ShapeTool::new(tool);
|
||||
assert_eq!(t.cursor(&c, w.at, Mods::default()), Cursor::ArrowHollow, "{tool}");
|
||||
assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, w.at.x, w.at.y)).is_empty(), "{tool}");
|
||||
let a = t.pointer(&c, &down(25.0));
|
||||
assert_eq!(
|
||||
a,
|
||||
vec![Action::Begin("Live Shape".into()), Action::Preview("object.setLiveShape".into(), json!({ "id": id.0, "sides": 7 }))],
|
||||
"{tool}"
|
||||
);
|
||||
assert!(t.transforming() && !t.drawing_boxed(), "{tool}");
|
||||
assert_eq!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, w.at.x, w.at.y + 25.0)), vec![Action::Commit], "{tool}");
|
||||
assert!(!t.busy(), "{tool}");
|
||||
t.pointer(&c, &PointerEvent::new(PointerKind::Down, w.at.x, w.at.y));
|
||||
t.pointer(&c, &down(-13.0));
|
||||
assert_eq!(t.key(&c, ToolKey::Escape, Mods::default()), vec![Action::Cancel], "{tool}");
|
||||
assert!(!t.busy(), "{tool}");
|
||||
}
|
||||
let mut t = ShapeTool::new("lineSegment");
|
||||
assert_eq!(t.cursor(&c, w.at, Mods::default()), Cursor::Crosshair);
|
||||
t.pointer(&c, &PointerEvent::new(PointerKind::Down, w.at.x, w.at.y));
|
||||
let a = t.pointer(&c, &down(25.0));
|
||||
assert!(matches!(a.last(), Some(Action::Preview(cmd, _)) if cmd == "shape.line"), "{a:?}");
|
||||
}
|
||||
|
||||
/// Switching away from a shape tool or the Selection tool during a drag of a corner, pie or side
|
||||
/// widget cancels it, as Escape does: the shape goes back. After a press that has not moved there
|
||||
/// is nothing to put back.
|
||||
#[test]
|
||||
fn a_tool_switch_cancels_a_widget_drag() {
|
||||
use vectorcraft_doc::{Appearance, LiveShape, Node, NodeKind};
|
||||
let live = |shape: LiveShape| {
|
||||
let mut d = vectorcraft_doc::Document::new(500.0, 500.0);
|
||||
let (l, id) = (d.layers[0].id, d.alloc_id());
|
||||
let mut n = Node::path(id, shape.to_path(), Appearance::default_art());
|
||||
if let NodeKind::Path { live: slot, .. } = &mut n.kind {
|
||||
*slot = Some(Box::new(shape));
|
||||
}
|
||||
d.insert(Some(l), 0, n).unwrap();
|
||||
let mut s = Selection::default();
|
||||
s.add(id);
|
||||
(d, s)
|
||||
};
|
||||
let xf = Affine::translate((100.0, 100.0));
|
||||
let rect = live(LiveShape::Rectangle { w: 100.0, h: 100.0, radii: [0.0; 4], kinds: Default::default(), radii_relative: false, xf });
|
||||
let ellipse = live(LiveShape::Ellipse { w: 200.0, h: 100.0, pie: (0.0, 360.0), xf });
|
||||
let polygon = live(LiveShape::Polygon {
|
||||
radius: 80.0,
|
||||
sides: 5,
|
||||
xf: Affine::translate((250.0, 250.0)),
|
||||
radii: vec![],
|
||||
kinds: vec![],
|
||||
radii_relative: false,
|
||||
});
|
||||
let p = paint();
|
||||
let side = crate::sidewidget::SideWidget::for_tool(&cx(&polygon.0, &polygon.1, &p)).expect("a side widget").0.at;
|
||||
// The corner widget at (110, 110), the pie widget 12 px right of (300, 150), the side widget.
|
||||
let drags = [
|
||||
(&rect, Point::new(110.0, 110.0), Point::new(130.0, 130.0)),
|
||||
(&ellipse, Point::new(312.0, 150.0), Point::new(200.0, 20.0)),
|
||||
(&polygon, side, side + Vec2::new(0.0, 25.0)),
|
||||
];
|
||||
for ((d, s), at, to) in drags {
|
||||
let c = cx(d, s, &p);
|
||||
let tools: [Box<dyn Tool>; 6] = [
|
||||
Box::new(crate::select::SelectionTool::default()),
|
||||
Box::new(ShapeTool::new("rectangle")),
|
||||
Box::new(ShapeTool::new("roundedRectangle")),
|
||||
Box::new(ShapeTool::new("ellipse")),
|
||||
Box::new(ShapeTool::new("polygon")),
|
||||
Box::new(ShapeTool::new("star")),
|
||||
];
|
||||
for mut t in tools {
|
||||
let id = t.id();
|
||||
assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Down, at.x, at.y)).is_empty(), "{id} at {at:?}");
|
||||
let a = t.pointer(&c, &PointerEvent::new(PointerKind::Drag, to.x, to.y));
|
||||
assert!(matches!(a.first(), Some(Action::Begin(_))), "{id} at {at:?}: {a:?}");
|
||||
assert_eq!(t.deactivate(&c), vec![Action::Cancel], "{id} at {at:?}");
|
||||
assert!(!t.busy() && !t.transforming(), "{id} at {at:?}");
|
||||
assert!(t.pointer(&c, &PointerEvent::new(PointerKind::Up, to.x, to.y)).is_empty(), "{id} at {at:?}");
|
||||
t.pointer(&c, &PointerEvent::new(PointerKind::Down, at.x, at.y));
|
||||
assert!(t.busy(), "{id} at {at:?}");
|
||||
assert!(t.deactivate(&c).is_empty(), "{id} at {at:?}");
|
||||
assert!(!t.busy(), "{id} at {at:?}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// A double-click on a corner widget of a selected live shape, with a shape tool that shows the
|
||||
/// widgets, asks for the Transform panel and nothing else: neither click draws, edits or begins an
|
||||
/// undo step, and the tool stays idle. Line Segment, a plain path, a pie widget, a hidden or
|
||||
|
||||
@@ -0,0 +1,432 @@
|
||||
//! The side widget: a small diamond beside the right side of a selected live polygon's bounding
|
||||
//! box (<https://helpx.adobe.com/illustrator/desktop/draw-shapes-and-paths/modify-live-shapes/add-or-remove-sides-from-polygons.html>).
|
||||
//! Dragging it down adds sides and dragging it up removes them, one side per [`STEP_PX`] screen
|
||||
//! pixels along the box's own vertical axis, from 3 to 11 sides. A polygon with more than 11
|
||||
//! sides keeps its count until the drag goes up a step, which gives it 11. The drag sends
|
||||
//! `object.setLiveShape`'s `sides` in one undo step, and none when the count ends where it began.
|
||||
//! The Selection tool and the shape tools that show the box hit the widget, and the canvas draws it
|
||||
//! from the same geometry.
|
||||
|
||||
use serde_json::json;
|
||||
use vectorcraft_doc::{Document, LiveShape, NodeId, NodeKind, OrientedBox, Selection};
|
||||
use vectorcraft_geom::Point;
|
||||
|
||||
use crate::select::shown_box;
|
||||
use crate::{Action, Overlay, PointerEvent, ToolContext};
|
||||
|
||||
/// The widget's center sits this far (screen px) outside the middle of the box's right side, clear
|
||||
/// of its handle.
|
||||
const OFFSET_PX: f64 = 16.0;
|
||||
/// Half the widget's diagonal (screen px), as the canvas draws it.
|
||||
pub const RADIUS_PX: f32 = 4.0;
|
||||
/// How near (screen px) the pointer must be to hit it.
|
||||
const HIT_PX: f64 = 5.0;
|
||||
/// How far (screen px) the pointer moves along the box's vertical axis per side.
|
||||
pub const STEP_PX: f64 = 12.0;
|
||||
/// The fewest sides a drag gives.
|
||||
pub const MIN_SIDES: u32 = 3;
|
||||
/// The most sides a drag gives.
|
||||
pub const MAX_SIDES: u32 = 11;
|
||||
|
||||
/// The side widget of a selection that is exactly one editable live polygon.
|
||||
#[derive(Clone, Copy, Debug, PartialEq)]
|
||||
pub struct SideWidget {
|
||||
pub id: NodeId,
|
||||
/// Center in document coordinates.
|
||||
pub at: Point,
|
||||
/// The polygon's side count.
|
||||
pub sides: u32,
|
||||
}
|
||||
|
||||
impl SideWidget {
|
||||
/// The widget beside `bx`, the selection's bounding box, at `zoom` (screen px per document
|
||||
/// point). None unless the selection is one whole editable live polygon, with no anchors or
|
||||
/// segments of it selected.
|
||||
pub fn of(doc: &Document, selection: &Selection, bx: &OrientedBox, zoom: f64) -> Option<Self> {
|
||||
let [id] = selection.objects[..] else { return None };
|
||||
if !selection.anchors.is_empty() || selection.segments.contains_key(&id) || !doc.is_editable(id) || !zoom.is_finite() || zoom <= 0.0 {
|
||||
return None;
|
||||
}
|
||||
let NodeKind::Path { live, .. } = &doc.node(id)?.kind else { return None };
|
||||
let Some(LiveShape::Polygon { sides, .. }) = live.as_deref() else { return None };
|
||||
let r = bx.rect;
|
||||
let at = bx.to_doc() * Point::new(r.x1 + OFFSET_PX / zoom, r.center().y);
|
||||
(at.x.is_finite() && at.y.is_finite()).then_some(Self { id, at, sides: *sides })
|
||||
}
|
||||
|
||||
/// The widget the tool can drag (its bounding box showing).
|
||||
pub fn for_tool(cx: &ToolContext) -> Option<(Self, OrientedBox)> {
|
||||
// One object or none: a larger selection's box is not measured.
|
||||
if cx.selection.objects.len() != 1 {
|
||||
return None;
|
||||
}
|
||||
let bx = shown_box(cx)?;
|
||||
Some((Self::of(cx.doc, cx.selection, &bx, cx.zoom)?, bx))
|
||||
}
|
||||
|
||||
/// The widget of `cx` and its box if the widget is under `p`.
|
||||
fn at(cx: &ToolContext, p: Point) -> Option<(Self, OrientedBox)> {
|
||||
Self::for_tool(cx).filter(|(w, _)| w.at.distance(p) <= cx.tol(HIT_PX))
|
||||
}
|
||||
}
|
||||
|
||||
/// Is `p` over the side widget?
|
||||
pub fn over_widget(cx: &ToolContext, p: Point) -> bool {
|
||||
SideWidget::at(cx, p).is_some()
|
||||
}
|
||||
|
||||
/// The side count a drag of `steps` (down positive) gives a polygon of `from` sides: within 3 to 11,
|
||||
/// and `from` itself while a polygon of more than 11 sides has not been dragged up.
|
||||
pub fn sides_after(from: u32, steps: i64) -> u32 {
|
||||
let (min, max) = (i64::from(MIN_SIDES), i64::from(MAX_SIDES));
|
||||
let to = if from <= MAX_SIDES {
|
||||
i64::from(from).saturating_add(steps)
|
||||
} else if steps >= 0 {
|
||||
return from;
|
||||
} else {
|
||||
(max + 1).saturating_add(steps)
|
||||
};
|
||||
to.clamp(min, max) as u32
|
||||
}
|
||||
|
||||
/// Dragging the side widget.
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct SideDrag {
|
||||
widget: SideWidget,
|
||||
bx: OrientedBox,
|
||||
start: Point,
|
||||
/// The pointer has left the click.
|
||||
moved: bool,
|
||||
/// The undo step has begun: the count has differed from the polygon's.
|
||||
began: bool,
|
||||
/// The count last sent (the polygon's until the drag changes it).
|
||||
sides: u32,
|
||||
at: Point,
|
||||
}
|
||||
|
||||
impl SideDrag {
|
||||
/// The drag has left the click.
|
||||
pub fn adjusting(&self) -> bool {
|
||||
self.moved
|
||||
}
|
||||
|
||||
/// Start a drag when the press `ev` is on the side widget of the selection.
|
||||
pub fn hit(cx: &ToolContext, ev: &PointerEvent) -> Option<Self> {
|
||||
let (widget, bx) = SideWidget::at(cx, ev.pos)?;
|
||||
Some(Self { widget, bx, start: ev.pos, moved: false, began: false, sides: widget.sides, at: ev.pos })
|
||||
}
|
||||
|
||||
/// A pointer position that is not finite leaves the count and the readout as they are. A drag
|
||||
/// too long to measure counts as the most steps in its direction.
|
||||
pub fn drag(&mut self, cx: &ToolContext, p: Point) -> Vec<Action> {
|
||||
if !p.x.is_finite() || !p.y.is_finite() {
|
||||
return vec![];
|
||||
}
|
||||
self.at = p;
|
||||
if !self.moved {
|
||||
if p.distance(self.start) < cx.tol(3.0) {
|
||||
return vec![];
|
||||
}
|
||||
self.moved = true;
|
||||
}
|
||||
let down = (self.bx.to_local(p).y - self.bx.to_local(self.start).y) * cx.zoom;
|
||||
let steps = (down / STEP_PX).trunc();
|
||||
if steps.is_nan() {
|
||||
return vec![];
|
||||
}
|
||||
// The cast saturates: an infinite count of steps becomes i64::MAX or i64::MIN.
|
||||
let sides = sides_after(self.widget.sides, steps as i64);
|
||||
if sides == self.sides {
|
||||
return vec![];
|
||||
}
|
||||
let mut out = vec![];
|
||||
if !self.began {
|
||||
self.began = true;
|
||||
out.push(Action::Begin("Live Shape".into()));
|
||||
}
|
||||
self.sides = sides;
|
||||
out.push(Action::Preview("object.setLiveShape".into(), json!({ "id": self.widget.id.0, "sides": sides })));
|
||||
out
|
||||
}
|
||||
|
||||
/// The release: one undo step when the count changed, and nothing kept when it came back.
|
||||
pub fn finish(self) -> Vec<Action> {
|
||||
match (self.began, self.sides == self.widget.sides) {
|
||||
(false, _) => vec![],
|
||||
(true, true) => vec![Action::Cancel],
|
||||
(true, false) => vec![Action::Commit],
|
||||
}
|
||||
}
|
||||
|
||||
/// Escape: the polygon keeps the count it had.
|
||||
pub fn cancel(self) -> Vec<Action> {
|
||||
if self.began { vec![Action::Cancel] } else { vec![] }
|
||||
}
|
||||
|
||||
/// The side count next to the pointer.
|
||||
pub fn overlays(&self, cx: &ToolContext) -> Vec<Overlay> {
|
||||
if !self.moved || !cx.measurement_labels {
|
||||
return vec![];
|
||||
}
|
||||
vec![Overlay::Measure { p: self.at, text: format!("Sides: {}", self.sides) }]
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::select::SelectionTool;
|
||||
use crate::testutil::*;
|
||||
use crate::{Cursor, Mods, PointerKind, Tool, ToolKey};
|
||||
use vectorcraft_doc::{Appearance, Node};
|
||||
use vectorcraft_geom::Affine;
|
||||
|
||||
/// A document holding a live polygon of `sides` sides and radius 100 placed by `xf`, and a
|
||||
/// selection of it.
|
||||
fn polygon_doc(sides: u32, xf: Affine) -> (Document, NodeId, Selection) {
|
||||
let live = LiveShape::Polygon { radius: 100.0, sides, xf, radii: vec![], kinds: vec![], radii_relative: false };
|
||||
let mut d = Document::new(800.0, 800.0);
|
||||
let l = d.layers[0].id;
|
||||
let id = d.alloc_id();
|
||||
let mut n = Node::path(id, live.to_path(), Appearance::default_art());
|
||||
if let NodeKind::Path { live: slot, .. } = &mut n.kind {
|
||||
*slot = Some(Box::new(live));
|
||||
}
|
||||
d.insert(Some(l), 0, n).unwrap();
|
||||
let mut s = Selection::default();
|
||||
s.add(id);
|
||||
(d, id, s)
|
||||
}
|
||||
|
||||
fn ev(kind: PointerKind, p: Point) -> PointerEvent {
|
||||
PointerEvent::new(kind, p.x, p.y)
|
||||
}
|
||||
|
||||
fn sides_of(a: &[Action]) -> Vec<u64> {
|
||||
a.iter().filter_map(|a| if let Action::Preview(_, v) = a { v["sides"].as_u64() } else { None }).collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_counts_stay_within_three_and_eleven() {
|
||||
assert_eq!(sides_after(5, 1), 6);
|
||||
assert_eq!(sides_after(5, -1), 4);
|
||||
assert_eq!(sides_after(5, 100), 11);
|
||||
assert_eq!(sides_after(5, -100), 3);
|
||||
assert_eq!(sides_after(3, -1), 3);
|
||||
assert_eq!(sides_after(11, 1), 11);
|
||||
// Over 11: unchanged until the drag goes up, which gives 11, then 10.
|
||||
assert_eq!(sides_after(40, 0), 40);
|
||||
assert_eq!(sides_after(40, 5), 40);
|
||||
assert_eq!(sides_after(40, -1), 11);
|
||||
assert_eq!(sides_after(40, -2), 10);
|
||||
assert_eq!(sides_after(1000, -100), 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_longest_drags_stay_within_three_and_eleven() {
|
||||
assert_eq!(sides_after(5, i64::MAX), 11);
|
||||
assert_eq!(sides_after(5, i64::MIN), 3);
|
||||
assert_eq!(sides_after(3, i64::MAX), 11);
|
||||
assert_eq!(sides_after(11, i64::MAX), 11);
|
||||
assert_eq!(sides_after(11, i64::MIN), 3);
|
||||
assert_eq!(sides_after(40, i64::MAX), 40);
|
||||
assert_eq!(sides_after(40, i64::MIN), 3);
|
||||
}
|
||||
|
||||
/// A drag far past the document, even one too long to measure, stops at 11 down and 3 up; a
|
||||
/// pointer position that is not finite keeps the count it had.
|
||||
#[test]
|
||||
fn a_huge_or_invalid_drag_stays_within_three_and_eleven() {
|
||||
let (d, _, s) = polygon_doc(5, Affine::translate((300.0, 300.0)));
|
||||
let p = paint();
|
||||
// At zoom 1 the step count is finite and past i64; at zoom 4 the distance itself is infinite.
|
||||
for zoom in [1.0, 4.0] {
|
||||
let c = ToolContext { zoom, ..cx(&d, &s, &p) };
|
||||
let (w, _) = SideWidget::for_tool(&c).unwrap();
|
||||
let far = |y: f64| Point::new(w.at.x, y);
|
||||
let mut t = SelectionTool::default();
|
||||
t.pointer(&c, &ev(PointerKind::Down, w.at));
|
||||
assert_eq!(sides_of(&t.pointer(&c, &ev(PointerKind::Drag, far(1e308)))), [11], "zoom {zoom}");
|
||||
assert_eq!(sides_of(&t.pointer(&c, &ev(PointerKind::Drag, far(-1e308)))), [3], "zoom {zoom}");
|
||||
assert_eq!(t.pointer(&c, &ev(PointerKind::Up, far(-1e308))), vec![Action::Commit]);
|
||||
}
|
||||
let c = cx(&d, &s, &p);
|
||||
let (w, _) = SideWidget::for_tool(&c).unwrap();
|
||||
let mut t = SelectionTool::default();
|
||||
t.pointer(&c, &ev(PointerKind::Down, w.at));
|
||||
let shown = w.at + vectorcraft_geom::Vec2::new(0.0, 24.0);
|
||||
assert_eq!(sides_of(&t.pointer(&c, &ev(PointerKind::Drag, shown))), [7]);
|
||||
for bad in [Point::new(f64::NAN, w.at.y), Point::new(w.at.x, f64::INFINITY), Point::new(w.at.x, f64::NEG_INFINITY)] {
|
||||
assert!(t.pointer(&c, &ev(PointerKind::Drag, bad)).is_empty(), "{bad:?}");
|
||||
}
|
||||
assert!(t.overlays(&c).iter().any(|o| matches!(o, Overlay::Measure { p, text } if *p == shown && text == "Sides: 7")));
|
||||
assert_eq!(t.pointer(&c, &ev(PointerKind::Up, shown)), vec![Action::Commit]);
|
||||
}
|
||||
|
||||
/// The widget sits 16 px right of the middle of the box's right side, at any zoom; only one
|
||||
/// whole editable live polygon shows it.
|
||||
#[test]
|
||||
fn one_whole_live_polygon_shows_the_widget() {
|
||||
let (d, id, s) = polygon_doc(6, Affine::translate((300.0, 300.0)));
|
||||
let p = paint();
|
||||
let c = cx(&d, &s, &p);
|
||||
let (w, bx) = SideWidget::for_tool(&c).expect("a widget");
|
||||
assert_eq!((w.id, w.sides), (id, 6));
|
||||
let want = |zoom: f64| Point::new(bx.rect.x1 + 16.0 / zoom, bx.rect.center().y);
|
||||
assert!(w.at.distance(want(1.0)) < 1e-9, "{w:?} {bx:?}");
|
||||
assert!(SideWidget::of(&d, &s, &bx, 4.0).unwrap().at.distance(want(4.0)) < 1e-9);
|
||||
assert!(over_widget(&c, w.at) && !over_widget(&c, w.at + vectorcraft_geom::Vec2::new(0.0, 8.0)));
|
||||
// Hidden with the bounding box hidden, with an anchor or segment selected, or with no zoom.
|
||||
assert!(SideWidget::for_tool(&ToolContext { show_bbox: false, ..cx(&d, &s, &p) }).is_none());
|
||||
let mut part = s.clone();
|
||||
part.segments.insert(id, Default::default());
|
||||
assert!(SideWidget::of(&d, &part, &bx, 1.0).is_none());
|
||||
assert!(SideWidget::of(&d, &s, &bx, 0.0).is_none() && SideWidget::of(&d, &s, &bx, f64::NAN).is_none());
|
||||
// A locked polygon, two polygons, nothing or a plain path: none.
|
||||
let mut locked = d.clone();
|
||||
locked.node_mut(id).unwrap().locked = true;
|
||||
assert!(SideWidget::of(&locked, &s, &bx, 1.0).is_none());
|
||||
let mut two = d.clone();
|
||||
let other = two.alloc_id();
|
||||
let mut n = two.node(id).unwrap().clone();
|
||||
n.id = other;
|
||||
let l = two.layers[0].id;
|
||||
two.insert(Some(l), 0, n).unwrap();
|
||||
let mut both = s.clone();
|
||||
both.add(other);
|
||||
assert!(SideWidget::of(&two, &both, &bx, 1.0).is_none());
|
||||
assert!(SideWidget::of(&d, &Selection::default(), &bx, 1.0).is_none());
|
||||
let (d, rect) = doc_with_rect();
|
||||
let mut s = Selection::default();
|
||||
s.add(rect);
|
||||
let bx = OrientedBox::aligned(vectorcraft_geom::Rect::new(0.0, 0.0, 10.0, 10.0));
|
||||
assert!(SideWidget::of(&d, &s, &bx, 1.0).is_none());
|
||||
}
|
||||
|
||||
/// With the Selection tool, dragging the widget down adds a side per 12 screen px and up removes
|
||||
/// them, within 3 to 11, in one undo step with the count shown next to the pointer.
|
||||
#[test]
|
||||
fn dragging_the_widget_changes_the_sides() {
|
||||
let (d, id, s) = polygon_doc(5, Affine::translate((300.0, 300.0)));
|
||||
let p = paint();
|
||||
for zoom in [1.0, 2.0] {
|
||||
let c = ToolContext { zoom, ..cx(&d, &s, &p) };
|
||||
let (w, _) = SideWidget::for_tool(&c).unwrap();
|
||||
let at = |px: f64| w.at + vectorcraft_geom::Vec2::new(0.0, px / zoom);
|
||||
let mut t = SelectionTool::default();
|
||||
assert_eq!(t.cursor(&c, w.at, Mods::default()), Cursor::ArrowHollow);
|
||||
assert!(t.pointer(&c, &ev(PointerKind::Down, w.at)).is_empty());
|
||||
// Past the click but short of a step: nothing yet.
|
||||
assert!(t.pointer(&c, &ev(PointerKind::Drag, at(6.0))).is_empty());
|
||||
assert!(t.transforming());
|
||||
let a = t.pointer(&c, &ev(PointerKind::Drag, at(12.0)));
|
||||
assert_eq!(a[0], Action::Begin("Live Shape".into()));
|
||||
assert_eq!(a[1], Action::Preview("object.setLiveShape".into(), json!({ "id": id.0, "sides": 6 })));
|
||||
assert!(t.overlays(&c).iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text == "Sides: 6")));
|
||||
// The same count again sends nothing; far down stops at 11, far up at 3.
|
||||
assert!(t.pointer(&c, &ev(PointerKind::Drag, at(20.0))).is_empty());
|
||||
assert_eq!(sides_of(&t.pointer(&c, &ev(PointerKind::Drag, at(500.0)))), [11]);
|
||||
assert_eq!(sides_of(&t.pointer(&c, &ev(PointerKind::Drag, at(-500.0)))), [3]);
|
||||
assert_eq!(t.pointer(&c, &ev(PointerKind::Up, at(-500.0))), vec![Action::Commit]);
|
||||
assert!(!t.busy() && !t.transforming());
|
||||
}
|
||||
// A click sends nothing, and the readout follows Measurement Labels.
|
||||
let c = cx(&d, &s, &p);
|
||||
let (w, _) = SideWidget::for_tool(&c).unwrap();
|
||||
let mut t = SelectionTool::default();
|
||||
assert!(t.pointer(&c, &ev(PointerKind::Down, w.at)).is_empty());
|
||||
assert!(t.pointer(&c, &ev(PointerKind::Up, w.at)).is_empty());
|
||||
t.pointer(&c, &ev(PointerKind::Down, w.at));
|
||||
t.pointer(&c, &ev(PointerKind::Drag, w.at + vectorcraft_geom::Vec2::new(0.0, 13.0)));
|
||||
let quiet = ToolContext { measurement_labels: false, ..cx(&d, &s, &p) };
|
||||
assert!(!t.overlays(&quiet).iter().any(|o| matches!(o, Overlay::Measure { .. })));
|
||||
// Back at the start: the release keeps nothing.
|
||||
assert_eq!(sides_of(&t.pointer(&c, &ev(PointerKind::Drag, w.at))), [5]);
|
||||
assert_eq!(t.pointer(&c, &ev(PointerKind::Up, w.at)), vec![Action::Cancel]);
|
||||
}
|
||||
|
||||
/// On a turned polygon the drag is read along the box's own vertical axis.
|
||||
#[test]
|
||||
fn a_turned_polygon_reads_the_drag_along_its_box() {
|
||||
let xf = Affine::translate((400.0, 400.0)) * Affine::rotate(std::f64::consts::FRAC_PI_2);
|
||||
let (d, _, s) = polygon_doc(5, xf);
|
||||
let p = paint();
|
||||
let c = cx(&d, &s, &p);
|
||||
let (w, bx) = SideWidget::for_tool(&c).unwrap();
|
||||
let down = bx.to_doc() * Point::new(0.0, 1.0) - bx.to_doc() * Point::ZERO;
|
||||
let mut t = SelectionTool::default();
|
||||
t.pointer(&c, &ev(PointerKind::Down, w.at));
|
||||
assert_eq!(sides_of(&t.pointer(&c, &ev(PointerKind::Drag, w.at + down * 25.0))), [7], "{bx:?}");
|
||||
assert_eq!(sides_of(&t.pointer(&c, &ev(PointerKind::Drag, w.at - down * 13.0))), [4]);
|
||||
}
|
||||
|
||||
/// A double-click on the widget with the Selection tool does nothing: in isolation mode it does
|
||||
/// not leave isolation, though no art is under the widget.
|
||||
#[test]
|
||||
fn a_double_click_on_the_widget_does_nothing() {
|
||||
let live = LiveShape::Polygon {
|
||||
radius: 100.0,
|
||||
sides: 5,
|
||||
xf: Affine::translate((300.0, 300.0)),
|
||||
radii: vec![],
|
||||
kinds: vec![],
|
||||
radii_relative: false,
|
||||
};
|
||||
let mut d = Document::new(800.0, 800.0);
|
||||
let l = d.layers[0].id;
|
||||
let id = d.alloc_id();
|
||||
let mut n = Node::path(id, live.to_path(), Appearance::default_art());
|
||||
if let NodeKind::Path { live: slot, .. } = &mut n.kind {
|
||||
*slot = Some(Box::new(live));
|
||||
}
|
||||
let group = d.alloc_id();
|
||||
d.insert(Some(l), 0, Node::group(group, vec![std::sync::Arc::new(n)])).unwrap();
|
||||
let mut s = Selection::default();
|
||||
s.add(id);
|
||||
let p = paint();
|
||||
let c = ToolContext { isolation: Some(group), ..cx(&d, &s, &p) };
|
||||
let (w, _) = SideWidget::for_tool(&c).unwrap();
|
||||
assert!(vectorcraft_doc::hit::hit_test(&d, w.at, c.hit_options()).is_none());
|
||||
let mut t = SelectionTool::default();
|
||||
assert!(t.pointer(&c, &ev(PointerKind::DoubleClick, w.at)).is_empty());
|
||||
// Away from the widget and the art, the double-click leaves isolation.
|
||||
let away = w.at + vectorcraft_geom::Vec2::new(40.0, 0.0);
|
||||
assert_eq!(t.pointer(&c, &ev(PointerKind::DoubleClick, away)), vec![Action::Exec("object.exitIsolation".into(), json!({}))]);
|
||||
}
|
||||
|
||||
/// A polygon of more than 11 sides keeps its count on a press and a drag down; the first step
|
||||
/// up gives 11.
|
||||
#[test]
|
||||
fn a_polygon_over_eleven_sides_does_not_jump() {
|
||||
let (d, _, s) = polygon_doc(40, Affine::translate((300.0, 300.0)));
|
||||
let p = paint();
|
||||
let c = cx(&d, &s, &p);
|
||||
let (w, _) = SideWidget::for_tool(&c).unwrap();
|
||||
let mut t = SelectionTool::default();
|
||||
assert!(t.pointer(&c, &ev(PointerKind::Down, w.at)).is_empty());
|
||||
assert!(t.pointer(&c, &ev(PointerKind::Drag, w.at + vectorcraft_geom::Vec2::new(0.0, 40.0))).is_empty());
|
||||
assert!(t.pointer(&c, &ev(PointerKind::Up, w.at + vectorcraft_geom::Vec2::new(0.0, 40.0))).is_empty());
|
||||
t.pointer(&c, &ev(PointerKind::Down, w.at));
|
||||
let a = t.pointer(&c, &ev(PointerKind::Drag, w.at - vectorcraft_geom::Vec2::new(0.0, 12.0)));
|
||||
assert_eq!(a[0], Action::Begin("Live Shape".into()));
|
||||
assert_eq!(sides_of(&a), [11]);
|
||||
assert!(t.overlays(&c).iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text == "Sides: 11")));
|
||||
assert_eq!(sides_of(&t.pointer(&c, &ev(PointerKind::Drag, w.at - vectorcraft_geom::Vec2::new(0.0, 24.0)))), [10]);
|
||||
}
|
||||
|
||||
/// Escape during a drag puts the count back; the release after it sends nothing.
|
||||
#[test]
|
||||
fn escape_cancels_a_side_widget_drag() {
|
||||
let (d, _, s) = polygon_doc(5, Affine::translate((300.0, 300.0)));
|
||||
let p = paint();
|
||||
let c = cx(&d, &s, &p);
|
||||
let (w, _) = SideWidget::for_tool(&c).unwrap();
|
||||
let mut t = SelectionTool::default();
|
||||
t.pointer(&c, &ev(PointerKind::Down, w.at));
|
||||
t.pointer(&c, &ev(PointerKind::Drag, w.at + vectorcraft_geom::Vec2::new(0.0, 30.0)));
|
||||
assert_eq!(t.key(&c, ToolKey::Escape, Mods::default()), vec![Action::Cancel]);
|
||||
assert!(!t.busy() && !t.transforming());
|
||||
assert!(!t.overlays(&c).iter().any(|o| matches!(o, Overlay::Measure { .. })));
|
||||
assert!(t.pointer(&c, &ev(PointerKind::Up, w.at)).is_empty());
|
||||
}
|
||||
}
|
||||
@@ -43,10 +43,13 @@ use vectorcraft_text::{FontDb, TextLayout, edit};
|
||||
use crate::guides::DrawSnap;
|
||||
use crate::{Action, Cursor, ImeSurrounding, Mods, Overlay, PointerEvent, PointerKind, SurroundingUnit, Tool, ToolContext, ToolKey};
|
||||
|
||||
mod missing;
|
||||
mod plain;
|
||||
mod ports;
|
||||
mod tool;
|
||||
|
||||
pub use missing::MISSING_FONT_EDIT;
|
||||
use missing::PendingEdit;
|
||||
#[cfg(test)]
|
||||
use plain::char_range_to_bytes;
|
||||
use plain::common_affixes;
|
||||
@@ -228,6 +231,8 @@ pub struct TypeTool {
|
||||
stepped: bool,
|
||||
/// The state at the start of each `command.batch` still running, innermost last.
|
||||
batches: Vec<HistoryState>,
|
||||
/// The edit of type set in fonts that aren't available whose question is open ([`missing`]).
|
||||
pending_edit: Option<PendingEdit>,
|
||||
cache: Mutex<Option<CachedLayout>>,
|
||||
/// The other frames' layouts the last overlays drew ([`FrameLayouts`]): each overlays call
|
||||
/// keeps only the frames it draws.
|
||||
@@ -815,18 +820,68 @@ impl TypeTool {
|
||||
|
||||
/// Start editing the type under `p` with the caret there → the actions (ending the previous
|
||||
/// edit, selecting the type); None when no type is under `p`. A click among the characters
|
||||
/// edits them, whatever Type Object Selection by Path Only says.
|
||||
/// edits them, whatever Type Object Selection by Path Only says. When the story of that type is
|
||||
/// drawn in a font that isn't available as named and is not the story being edited, nothing
|
||||
/// starts yet: the action asks the UI to open the [`MISSING_FONT_EDIT`] question, and OK starts
|
||||
/// the edit ([`Self::resume_edit`]).
|
||||
fn edit_at(&mut self, cx: &ToolContext, p: Point) -> Option<Vec<Action>> {
|
||||
self.pending_edit = None;
|
||||
let h = hit_test(cx.doc, p, vectorcraft_doc::hit::HitOptions { type_path_only: false, ..cx.hit_options() })?;
|
||||
let Some(NodeKind::Text(t)) = cx.doc.node(h.leaf).map(|n| &n.kind) else { return None };
|
||||
let lay = self.layout(t);
|
||||
let byte = vectorcraft_text::hit_byte(&lay, t.xf.inverse() * p);
|
||||
let same_story = self.editing.is_some_and(|e| cx.doc.story_of(e).contains(&h.leaf));
|
||||
if !same_story {
|
||||
let fonts = missing::unavailable_fonts(cx.doc, h.leaf);
|
||||
if !fonts.0.is_empty() {
|
||||
let token = next_edit_session();
|
||||
self.pending_edit = Some(PendingEdit { token, revision: cx.revision, id: h.leaf, byte, accepted: false });
|
||||
self.clicks = (None, 0);
|
||||
return Some(vec![Action::Dialog(MISSING_FONT_EDIT.into(), missing::question(token, h.leaf, &fonts))]);
|
||||
}
|
||||
}
|
||||
Some(self.begin_edit(cx, h.leaf, byte, p))
|
||||
}
|
||||
|
||||
/// End the previous edit and edit type `id` with the caret at `byte` (clicked at `p`), selecting
|
||||
/// it → the actions.
|
||||
fn begin_edit(&mut self, cx: &ToolContext, id: NodeId, byte: usize, p: Point) -> Vec<Action> {
|
||||
let mut out = self.finish(cx);
|
||||
self.start_editing(h.leaf, byte);
|
||||
self.start_editing(id, byte);
|
||||
self.remember(cx);
|
||||
self.clicks = (Some(p), 1);
|
||||
out.push(Action::Exec("select.set".into(), json!({"ids": [h.leaf.0]})));
|
||||
Some(out)
|
||||
out.push(Action::Exec("select.set".into(), json!({"ids": [id.0]})));
|
||||
out
|
||||
}
|
||||
|
||||
/// The answer to the [`MISSING_FONT_EDIT`] question whose token is `token`: OK (`ok`) lets the
|
||||
/// next [`Tool::poll`] start the edit, Cancel forgets it. An answer to another question is
|
||||
/// ignored.
|
||||
fn answer_edit(&mut self, token: u64, ok: bool) {
|
||||
let Some(e) = self.pending_edit.as_mut().filter(|e| e.token == token) else { return };
|
||||
if ok {
|
||||
e.accepted = true;
|
||||
} else {
|
||||
self.pending_edit = None;
|
||||
}
|
||||
}
|
||||
|
||||
/// Start the edit OK accepted: the caret goes where the type was clicked. Nothing starts when
|
||||
/// the document changed since the question, or the type is gone.
|
||||
fn resume_edit(&mut self, cx: &ToolContext) -> Vec<Action> {
|
||||
let Some(e) = self.pending_edit.take_if(|e| e.accepted) else { return vec![] };
|
||||
if e.revision != cx.revision {
|
||||
return vec![];
|
||||
}
|
||||
let Some(t) = Self::text(cx, e.id) else { return vec![] };
|
||||
let text = t.plain_text();
|
||||
let mut byte = e.byte.min(text.len());
|
||||
while !text.is_char_boundary(byte) {
|
||||
byte -= 1;
|
||||
}
|
||||
let out = self.begin_edit(cx, e.id, byte, Point::ZERO);
|
||||
self.clicks = (None, 0);
|
||||
out
|
||||
}
|
||||
|
||||
/// The button released after a press at `start` (new type goes at `at`). While type is being
|
||||
|
||||
@@ -0,0 +1,83 @@
|
||||
//! Type set in fonts that aren't available as named asks before it is edited: a click or a
|
||||
//! double-click that would start editing it opens a question ([`MISSING_FONT_EDIT`]) instead, and
|
||||
//! editing starts at the clicked place only after OK (the tool option `missingFontEdit`). The
|
||||
//! fonts are those `text.missingFonts` reads, for the story of the type clicked only.
|
||||
|
||||
use std::collections::BTreeSet;
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::{Document, NodeId, NodeKind, TextRun};
|
||||
use vectorcraft_text::{FontDb, FontMatch};
|
||||
|
||||
/// The dialog kind of the question, with the fields `token`, `id`, `missing` and `style` (lists of
|
||||
/// "family style" names) and `more` (how many more fonts the lists leave out).
|
||||
pub const MISSING_FONT_EDIT: &str = "missingFontEdit";
|
||||
|
||||
/// The most fonts the question names.
|
||||
const LISTED: usize = 8;
|
||||
|
||||
/// The longest family or style name checked (bytes), as `text.missingFonts` reads them.
|
||||
const MAX_NAME: usize = 256;
|
||||
|
||||
/// An edit of type set in fonts that aren't available, waiting for the answer to its question.
|
||||
#[derive(Clone, Debug, PartialEq)]
|
||||
pub(super) struct PendingEdit {
|
||||
/// The question's token, which its answer names.
|
||||
pub token: u64,
|
||||
/// The document (its uid) and its revision when the question was asked: an answer to a
|
||||
/// document since changed starts no editing.
|
||||
pub revision: (u64, u64),
|
||||
/// The type clicked, and the caret's byte offset there.
|
||||
pub id: NodeId,
|
||||
pub byte: usize,
|
||||
/// OK was chosen: the next [`crate::Tool::poll`] starts editing.
|
||||
pub accepted: bool,
|
||||
}
|
||||
|
||||
/// The fonts (family, style) run `r` is drawn in: its own, or, set in a composite font, those of
|
||||
/// the parts its characters fall in. An inline graphic and an empty run draw no glyphs.
|
||||
fn run_fonts(db: &FontDb, r: &TextRun) -> Vec<(String, String)> {
|
||||
if r.inline.is_some() || r.text.is_empty() {
|
||||
return vec![];
|
||||
}
|
||||
db.composite_fonts_for(&r.style.font_family, &r.text).unwrap_or_else(|| vec![(r.style.font_family.clone(), r.style.font_style.clone())])
|
||||
}
|
||||
|
||||
/// The fonts that the story of type object `id` ([`Document::story_of`]: every frame threaded with
|
||||
/// it) is drawn in and that aren't available as named, each once, in the order first used, with how
|
||||
/// they resolve ([`FontMatch::Missing`] or [`FontMatch::Style`]); at most [`LISTED`], with how many
|
||||
/// more there are. CSS generic families and names longer than 256 bytes are left out, as
|
||||
/// `text.missingFonts` leaves them out.
|
||||
pub(super) fn unavailable_fonts(doc: &Document, id: NodeId) -> (Vec<(String, String, FontMatch)>, usize) {
|
||||
let db = FontDb::global();
|
||||
let mut seen = BTreeSet::new();
|
||||
let mut listed = Vec::new();
|
||||
let mut more = 0;
|
||||
for frame in doc.story_of(id) {
|
||||
let Some(NodeKind::Text(t)) = doc.node(frame).map(|n| &n.kind) else { continue };
|
||||
for (family, style) in t.runs.iter().flat_map(|r| run_fonts(db, r)) {
|
||||
if family.trim().is_empty() || vectorcraft_text::is_generic_family(&family) || family.len() > MAX_NAME || style.len() > MAX_NAME {
|
||||
continue;
|
||||
}
|
||||
if !seen.insert((family.clone(), style.clone())) {
|
||||
continue;
|
||||
}
|
||||
let found = db.resolve(&family, &style).map_or(FontMatch::Missing, |(_, m)| m);
|
||||
if found == FontMatch::Exact {
|
||||
continue;
|
||||
}
|
||||
if listed.len() < LISTED {
|
||||
listed.push((family, style, found));
|
||||
} else {
|
||||
more += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
(listed, more)
|
||||
}
|
||||
|
||||
/// The question's fields for `fonts` ([`unavailable_fonts`]) and the edit `token` of type `id`.
|
||||
pub(super) fn question(token: u64, id: NodeId, (fonts, more): &(Vec<(String, String, FontMatch)>, usize)) -> Value {
|
||||
let names = |m: FontMatch| fonts.iter().filter(|f| f.2 == m).map(|(family, style, _)| format!("{family} {style}")).collect::<Vec<_>>();
|
||||
json!({"token": token, "id": id.0, "missing": names(FontMatch::Missing), "style": names(FontMatch::Style), "more": more})
|
||||
}
|
||||
@@ -1327,6 +1327,7 @@ fn area_type_drag_measure_labels_honor_preference() {
|
||||
|
||||
#[test]
|
||||
fn layout_cache_follows_fonts_added_later() {
|
||||
let _inputs = crate::testutil::changing_layout_inputs();
|
||||
// Other tests can load system fonts; this assertion needs its own process-wide database.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if std::env::var("VECTORCRAFT_FONT_CACHE_TEST_CHILD").as_deref() != Ok("1") {
|
||||
@@ -1542,6 +1543,7 @@ fn selected_type_shows_its_ports_in_each_state() {
|
||||
/// Preferences › Hyphenation › Exceptions change, the selected type is laid out again.
|
||||
#[test]
|
||||
fn the_out_port_follows_the_hyphenation_exceptions() {
|
||||
let _inputs = crate::testutil::changing_layout_inputs();
|
||||
struct Clear;
|
||||
impl Drop for Clear {
|
||||
fn drop(&mut self) {
|
||||
@@ -1690,6 +1692,7 @@ const OVERFLOWS: &str = "This text is far too long to fit in a frame of one hund
|
||||
/// overlays as a tool that lays every frame out afresh.
|
||||
#[test]
|
||||
fn type_overlays_keep_the_selected_frames_layouts() {
|
||||
let _inputs = crate::testutil::steady_layout_inputs();
|
||||
let (d, ids) = area_frames(&["One", "Two words", "Three words here", OVERFLOWS]);
|
||||
let (mut sel, p) = (Selection::default(), paint());
|
||||
sel.set(ids.iter().copied());
|
||||
@@ -1721,6 +1724,7 @@ fn type_overlays_keep_the_selected_frames_layouts() {
|
||||
/// out again on the next frame.
|
||||
#[test]
|
||||
fn type_overlays_keep_a_selected_storys_layouts() {
|
||||
let _inputs = crate::testutil::steady_layout_inputs();
|
||||
let (mut d, ids) = area_frames(&["Story one ", "story two ", "story three ", "story four"]);
|
||||
d.text_threads.push(ids.clone());
|
||||
let (mut sel, p) = (Selection::default(), paint());
|
||||
@@ -1749,6 +1753,7 @@ fn type_overlays_keep_a_selected_storys_layouts() {
|
||||
/// longer drawn is dropped, and choosing another tool drops them all.
|
||||
#[test]
|
||||
fn type_overlays_lay_out_again_only_the_frames_that_changed() {
|
||||
let _inputs = crate::testutil::steady_layout_inputs();
|
||||
let (mut d, ids) = area_frames(&["One", "Two", "Three", OVERFLOWS]);
|
||||
let (mut sel, p) = (Selection::default(), paint());
|
||||
sel.set(ids.iter().copied());
|
||||
@@ -1786,6 +1791,7 @@ fn type_overlays_lay_out_again_only_the_frames_that_changed() {
|
||||
/// each call, and draws what laying every frame out afresh draws.
|
||||
#[test]
|
||||
fn type_overlays_keep_at_most_frame_layouts_max() {
|
||||
let _inputs = crate::testutil::steady_layout_inputs();
|
||||
let texts = vec!["a "; FRAME_LAYOUTS_MAX + 3];
|
||||
let (mut d, ids) = area_frames(&texts);
|
||||
d.text_threads.push(ids.clone());
|
||||
@@ -1806,6 +1812,7 @@ fn type_overlays_keep_at_most_frame_layouts_max() {
|
||||
|
||||
#[test]
|
||||
fn frame_layouts_follow_fonts_and_hyphenation_exceptions() {
|
||||
let _inputs = crate::testutil::changing_layout_inputs();
|
||||
// Other tests can load system fonts; this assertion needs its own process-wide database.
|
||||
#[cfg(not(target_arch = "wasm32"))]
|
||||
if std::env::var("VECTORCRAFT_FONT_CACHE_TEST_CHILD").as_deref() != Ok("1") {
|
||||
@@ -1848,6 +1855,7 @@ fn frame_layouts_follow_fonts_and_hyphenation_exceptions() {
|
||||
#[test]
|
||||
#[ignore = "timing, run by hand"]
|
||||
fn type_overlays_timing() {
|
||||
let _inputs = crate::testutil::steady_layout_inputs();
|
||||
use std::time::Instant;
|
||||
let words = "The quick brown fox jumps over the lazy dog while seven wizards box. ".repeat(6);
|
||||
let texts: Vec<String> = (0..200).map(|i| format!("{i} {words}")).collect();
|
||||
@@ -2163,3 +2171,157 @@ fn soft_return_in_a_list_item_keeps_tab_within_the_paragraph() {
|
||||
let acts = key(&mut tool, &d, ToolKey::Tab, Mods::default());
|
||||
assert!(acts.iter().any(|a| matches!(a, Action::Exec(cmd, p) if cmd == "text.setFormat" && p["listLevel"] == 2)));
|
||||
}
|
||||
|
||||
/// A family no computer has.
|
||||
const NO_SUCH_FAMILY: &str = "Missing Test Family 7258";
|
||||
|
||||
/// Point type at (x, 100) whose runs are `runs` (text, family, style).
|
||||
fn add_styled_text(d: &mut Document, x: f64, runs: &[(&str, &str, &str)]) -> NodeId {
|
||||
let id = d.alloc_id();
|
||||
let style =
|
||||
|family: &str, font_style: &str| CharStyle { size: 20.0, font_family: family.into(), font_style: font_style.into(), ..Default::default() };
|
||||
let mut t = TextObject::point(Point::new(x, 100.0), "", style(runs[0].1, runs[0].2));
|
||||
t.runs = runs.iter().map(|(text, family, font_style)| TextRun::new(*text, style(family, font_style))).collect();
|
||||
d.insert(Some(d.layers[0].id), 0, Node::new(id, NodeKind::Text(Box::new(t)))).unwrap();
|
||||
id
|
||||
}
|
||||
|
||||
/// Where the caret before byte `b` of type `id` is drawn (document space).
|
||||
fn caret_at(c: &ToolContext, id: NodeId, b: usize) -> Point {
|
||||
let t = TypeTool::text(c, id).unwrap();
|
||||
let lay = vectorcraft_text::layout(FontDb::global(), t);
|
||||
let (a, bb) = vectorcraft_text::caret_position(&lay, b);
|
||||
let at = t.xf * a.midpoint(bb);
|
||||
Point::new(at.x + 0.1, at.y)
|
||||
}
|
||||
|
||||
/// The question a click asked → its token and fields.
|
||||
fn asked(acts: &[Action]) -> (u64, Value) {
|
||||
match acts {
|
||||
[Action::Dialog(kind, p)] if kind == MISSING_FONT_EDIT => (p["token"].as_u64().unwrap(), p.clone()),
|
||||
_ => panic!("expected only the missing-font question: {acts:?}"),
|
||||
}
|
||||
}
|
||||
|
||||
/// A click on type set in a family that isn't available asks first and starts no edit; OK starts
|
||||
/// it with the caret where the type was clicked, and the font the type names stays as it is.
|
||||
#[test]
|
||||
fn a_click_on_type_in_a_missing_font_asks_before_editing() {
|
||||
let mut d = Document::new(500.0, 500.0);
|
||||
let id = add_styled_text(&mut d, 100.0, &[("Hello", NO_SUCH_FAMILY, "Regular")]);
|
||||
let mut tool = TypeTool::new("type");
|
||||
let (sel, p) = (Selection::default(), paint());
|
||||
let c = cx(&d, &sel, &p);
|
||||
let at = caret_at(&c, id, 3);
|
||||
let (token, q) = asked(&click(&mut tool, &c, at.x, at.y));
|
||||
assert_eq!(
|
||||
(q["id"].as_u64(), &q["missing"], &q["style"], &q["more"]),
|
||||
(Some(id.0), &json!([format!("{NO_SUCH_FAMILY} Regular")]), &json!([]), &json!(0))
|
||||
);
|
||||
assert_eq!(tool.editing, None);
|
||||
assert!(!tool.waiting());
|
||||
// OK: the next poll starts the edit at the clicked character.
|
||||
tool.set_option("missingFontEdit", &json!({"token": token, "ok": true}));
|
||||
assert!(tool.waiting());
|
||||
let acts = tool.poll(&c, false);
|
||||
assert_eq!(acts, vec![Action::Exec("select.set".into(), json!({"ids": [id.0]}))]);
|
||||
assert_eq!((tool.editing, tool.caret, tool.anchor), (Some(id), 3, 3));
|
||||
assert!(!tool.waiting());
|
||||
let NodeKind::Text(t) = &d.node(id).unwrap().kind else { panic!("text") };
|
||||
assert_eq!(t.runs[0].style.font_family, NO_SUCH_FAMILY);
|
||||
// A click within the type being edited moves the caret without asking again.
|
||||
let at = caret_at(&c, id, 1);
|
||||
let acts = click(&mut tool, &c, at.x, at.y);
|
||||
assert!(!acts.iter().any(|a| matches!(a, Action::Dialog(..))), "{acts:?}");
|
||||
assert_eq!((tool.editing, tool.caret), (Some(id), 1));
|
||||
}
|
||||
|
||||
/// Cancel starts no edit, and the edit in progress on other type goes on; an answer that names
|
||||
/// another question, or one given to a document changed since, starts nothing either.
|
||||
#[test]
|
||||
fn cancel_or_a_stale_answer_starts_no_edit_in_missing_fonts() {
|
||||
let (mut d, first, mut tool) = editing("First");
|
||||
tool.caret = 2;
|
||||
let other = add_styled_text(&mut d, 300.0, &[("Second", NO_SUCH_FAMILY, "Bold")]);
|
||||
let (sel, p) = (Selection::default(), paint());
|
||||
let c = cx(&d, &sel, &p);
|
||||
let at = caret_at(&c, other, 2);
|
||||
let (token, _) = asked(&click(&mut tool, &c, at.x, at.y));
|
||||
assert_eq!((tool.editing, tool.caret), (Some(first), 2), "the edit in progress goes on while the question is open");
|
||||
tool.set_option("missingFontEdit", &json!({"token": token + 1, "ok": true}));
|
||||
assert!(!tool.waiting(), "another question's answer");
|
||||
tool.set_option("missingFontEdit", &json!({"token": token, "ok": false}));
|
||||
assert!(tool.poll(&c, false).is_empty());
|
||||
assert_eq!((tool.editing, tool.caret), (Some(first), 2));
|
||||
// OK after the document changed: nothing starts.
|
||||
let (token, _) = asked(&click(&mut tool, &c, at.x, at.y));
|
||||
tool.set_option("missingFontEdit", &json!({"token": token, "ok": true}));
|
||||
let changed = ToolContext { revision: (0, 1), ..cx(&d, &sel, &p) };
|
||||
assert!(tool.poll(&changed, false).is_empty());
|
||||
assert_eq!(tool.editing, Some(first));
|
||||
assert!(!tool.waiting());
|
||||
}
|
||||
|
||||
/// Every new edit of such type asks again, after an earlier OK too, and a style the family lacks
|
||||
/// asks as a missing family does; type in available fonts is edited at once.
|
||||
#[test]
|
||||
fn each_new_edit_of_type_in_unavailable_fonts_asks() {
|
||||
let mut d = Document::new(500.0, 500.0);
|
||||
let styled = add_styled_text(&mut d, 100.0, &[("Wide", "Source Sans 3", "Ultra Condensed Oblique 7258")]);
|
||||
let plain = add_styled_text(&mut d, 300.0, &[("Plain", "Source Sans 3", "Regular")]);
|
||||
let mut tool = TypeTool::new("type");
|
||||
let (sel, p) = (Selection::default(), paint());
|
||||
let c = cx(&d, &sel, &p);
|
||||
let at = caret_at(&c, styled, 1);
|
||||
let (token, q) = asked(&click(&mut tool, &c, at.x, at.y));
|
||||
assert_eq!((&q["missing"], &q["style"]), (&json!([]), &json!(["Source Sans 3 Ultra Condensed Oblique 7258"])));
|
||||
tool.set_option("missingFontEdit", &json!({"token": token, "ok": true}));
|
||||
tool.poll(&c, false);
|
||||
assert_eq!(tool.editing, Some(styled));
|
||||
// Other type in an available font is edited at once.
|
||||
let to = caret_at(&c, plain, 2);
|
||||
let acts = click(&mut tool, &c, to.x, to.y);
|
||||
assert!(acts.contains(&Action::Exec("select.set".into(), json!({"ids": [plain.0]}))), "{acts:?}");
|
||||
assert_eq!(tool.editing, Some(plain));
|
||||
// Back to the first type: a new edit, so the question comes again.
|
||||
asked(&click(&mut tool, &c, at.x, at.y));
|
||||
assert_eq!(tool.editing, Some(plain));
|
||||
}
|
||||
|
||||
/// The whole story counts: type with one run in a missing font asks even when the click lands in a
|
||||
/// run in an available font, and the question names each font once.
|
||||
#[test]
|
||||
fn a_story_with_one_run_in_a_missing_font_asks() {
|
||||
let mut d = Document::new(500.0, 500.0);
|
||||
let id = add_styled_text(
|
||||
&mut d,
|
||||
100.0,
|
||||
&[("Here ", "Source Sans 3", "Regular"), ("gone ", NO_SUCH_FAMILY, "Regular"), ("again", NO_SUCH_FAMILY, "Regular")],
|
||||
);
|
||||
let mut tool = TypeTool::new("type");
|
||||
let (sel, p) = (Selection::default(), paint());
|
||||
let c = cx(&d, &sel, &p);
|
||||
let at = caret_at(&c, id, 1);
|
||||
let (_, q) = asked(&click(&mut tool, &c, at.x, at.y));
|
||||
assert_eq!(q["missing"], json!([format!("{NO_SUCH_FAMILY} Regular")]));
|
||||
assert_eq!(tool.editing, None);
|
||||
}
|
||||
|
||||
/// Type set in a CSS generic family is edited without a question, and a press dropped while the
|
||||
/// question is open leaves the edit in progress as it was.
|
||||
#[test]
|
||||
fn generic_families_and_a_dropped_press_ask_nothing_more() {
|
||||
let mut d = Document::new(500.0, 500.0);
|
||||
let generic = add_styled_text(&mut d, 100.0, &[("Generic", "sans-serif", "Regular")]);
|
||||
let missing = add_styled_text(&mut d, 300.0, &[("Missing", NO_SUCH_FAMILY, "Regular")]);
|
||||
let mut tool = TypeTool::new("type");
|
||||
let (sel, p) = (Selection::default(), paint());
|
||||
let c = cx(&d, &sel, &p);
|
||||
let at = caret_at(&c, generic, 1);
|
||||
let acts = click(&mut tool, &c, at.x, at.y);
|
||||
assert!(acts.contains(&Action::Exec("select.set".into(), json!({"ids": [generic.0]}))), "{acts:?}");
|
||||
let to = caret_at(&c, missing, 1);
|
||||
asked(&tool.pointer(&c, &PointerEvent::new(PointerKind::Down, to.x, to.y)));
|
||||
assert!(tool.drop_press(&c).is_empty());
|
||||
assert_eq!(tool.editing, Some(generic));
|
||||
}
|
||||
|
||||
@@ -73,8 +73,12 @@ impl Tool for TypeTool {
|
||||
}
|
||||
self.clicks = (None, 0);
|
||||
// A press on other type edits it from there, so a drag selects its text at once,
|
||||
// as it does in the type being edited.
|
||||
// as it does in the type being edited. While the question about its fonts is open,
|
||||
// the press does nothing more, and the edit in progress goes on.
|
||||
if let Some(out) = self.edit_at(cx, ev.pos) {
|
||||
if self.pending_edit.is_some() {
|
||||
return out;
|
||||
}
|
||||
self.selecting = true;
|
||||
self.before_press = Some(before);
|
||||
return out;
|
||||
@@ -472,9 +476,17 @@ impl Tool for TypeTool {
|
||||
}
|
||||
fn deactivate(&mut self, cx: &ToolContext) -> Vec<Action> {
|
||||
self.prev_tool = None;
|
||||
self.pending_edit = None;
|
||||
self.frames.get_mut().unwrap_or_else(|e| e.into_inner()).clear();
|
||||
self.finish(cx)
|
||||
}
|
||||
/// OK on the question about type in missing fonts started an edit the next poll begins.
|
||||
fn waiting(&self) -> bool {
|
||||
self.pending_edit.as_ref().is_some_and(|e| e.accepted)
|
||||
}
|
||||
fn poll(&mut self, cx: &ToolContext, _wait: bool) -> Vec<Action> {
|
||||
self.resume_edit(cx)
|
||||
}
|
||||
/// Editing ends when a command takes the text out of the selection (Deselect, another object
|
||||
/// picked in the Layers panel) or removes it. After an Undo that takes back a list typed
|
||||
/// characters started, the caret goes on after the characters, and after its Redo the caret
|
||||
@@ -538,9 +550,15 @@ impl Tool for TypeTool {
|
||||
}
|
||||
}
|
||||
/// `select {start, end}` / `selectAll` / `copy` (with `runs` of the selection) /
|
||||
/// `commitTyping` (the caller commits the engine interaction).
|
||||
/// `commitTyping` (the caller commits the engine interaction) / `missingFontEdit {token, ok}`
|
||||
/// (the answer to the question about type in missing fonts; never a saved setting).
|
||||
fn set_option(&mut self, key: &str, v: &Value) {
|
||||
match key {
|
||||
"missingFontEdit" => {
|
||||
if let (Some(token), Some(ok)) = (v.get("token").and_then(Value::as_u64), v.get("ok").and_then(Value::as_bool)) {
|
||||
self.answer_edit(token, ok);
|
||||
}
|
||||
}
|
||||
// Transient selection transferred between Type and Eyedropper; never a saved setting.
|
||||
"textSelection" => {
|
||||
if let (Some(id), Some(a), Some(b)) = (
|
||||
|
||||
@@ -470,6 +470,7 @@ fn the_tool_is_made_by_its_id() {
|
||||
|
||||
#[test]
|
||||
fn touch_type_rtl_middle_character_can_drag_and_nudge_along_its_line() {
|
||||
let _inputs = crate::testutil::changing_layout_inputs();
|
||||
use vectorcraft_text::test_fonts::{RIGHT_TO_LEFT_OPTICAL_FAMILY, right_to_left_optical_font};
|
||||
|
||||
// The process-wide database deduplicates the same synthetic face across tests.
|
||||
|
||||
@@ -18,7 +18,7 @@ use vectorcraft_geom::{BezPath, Point, Rect, Shape};
|
||||
|
||||
use crate::{Overlay, Tool};
|
||||
|
||||
pub use artboard::ArtboardTool;
|
||||
pub use artboard::{ArtboardTool, EDGE_BUTTON_TIP, EDGE_BUTTON_TIP_LOCKED};
|
||||
pub use eyedropper::EyedropperTool;
|
||||
pub use free::{DistortMode, FreeTransformTool};
|
||||
pub use gradient::GradientTool;
|
||||
|
||||
@@ -28,7 +28,8 @@
|
||||
//! no other artboard). Clicking one adds an empty artboard there (`artboard.new {beside, side}`);
|
||||
//! Alt-clicking duplicates the artboard with its art there (`artboard.duplicate {index, side}`),
|
||||
//! except on a locked artboard, where an Alt-click does nothing. Each is one undo step, and the new
|
||||
//! artboard becomes the active one.
|
||||
//! artboard becomes the active one. Resting the pointer on a button shows a tooltip that says what a
|
||||
//! click does there and, on an unlocked artboard, what an Alt-click does.
|
||||
|
||||
use serde_json::{Value, json};
|
||||
use vectorcraft_doc::ArtboardSide;
|
||||
@@ -298,6 +299,10 @@ fn bleed_offset(cx: &ToolContext, rect: Rect, handle: Handle) -> Vec2 {
|
||||
const EDGE_BUTTON_OFFSET: f64 = 18.0;
|
||||
/// The add button's radius in screen pixels: a press this near its center takes it.
|
||||
const EDGE_BUTTON_RADIUS: f64 = 7.0;
|
||||
/// The add button's tooltip ([`Overlay::HoverText`]), an English UI string the UI translates.
|
||||
pub const EDGE_BUTTON_TIP: &str = "Click to add an artboard on this side; Alt-click to duplicate this artboard with its art";
|
||||
/// The add button's tooltip on a locked artboard, where an Alt-click does nothing.
|
||||
pub const EDGE_BUTTON_TIP_LOCKED: &str = "Click to add an artboard on this side";
|
||||
|
||||
impl ArtboardTool {
|
||||
/// The add buttons on the active artboard's edges, each with its side and center: shown while
|
||||
@@ -657,9 +662,11 @@ impl Tool for ArtboardTool {
|
||||
if self.drag.is_some() {
|
||||
o.extend(self.guides.iter().cloned());
|
||||
}
|
||||
// The add buttons: a ring with a plus in it.
|
||||
// The add buttons: a ring with a plus in it, and a tooltip over the area a press takes.
|
||||
let (radius, arm) = (cx.tol(EDGE_BUTTON_RADIUS), cx.tol(3.5));
|
||||
let tip = if ab.locked { EDGE_BUTTON_TIP_LOCKED } else { EDGE_BUTTON_TIP };
|
||||
for (_, at) in self.edge_buttons(cx) {
|
||||
o.push(Overlay::HoverText { center: at, radius, text: tip });
|
||||
let ring: Vec<Point> = (0..24).map(|k| at + Vec2::from_angle(f64::from(k) * std::f64::consts::TAU / 24.0) * radius).collect();
|
||||
let mut path = polygon(&ring, true);
|
||||
for arm in [Vec2::new(arm, 0.0), Vec2::new(0.0, arm)] {
|
||||
|
||||
@@ -611,6 +611,44 @@ fn add_buttons_hide_with_several_artboards_selected_or_during_a_drag() {
|
||||
assert!(button_sides(&t, &c).is_empty(), "none while an artboard is dragged");
|
||||
}
|
||||
|
||||
/// The tooltips the add buttons carry: each one's center, radius and text.
|
||||
fn button_tips(t: &ArtboardTool, c: &ToolContext) -> Vec<(Point, f64, &'static str)> {
|
||||
t.overlays(c)
|
||||
.into_iter()
|
||||
.filter_map(|o| if let Overlay::HoverText { center, radius, text } = o { Some((center, radius, text)) } else { None })
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn each_add_button_has_a_tooltip_over_the_area_a_press_takes() {
|
||||
let mut d = two_boards();
|
||||
let (s, p) = (Selection::default(), paint());
|
||||
let c = cx(&d, &s, &p);
|
||||
let t = ArtboardTool::default();
|
||||
let radius = c.tol(EDGE_BUTTON_RADIUS);
|
||||
let want: Vec<_> = t.edge_buttons(&c).into_iter().map(|(_, at)| (at, radius, EDGE_BUTTON_TIP)).collect();
|
||||
assert_eq!(want.len(), 3, "no button and no tooltip on the side without room");
|
||||
assert_eq!(button_tips(&t, &c), want);
|
||||
// The tooltip's disc is the one a press takes.
|
||||
for (at, r, _) in &want {
|
||||
assert!(t.edge_button_at(&c, *at + Vec2::new(r * 0.99, 0.0)).is_some());
|
||||
assert!(t.edge_button_at(&c, *at + Vec2::new(r * 1.01, 0.0)).is_none());
|
||||
}
|
||||
// None with several artboards selected or during a drag.
|
||||
let several = ArtboardTool { active: 1, others: vec![0], ..Default::default() };
|
||||
assert!(button_tips(&several, &c).is_empty());
|
||||
let mut dragging = ArtboardTool::default();
|
||||
dragging.pointer(&c, &ev(PointerKind::Down, 700.0, 100.0));
|
||||
dragging.pointer(&c, &ev(PointerKind::Drag, 720.0, 100.0));
|
||||
assert!(button_tips(&dragging, &c).is_empty(), "none while an artboard is dragged");
|
||||
// A locked artboard's buttons tell only what a click does: an Alt-click does nothing there.
|
||||
d.artboards[0].locked = true;
|
||||
let c = cx(&d, &s, &p);
|
||||
let tips = button_tips(&t, &c);
|
||||
assert_eq!(tips.len(), 3);
|
||||
assert!(tips.iter().all(|(_, _, text)| *text == EDGE_BUTTON_TIP_LOCKED), "{tips:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_add_button_adds_an_empty_artboard_and_alt_duplicates_on_that_side() {
|
||||
let d = two_boards();
|
||||
|
||||
Reference in New Issue
Block a user