Merge pull request #8493 from dotCooCoo/feat/circle-from-center

Shapes: the Circle tool draws a circle from its center through a point
This commit is contained in:
BFlat
2026-11-26 08:47:08 +07:00
committed by GitHub
10 changed files with 552 additions and 69 deletions
+1
View File
@@ -147,6 +147,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 2026-11-15: Circle through three points: three Shift-clicks with the Ellipse tool, or `shape.circleThroughPoints` with three points or three selected anchor points, draw the circle whose edge passes through them, with the current paint, in one undo step; after two points the tool previews the circle through the pointer, and two points that are the same or three on one line are refused with a message. Scores and estimates unchanged.
- 2026-11-17: Circle tool (after the Ellipse tool in its group): two clicks or a drag draw the circle on that diameter, and a click followed by a drag from a second point to a third draws the circle through the three; Shift keeps the diameter at 45° steps, Alt rounds a two-point circle's diameter to the rulers' ticks at the current zoom, points snap to Smart Guides, and the tool shows the circle, its center, its radii and its diameter until the release, or "Circle too large" for points on one line or a circle past the canvas. `shape.circleThroughPoints` also takes two points or two selected anchor points as the ends of a diameter. One undo step per circle. A VectorCraft addition: headline numbers unchanged.
- 2026-11-17: Circle Tool Options (double-click the Circle tool): Show Center, Show Radii and Show Diameter switch what the tool shows while a circle is drawn, Color sets the color of the center cross and radius lines, Anchors at Standard Positions off puts the circle's anchors at the points it was drawn through (`shape.circleThroughPoints {anchors: "points"}`), and Third Point by Dragging off draws a three-point circle with three clicks and a two-point circle with a double-click on the second point. A VectorCraft addition: headline numbers unchanged.
- 2026-11-17: Circle tool, From Center (a Control bar checkbox, `tool.setOption` `fromCenter`): the first point is the circle's center and the outline passes through the pointer, which snaps to Smart Guides and anchor points, so a circle centered on one corner of a rectangle can pass through the opposite corner; `shape.circleThroughPoints {center, points: [[x, y]]}` draws it. One undo step per circle. A VectorCraft addition: headline numbers unchanged.
- 2026-11-19: Quick Pen tool, in the Pen tool's group (Alt+P, Option+P on macOS): clicks or drags add straight lines, continuous arcs or sharp-corner arcs; Alt tapped on its own switches the action, C flips the last arc, `[` and `]` size it, a click on the first point closes the path and a click on an open end continues it (`path.quickPen`, part of #2660). Headline numbers unchanged.
- 2026-11-19: Quick Pen length handles: a handle beyond the start and the end of the path being drawn, or of the selected path, makes the line or arc there longer or shorter when dragged; a line keeps its direction and an arc its circle (`path.quickPenLength`, part of #2660). Headline numbers unchanged.
- 2026-11-19: Quick Pen toolbar on the canvas while the tool is active: Straight Line, Continuous Arc and Sharp Corner Arc, Flip Arc, and More Options with Hide Toolbar, Pin Toolbar Position and Reset Toolbar Position; it follows the drawing beside the path's last point and its handle drags it (`tool.quickPen.flipArc`, `window.quickPenToolbar`, Window › Quick Pen Toolbar; part of #2660). Headline numbers unchanged.
+41 -11
View File
@@ -73,7 +73,7 @@ pub fn specs() -> Vec<CommandSpec> {
"Circle Through Points",
[],
None,
"{points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]] (two: the ends of a diameter; left out: the two or three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count), anchors?: \"standard\"|\"points\" (default standard: four anchors at 0°, 90°, 180° and 270°; points: an anchor at each point and more between them so that no curve turns more than a quarter)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same, three on one line, or a circle reaching past the canvas are an error, and nothing is drawn",
"{points?: [[x, y], [x, y]] or [[x, y], [x, y], [x, y]] (two: the ends of a diameter; left out: the two or three selected anchor points, where a path selected whole counts all its anchors and selected segments' ends do not count), center?: [x, y] (the circle's center; `points` then holds the one point its edge passes through, [[x, y]]), anchors?: \"standard\"|\"points\" (default standard: four anchors at 0°, 90°, 180° and 270°; points: an anchor at each point and more between them so that no curve turns more than a quarter)} → {id, cx, cy, radius}: a circle with the current paint whose edge passes through the points, not pixel-aligned even while Align New Objects to Pixel Grid is on; two points that are the same, a point on `center`, three on one line, a circle reaching past the canvas, or one too small for its edges to differ at its coordinates are an error, and nothing is drawn",
has_doc,
circle_through_points
),
@@ -449,9 +449,33 @@ fn ellipse(s: &mut Session, p: &Value) -> Result<Value> {
/// Ellipse tool drag is.
fn circle_through_points(s: &mut Session, p: &Value) -> Result<Value> {
const C: &str = "shape.circleThroughPoints";
let points = match p.get("points").filter(|v| !v.is_null()) {
Some(v) => two_or_three_points(v).ok_or_else(|| bad(C, "`points` must be two or three [x, y] pairs of numbers"))?,
None => selected_anchor_points(s)?.ok_or_else(|| bad(C, "direct-select two or three anchor points, or give `points`"))?,
const SAME: &str = "no circle passes through these points: two are the same or all three lie on one line";
let (center, radius, points) = match p.get("center") {
// From a center: the circle at `center` whose edge passes through the one point. A null
// `center` is refused, as a null `points` with a center is.
Some(c) => {
let one = p.get("points").and_then(Value::as_array).and_then(|v| match v.as_slice() {
[q] => pair(q),
_ => None,
});
let (c, q) = pair(c).zip(one).ok_or_else(|| bad(C, "`center` must be an [x, y] pair of numbers, with one [x, y] pair in `points`"))?;
let r = c.distance(q);
if r == 0.0 {
return Err(bad(C, "the point in `points` is on `center`"));
}
if !r.is_finite() {
return Err(bad(C, "result would exceed the canvas (coordinates out of range)"));
}
(c, r, vec![q])
}
None => {
let points = match p.get("points").filter(|v| !v.is_null()) {
Some(v) => two_or_three_points(v).ok_or_else(|| bad(C, "`points` must be two or three [x, y] pairs of numbers"))?,
None => selected_anchor_points(s)?.ok_or_else(|| bad(C, "direct-select two or three anchor points, or give `points`"))?,
};
let (c, r) = shapes::circle_through_points(&points).ok_or_else(|| bad(C, SAME))?;
(c, r, points)
}
};
let key = "anchors";
let at_points = match p.get(key).map(Value::as_str) {
@@ -459,13 +483,15 @@ fn circle_through_points(s: &mut Session, p: &Value) -> Result<Value> {
Some(Some("points")) => true,
Some(_) => return Err(bad(C, format!("`{key}` must be one of {}", "standard, points"))),
};
let (center, radius) = shapes::circle_through_points(&points)
.ok_or_else(|| bad(C, "no circle passes through these points: two are the same or all three lie on one line"))?;
let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius);
// A radius below the step between doubles at the center leaves opposite edges on one number.
if !(r.width() > 0.0 && r.height() > 0.0) {
return Err(bad(C, "the circle is too small to draw at these coordinates"));
}
// Not pixel-aligned: the circle stays through the points.
let mut out = if at_points {
add_art_unaligned(s, "Ellipse", path_kind(shapes::circle_with_anchors_at(center, radius, &points), None))?
} else {
let r = Rect::new(center.x - radius, center.y - radius, center.x + radius, center.y + radius);
let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) };
add_art_unaligned(s, "Ellipse", path_kind(live.to_path(), Some(live)))?
};
@@ -475,13 +501,17 @@ fn circle_through_points(s: &mut Session, p: &Value) -> Result<Value> {
Ok(out)
}
/// The point an `[x, y]` pair of finite numbers gives.
fn pair(v: &Value) -> Option<Point> {
match v.as_array().map(Vec::as_slice) {
Some([x, y]) => x.as_f64().zip(y.as_f64()).filter(|(x, y)| x.is_finite() && y.is_finite()).map(|(x, y)| Point::new(x, y)),
_ => None,
}
}
/// The two or three points `[[x, y], [x, y]]` or `[[x, y], [x, y], [x, y]]` holds, each pair two
/// finite numbers.
fn two_or_three_points(v: &Value) -> Option<Vec<Point>> {
let pair = |v: &Value| match v.as_array().map(Vec::as_slice) {
Some([x, y]) => x.as_f64().zip(y.as_f64()).filter(|(x, y)| x.is_finite() && y.is_finite()).map(|(x, y)| Point::new(x, y)),
_ => None,
};
match v.as_array() {
Some(pairs) if matches!(pairs.len(), 2 | 3) => pairs.iter().map(pair).collect(),
_ => None,
+79
View File
@@ -123,6 +123,63 @@ fn two_points_are_the_ends_of_a_diameter() {
assert_eq!((undo_len(&s), object_count(&s)), (undo, count));
}
/// With `center`, the circle is centered there and its edge passes through the one point in
/// `points`: from the bottom-right corner (200, 200) of a 100 pt square through its top-left
/// corner (100, 100), the radius is the square's diagonal, in one undo step. A point on the center
/// and a circle past the canvas are refused, and so is a `center` (null included) or `points` that
/// is not one `[x, y]` pair of finite numbers; nothing is drawn and no undo step is recorded.
#[test]
fn a_center_and_a_point_on_the_edge_give_the_circle() {
let mut s = session();
let undo = undo_len(&s);
let out = s.execute(C, &json!({"center": [200, 200], "points": [[100, 100]]})).unwrap();
let r = 100.0 * std::f64::consts::SQRT_2;
assert_eq!((out["cx"].as_f64(), out["cy"].as_f64()), (Some(200.0), Some(200.0)), "{out}");
assert!((out["radius"].as_f64().unwrap() - r).abs() < 1e-12, "{out}");
let id = id_of(&out);
assert!(bounds_are(&s, id, vectorcraft_geom::Rect::new(200.0 - r, 200.0 - r, 200.0 + r, 200.0 + r)));
assert!(farthest_from_path(&s, id, &[Point::new(100.0, 100.0)]) < r * 3e-4);
assert_eq!(s.doc().unwrap().selection.objects, [id]);
assert_eq!(undo_len(&s), undo + 1);
let (undo, count) = (undo_len(&s), object_count(&s));
let e = s.execute(C, &json!({"center": [30, 30], "points": [[30, 30]]})).unwrap_err().to_string();
assert!(e.contains("the point in `points` is on `center`"), "{e}");
// Past the canvas, and finite coordinates whose distance overflows to infinity.
for (center, point) in [(json!([0, 0]), json!([4_100_000, 0])), (json!([-1e308, -1e308]), json!([1e308, 1e308]))] {
let e = s.execute(C, &json!({ "center": center, "points": [point] })).unwrap_err().to_string();
assert!(e.contains("result would exceed the canvas"), "{center} {point}: {e}");
}
for (center, points) in [
(json!([0, 0]), json!([[10, 0], [0, 10]])),
(json!([0, 0]), json!([])),
(json!([0, 0]), Value::Null),
(json!([0, 0]), json!([[10, "0"]])),
(json!([0]), json!([[10, 0]])),
(json!("0,0"), json!([[10, 0]])),
(json!([0, 0, 1]), json!([[10, 0]])),
(Value::Null, json!([[10, 0]])),
(Value::Null, json!([[10, 0], [20, 0]])),
] {
let e = s.execute(C, &json!({ "center": center, "points": points })).unwrap_err().to_string();
assert!(e.contains("`center` must be an [x, y] pair of numbers, with one [x, y] pair in `points`"), "{center} {points}: {e}");
}
assert_eq!((undo_len(&s), object_count(&s)), (undo, count));
}
/// A circle so small beside its coordinates that its left and right edges round to the same
/// number (radius 10⁻¹¹ pt at x = 1,048,576, where doubles step by about 2.3 × 10⁻¹⁰) is refused,
/// from a center and on a diameter alike; nothing is drawn and no undo step is recorded.
#[test]
fn a_circle_with_no_width_at_document_precision_is_refused() {
let mut s = session();
let (undo, count) = (undo_len(&s), object_count(&s));
for p in [json!({"center": [1_048_576, 0], "points": [[1_048_576, 1e-11]]}), json!({"points": [[1_048_576, 0], [1_048_576, 2e-11]]})] {
let e = s.execute(C, &p).unwrap_err().to_string();
assert!(e.contains("the circle is too small to draw at these coordinates"), "{p}: {e}");
}
assert_eq!((undo_len(&s), object_count(&s)), (undo, count));
}
/// Points that are not two or three pairs of finite numbers are an error, not a fallback.
#[test]
fn malformed_points_are_refused() {
@@ -243,6 +300,28 @@ fn click(s: &mut Session, mods: Mods, x: f64, y: f64) {
}
}
/// The Circle tool with From Center set through `tool.setOption`: a click on the center and a
/// click on the edge draw the circle, in one undo step. `fromCenter` must be true or false, and
/// the tool has no other option; a refused value changes nothing.
#[test]
fn the_circle_tool_draws_from_its_center() {
let mut s = session();
s.select_tool("circle", view()).unwrap();
let e = s.set_tool_option_cmd(&json!({"key": "fromCenter", "value": "yes"})).unwrap_err();
assert!(e.contains("`fromCenter` must be true or false"), "{e}");
assert!(s.set_tool_option_cmd(&json!({"key": "radius", "value": 5})).is_err());
assert_eq!(s.tool_options()["fromCenter"], json!(false));
s.set_tool_option_cmd(&json!({"key": "fromCenter", "value": true})).unwrap();
assert_eq!(s.tool_options()["fromCenter"], json!(true));
let undo = undo_len(&s);
click(&mut s, Mods::default(), 200.0, 200.0);
click(&mut s, Mods::default(), 100.0, 100.0);
assert_eq!(undo_len(&s), undo + 1);
let id = *s.doc().unwrap().selection.objects.first().unwrap();
let r = 100.0 * std::f64::consts::SQRT_2;
assert!(bounds_are(&s, id, vectorcraft_geom::Rect::new(200.0 - r, 200.0 - r, 200.0 + r, 200.0 + r)));
}
/// With the Ellipse tool, three Shift-clicks draw the circle through the three points, in one
/// undo step; Escape drops the points placed so far.
#[test]
+49
View File
@@ -30,6 +30,55 @@ fn blob_tip_options_report_and_persist() {
assert_eq!((next.tool_options()["angle"].as_f64(), next.tool_options()["roundness"].as_f64()), (Some(45.0), Some(0.0)));
}
/// The Circle tool's From Center survives a tool switch and is saved with the preferences.
#[test]
fn circle_from_center_persists() {
let mut s = session();
select(&mut s, "circle");
let mut want = s.tool_options();
assert_eq!(want["fromCenter"], json!(false));
want["fromCenter"] = json!(true);
s.set_tool_option("fromCenter", &json!(true));
select(&mut s, "selection");
select(&mut s, "circle");
assert_eq!(s.tool_options(), want);
select(&mut s, "selection");
let saved = serde_json::to_string(&s.prefs).unwrap();
let mut next = session();
next.apply_prefs(serde_json::from_str(&saved).unwrap());
select(&mut next, "circle");
assert_eq!(next.tool_options(), want);
}
/// An option set during a press (`tool.setOption`, or a Control bar change) is kept when the press
/// is dropped: the drop gives back only what the press itself changed.
#[test]
fn the_circle_from_center_set_during_a_dropped_press_is_kept() {
let v = ViewInfo::default();
let mut s = session();
select(&mut s, "circle");
let mut want = s.tool_options();
s.set_tool_option("fromCenter", &json!(true));
s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap();
s.set_tool_option_cmd(&json!({"key": "fromCenter", "value": false})).unwrap();
s.drop_tool_press(v).unwrap();
want["fromCenter"] = json!(false);
assert_eq!(s.tool_options(), want);
assert_eq!(s.prefs.tool_settings["circle"]["fromCenter"], json!(false));
s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap();
s.set_tool_option("fromCenter", &json!(true));
s.drop_tool_press(v).unwrap();
want["fromCenter"] = json!(true);
assert_eq!(s.tool_options(), want);
assert_eq!(s.prefs.tool_settings["circle"]["fromCenter"], json!(true));
// Setting a Parametric Shape's kind also puts its numbers back to that kind's: those are kept too.
select(&mut s, "parametricShape");
s.pointer(&PointerEvent::new(PointerKind::Down, 100.0, 100.0), v).unwrap();
let set = s.set_tool_option_cmd(&json!({"key": "kind", "value": "star"})).unwrap();
s.drop_tool_press(v).unwrap();
assert_eq!(s.tool_options(), set);
}
#[test]
fn options_survive_a_tool_switch() {
let mut s = session();
+130 -47
View File
@@ -17,6 +17,16 @@
//! reach past the canvas, the tool shows none and the release draws nothing; for three different
//! points on one line, or a circle past the canvas, the pointer shows "Circle too large".
//!
//! With the option From Center (`fromCenter`, in the Control bar) on, the first point is the
//! circle's center and the outline passes through the second: a drag from the center, or a click
//! on the center and then on a point of the outline, draws the circle whose radius is the distance
//! between them (`shape.circleThroughPoints` with `center`). The second point snaps to anchors and
//! Smart Guides as the others do, so the outline can pass exactly through another object's anchor.
//! Shift keeps the second point at 45° steps from the center, and Alt rounds the diameter to the
//! rulers' ticks. The option in force when the first point is placed applies to that circle, and
//! `dragThird` does not apply to it, since it has only two points. With `standardAnchors` off, its
//! one anchor on the outline is the second point.
//!
//! The tool's options (Circle Tool Options, `tool.setOption`; kept with the preferences):
//! `center`, `radii` and `diameter` show or hide the center cross, the radius lines and the
//! diameter label; `color` is the color of the cross and the lines (one of [`COLORS`]);
@@ -24,7 +34,7 @@
//! at 0°, 90°, 180° and 270° (`anchors: "points"`); `dragThird` off places the second point with
//! a click and draws the circle through three points with a third click, and a click on the second
//! point again (as a double-click there does) draws the circle on the two points. Every option is
//! on by default, and `color` is blue.
//! on by default except `fromCenter`, which is off, and `color` is blue.
use serde_json::{Map, Value, json};
use vectorcraft_doc::MAX_COORD;
@@ -56,7 +66,7 @@ pub const COLORS: &[(&str, [u8; 3])] = &[
];
/// The option keys that are true or false.
const SWITCHES: &[&str] = &["center", "radii", "diameter", "standardAnchors", "dragThird"];
const SWITCHES: &[&str] = &["center", "radii", "diameter", "standardAnchors", "dragThird", "fromCenter"];
/// The tool's options (see the module comment).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
@@ -68,11 +78,13 @@ struct Options {
color: usize,
standard_anchors: bool,
drag_third: bool,
/// The option From Center: the first point is the center.
from_center: bool,
}
impl Default for Options {
fn default() -> Self {
Options { center: true, radii: true, diameter: true, color: 1, standard_anchors: true, drag_third: true }
Options { center: true, radii: true, diameter: true, color: 1, standard_anchors: true, drag_third: true, from_center: false }
}
}
@@ -84,6 +96,7 @@ impl Options {
"diameter" => &mut self.diameter,
"standardAnchors" => &mut self.standard_anchors,
"dragThird" => &mut self.drag_third,
"fromCenter" => &mut self.from_center,
_ => return None,
})
}
@@ -143,48 +156,79 @@ pub struct CircleTool {
press: Option<Press>,
/// Where the pointer is, snapped: the point the next press or release places.
pointer: Option<Point>,
/// Is the circle being drawn drawn from its center (From Center when its first point was
/// placed)?
centered: bool,
}
/// The command the tool runs for `points`; with `standard_anchors` off, the circle's anchors are
/// at the points.
fn command(points: &[Point], standard_anchors: bool) -> (String, Value) {
let pairs: Vec<Value> = points.iter().map(|p| json!([p.x, p.y])).collect();
let params = if standard_anchors { json!({ "points": pairs }) } else { json!({ "points": pairs, "anchors": "points" }) };
/// The command the tool runs for `points`: with `centered`, the first point is the center and
/// the second is on the outline. With `standard_anchors` off, the circle's anchors are at the
/// points (from a center, the one point on the outline).
fn command(points: &[Point], centered: bool, standard_anchors: bool) -> (String, Value) {
let pair = |p: &Point| json!([p.x, p.y]);
let mut params = match points {
[c, p] if centered => json!({ "center": pair(c), "points": [pair(p)] }),
_ => json!({ "points": points.iter().map(pair).collect::<Vec<_>>() }),
};
if !standard_anchors {
params["anchors"] = json!("points");
}
("shape.circleThroughPoints".into(), params)
}
/// Is the circle at `c` with radius `r` inside the canvas, with its opposite edges on different
/// numbers (as `shape.circleThroughPoints` requires)?
fn on_canvas(c: Point, r: f64) -> bool {
[c.x - r, c.y - r, c.x + r, c.y + r].iter().all(|v| v.abs() <= MAX_COORD) && c.x - r < c.x + r && c.y - r < c.y + r
}
/// The circle through two points (the ends of a diameter) or three, as `shape.circleThroughPoints`
/// draws it: none where no circle passes through them or it would reach past the canvas.
pub fn circle_of(points: &[Point]) -> Option<(Point, f64)> {
let on_canvas = |(c, r): &(Point, f64)| [c.x - r, c.y - r, c.x + r, c.y + r].iter().all(|v| v.abs() <= MAX_COORD);
shapes::circle_through_points(points).filter(on_canvas)
shapes::circle_through_points(points).filter(|(c, r)| on_canvas(*c, *r))
}
/// [`circle_of`], as the tool draws it: with `standard_anchors` off, also none where the path with
/// an anchor at each point ([`shapes::circle_with_anchors_at`]) reaches past the canvas, since its
/// curves can reach slightly outside the circle.
fn drawn_circle(points: &[Point], standard_anchors: bool) -> Option<(Point, f64)> {
/// The circle `points` give: with `centered`, the circle at the first point whose outline passes
/// through the second, as `shape.circleThroughPoints` with `center` draws it (none for a second
/// point on the center or a circle past the canvas); otherwise [`circle_of`].
fn circle_for(points: &[Point], centered: bool) -> Option<(Point, f64)> {
match *points {
[c, p] if centered => {
let r = c.distance(p);
(c.is_finite() && r.is_finite() && r > 0.0 && on_canvas(c, r)).then_some((c, r))
}
_ if centered => None,
_ => circle_of(points),
}
}
/// [`circle_for`], as the tool draws it: with `standard_anchors` off, also none where the path with
/// an anchor at each point ([`shapes::circle_with_anchors_at`]; from a center, the one point on the
/// outline) reaches past the canvas, since its curves can reach slightly outside the circle.
fn drawn_circle(points: &[Point], centered: bool, standard_anchors: bool) -> Option<(Point, f64)> {
let anchors = if centered { points.get(1..).unwrap_or(&[]) } else { points };
let fits = |(c, r): &(Point, f64)| {
let b = vectorcraft_geom::Shape::bounding_box(&shapes::circle_with_anchors_at(*c, *r, points).to_bezpath());
let b = vectorcraft_geom::Shape::bounding_box(&shapes::circle_with_anchors_at(*c, *r, anchors).to_bezpath());
[b.x0, b.y0, b.x1, b.y1].iter().all(|v| v.is_finite() && v.abs() <= MAX_COORD)
};
circle_of(points).filter(|c| standard_anchors || fits(c))
circle_for(points, centered).filter(|c| standard_anchors || fits(c))
}
/// With Alt, `p` moved along the line from `first` so that their distance (the diameter) is on
/// the nearest ruler tick at the current zoom, in the General unit; `p` itself without Alt, and
/// when that rounding leaves no distance.
fn round_diameter(cx: &ToolContext, first: Point, p: Point, mods: Mods) -> Point {
let d = first.distance(p);
/// With Alt, `p` moved along the line from `first` so that the diameter (their distance, or twice
/// it from a center) is on the nearest ruler tick at the current zoom, in the General unit; `p`
/// itself without Alt, and when that rounding leaves no distance.
fn round_diameter(cx: &ToolContext, first: Point, p: Point, mods: Mods, centered: bool) -> Point {
let per = if centered { 2.0 } else { 1.0 };
let d = first.distance(p) * per;
let rounded = cx.unit.snap_to_ruler_tick(d, cx.zoom);
if mods.alt && d > 0.0 && rounded > 0.0 && rounded.is_finite() { first + (p - first) * (rounded / d) } else { p }
}
/// Are the points two or more different points through which no circle is drawn: three on one
/// line, or a circle that would reach past the canvas?
fn too_large(points: &[Point], standard_anchors: bool) -> bool {
fn too_large(points: &[Point], centered: bool, standard_anchors: bool) -> bool {
let distinct = points.iter().enumerate().all(|(i, p)| !points.iter().take(i).any(|q| q == p));
points.len() >= 2 && distinct && drawn_circle(points, standard_anchors).is_none()
points.len() >= 2 && distinct && drawn_circle(points, centered, standard_anchors).is_none()
}
impl CircleTool {
@@ -193,9 +237,21 @@ impl CircleTool {
self.second = None;
self.press = None;
self.pointer = None;
self.centered = false;
self.snap.clear();
}
/// [`round_diameter`] for the circle being drawn.
fn round(&self, cx: &ToolContext, first: Point, p: Point, mods: Mods) -> Point {
round_diameter(cx, first, p, mods, self.centered)
}
/// Does a drag place the third point? A circle drawn from its center has no third point, so
/// `dragThird` does not apply to it.
fn drag_third(&self) -> bool {
self.options.drag_third || self.centered
}
/// How the second point keeps to the first: Shift's 45° steps and the construction guides. A
/// third point keeps to neither.
fn leave(&self, cx: &ToolContext, mods: Mods) -> Option<Leave> {
@@ -222,9 +278,12 @@ impl CircleTool {
Some(Press::First { .. }) | None => out.extend(self.pointer.filter(|_| self.first.is_some())),
// A press on the first point adds no point: a drag from it drags out a diameter.
Some(Press::Second { on_first: true, dragged, .. }) => out.extend(self.pointer.filter(|_| dragged)),
// From a center, the second point follows the pointer once the press has been dragged;
// until then it is the pressed point, which a release within DRAG_PX draws through.
Some(Press::Second { dragged: true, .. }) if self.centered => out.extend(self.pointer),
Some(Press::Second { at, dragged: false, .. }) => out.push(at),
// With `dragThird` off, a drag moves the second point.
Some(Press::Second { at, .. }) if !self.options.drag_third => out.push(at),
Some(Press::Second { at, .. }) if !self.drag_third() => out.push(at),
Some(Press::Second { snapped, dragged: true, .. }) => {
out.push(snapped);
out.extend(self.pointer);
@@ -234,13 +293,17 @@ impl CircleTool {
out
}
/// The second point as the tool shows it: none for a press on the first point.
/// The second point as the tool shows it: none for a press on the first point, nor for a
/// circle drawn from its center, whose second point follows the pointer.
fn second(&self) -> Option<Point> {
if self.centered {
return None;
}
if let Some((b, _)) = self.second {
return Some(b);
}
match self.press {
Some(Press::Second { on_first: false, at, .. }) if !self.options.drag_third => Some(at),
Some(Press::Second { on_first: false, at, .. }) if !self.drag_third() => Some(at),
Some(Press::Second { on_first: false, dragged: false, at, .. }) => Some(at),
Some(Press::Second { on_first: false, dragged: true, snapped, .. }) => Some(snapped),
_ => None,
@@ -250,11 +313,12 @@ impl CircleTool {
/// Runs the circle through `points` and starts afresh; where no circle is drawn through them
/// (the tool showed none), it only starts afresh.
fn draw(&mut self, points: &[Point]) -> Vec<Action> {
let centered = self.centered;
self.clear();
if drawn_circle(points, self.options.standard_anchors).is_none() {
if drawn_circle(points, centered, self.options.standard_anchors).is_none() {
return vec![];
}
let (c, v) = command(points, self.options.standard_anchors);
let (c, v) = command(points, centered, self.options.standard_anchors);
vec![Action::Exec(c, v)]
}
@@ -267,7 +331,7 @@ impl CircleTool {
if on_second && !dragged {
return self.draw(&[a, b]);
}
if (on_first && !dragged) || drawn_circle(&[a, b, at], self.options.standard_anchors).is_none() {
if (on_first && !dragged) || drawn_circle(&[a, b, at], false, self.options.standard_anchors).is_none() {
self.snap.clear();
return vec![];
}
@@ -329,7 +393,7 @@ impl Tool for CircleTool {
let p = self.snap.hover(cx, ev.pos, &[], leave.as_ref());
// Alt's rounding of the diameter is for the second point only.
let rounds = self.first.filter(|_| self.second.is_none());
self.pointer = Some(rounds.map_or(p, |a| round_diameter(cx, a, p, ev.mods)));
self.pointer = Some(rounds.map_or(p, |a| self.round(cx, a, p, ev.mods)));
vec![]
}
PointerKind::Down => {
@@ -352,13 +416,14 @@ impl Tool for CircleTool {
None => {
let at = self.snap.press(cx, ev.pos, &[], None);
self.first = Some(at);
self.centered = self.options.from_center;
self.press = Some(Press::First { at, from: ev.pos, dragged: false });
self.pointer = Some(at);
}
Some(a) => {
let leave = self.leave(cx, ev.mods);
let snapped = self.snap.press(cx, ev.pos, &[], leave.as_ref());
let at = round_diameter(cx, a, snapped, ev.mods);
let at = self.round(cx, a, snapped, ev.mods);
let on_first = snapped == a || ev.pos.distance(a) <= cx.tol(REACH_PX);
self.press = Some(Press::Second { at, snapped, from: ev.pos, on_first, dragged: false });
self.pointer = Some(at);
@@ -367,7 +432,8 @@ impl Tool for CircleTool {
vec![]
}
PointerKind::Drag => {
let drag_third = self.options.drag_third;
let centered = self.centered;
let drag_third = self.drag_third();
let first = self.first;
match &mut self.press {
// With `dragThird` off, the second point follows the pointer as it does before
@@ -378,7 +444,7 @@ impl Tool for CircleTool {
if *dragged {
let leave = first.map(|a| Leave::segment(cx, a, ev.mods.shift));
*snapped = self.snap.drag(cx, ev.pos, leave.as_ref());
*at = first.map_or(*snapped, |a| round_diameter(cx, a, *snapped, ev.mods));
*at = first.map_or(*snapped, |a| round_diameter(cx, a, *snapped, ev.mods, false));
self.pointer = Some(*at);
}
}
@@ -392,15 +458,16 @@ impl Tool for CircleTool {
Some(Press::First { at, from, dragged }) => {
*dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX);
let leave = Leave::segment(cx, *at, ev.mods.shift);
self.pointer = Some(round_diameter(cx, *at, self.snap.drag(cx, ev.pos, Some(&leave)), ev.mods));
self.pointer = Some(round_diameter(cx, *at, self.snap.drag(cx, ev.pos, Some(&leave)), ev.mods, centered));
}
// Dragged from the first point, the pointer is the other end of a diameter, as
// for a drag from a first press.
Some(Press::Second { from, on_first: true, dragged, .. }) => {
// for a drag from a first press; from a center, the second point is always the
// pointer.
Some(Press::Second { from, dragged, on_first, .. }) if *on_first || centered => {
*dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX);
let leave = self.first.map(|a| Leave::segment(cx, a, ev.mods.shift));
let p = self.snap.drag(cx, ev.pos, leave.as_ref());
self.pointer = Some(self.first.map_or(p, |a| round_diameter(cx, a, p, ev.mods)));
self.pointer = Some(self.first.map_or(p, |a| round_diameter(cx, a, p, ev.mods, centered)));
}
Some(Press::Second { from, dragged, .. }) => {
*dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX);
@@ -414,15 +481,22 @@ impl Tool for CircleTool {
(Some(Press::Third { at, on_first, on_second, dragged, .. }), ..) => self.third_up(at, on_first, on_second, dragged),
// With `dragThird` off, the release places the second point; let go on the first
// point, as a press there is, it places nothing.
(Some(Press::Second { at, snapped, on_first: false, .. }), Some(a), _) if !self.options.drag_third => {
(Some(Press::Second { at, snapped, on_first: false, .. }), Some(a), _) if !self.drag_third() => {
if !(at == a || snapped == a || ev.pos.distance(a) <= cx.tol(REACH_PX)) {
self.second = Some((at, ev.pos));
}
self.snap.clear();
vec![]
}
(Some(Press::First { at, dragged: true, .. }), _, Some(b)) if b.distance(at) >= cx.tol(DRAG_PX) => self.draw(&[at, b]),
// A click places the first point; the guides of the press go.
// A release DRAG_PX or more from the press draws the circle the tool shows; where it
// shows none, the release draws nothing and starts afresh.
(Some(Press::First { at, dragged: true, .. }), _, Some(b))
if b.distance(at) >= cx.tol(DRAG_PX) || circle_for(&[at, b], self.centered).is_some() =>
{
self.draw(&[at, b])
}
// A click, or a drag back onto the press, places the first point; the guides of the
// press go.
(Some(Press::First { .. }), ..) => {
self.snap.clear();
vec![]
@@ -431,6 +505,9 @@ impl Tool for CircleTool {
// a drag from there draws the circle on the diameter it drags out.
(Some(Press::Second { on_first: true, dragged: false, .. }), ..) => vec![],
(Some(Press::Second { on_first: true, dragged: true, .. }), Some(a), Some(c)) => self.draw(&[a, c]),
// From a center: the outline passes through the point the tool shows it on, where
// the drag ends or, within DRAG_PX of the press, the pressed point.
(Some(Press::Second { .. }), Some(a), Some(c)) if self.centered => self.draw(&[a, c]),
(Some(Press::Second { at, dragged: false, .. }), Some(a), _) => self.draw(&[a, at]),
// Three points: Alt's rounding of the diameter does not apply.
(Some(Press::Second { snapped, dragged: true, .. }), Some(a), Some(c)) => self.draw(&[a, snapped, c]),
@@ -487,12 +564,14 @@ impl Tool for CircleTool {
let mut o = self.snap.guides().to_vec();
let points = self.points();
let color = crate::draw2::FEEDBACK;
if let Some((c, r)) = drawn_circle(&points, self.options.standard_anchors) {
// The path the release draws: with `standardAnchors` off, the one with an anchor at each point.
if let Some((c, r)) = drawn_circle(&points, self.centered, self.options.standard_anchors) {
// The path the release draws: with `standardAnchors` off, the one with an anchor at each
// point (from a center, at the one point on the outline).
let path = if self.options.standard_anchors {
shapes::ellipse(Rect::new(c.x - r, c.y - r, c.x + r, c.y + r)).to_bezpath()
} else {
shapes::circle_with_anchors_at(c, r, &points).to_bezpath()
let on_outline = if self.centered { points.get(1..).unwrap_or(&[]) } else { &points[..] };
shapes::circle_with_anchors_at(c, r, on_outline).to_bezpath()
};
// The canvas draws a dashed outline dash by dash along its whole length: a circle longer
// than DASHED_PX on screen is drawn solid instead.
@@ -501,7 +580,8 @@ impl Tool for CircleTool {
let opts = self.options;
let lines = COLORS.get(opts.color).map_or(color, |(_, rgb)| *rgb);
if opts.radii {
for p in &points {
// A circle drawn from its center has one radius, to the point on its outline.
for p in points.iter().filter(|p| **p != c) {
o.push(Overlay::Line { a: c, b: *p, color: lines, dashed: false });
}
}
@@ -513,7 +593,7 @@ impl Tool for CircleTool {
if let Some(p) = self.pointer.filter(|_| cx.measurement_labels && opts.diameter) {
o.push(Overlay::Measure { p: p + Vec2::new(cx.tol(12.0), cx.tol(12.0)), text: format!("D: {}", cx.len(2.0 * r)) });
}
} else if let Some(p) = self.pointer.filter(|_| too_large(&points, self.options.standard_anchors)) {
} else if let Some(p) = self.pointer.filter(|_| too_large(&points, self.centered, self.options.standard_anchors)) {
o.push(Overlay::Label { p, text: "Circle too large".into(), color });
}
for p in self.first.into_iter().chain(self.second()) {
@@ -536,6 +616,7 @@ impl Tool for CircleTool {
"color": color,
"standardAnchors": o.standard_anchors,
"dragThird": o.drag_third,
"fromCenter": o.from_center,
})
}
@@ -545,7 +626,8 @@ impl Tool for CircleTool {
}
/// Sets one option; a value the option does not take leaves it as it was. Switching
/// `dragThird` drops the points placed so far.
/// `dragThird` drops the points placed so far; a circle being drawn keeps the `fromCenter` mode
/// it started with.
fn set_option(&mut self, key: &str, value: &Value) {
if key == "color" {
if let Some(i) = value.as_str().and_then(|s| COLORS.iter().position(|(name, _)| *name == s)) {
@@ -558,7 +640,8 @@ impl Tool for CircleTool {
if let Some(switch) = self.options.switch(key) {
*switch = on;
}
if self.options.drag_third != was {
// A circle drawn from its center has no third point, so its center stays placed.
if self.options.drag_third != was && !self.centered {
self.clear();
}
}
+195 -5
View File
@@ -140,7 +140,10 @@ fn the_options_show_or_hide_the_center_radii_and_diameter_in_their_color() {
let o = t.overlays(&cx);
assert_eq!(annotations(&o, c), (vec![red; 2], vec![red; 2]));
assert!(o.iter().any(|o| matches!(o, Overlay::Path { color, .. } if *color == blue)), "{o:?}");
assert_eq!(t.options(), json!({"center": true, "radii": true, "diameter": false, "color": "red", "standardAnchors": true, "dragThird": true}));
assert_eq!(
t.options(),
json!({"center": true, "radii": true, "diameter": false, "color": "red", "standardAnchors": true, "dragThird": true, "fromCenter": false})
);
// A value an option does not take leaves it as it was.
for (key, value) in [("color", json!("orange")), ("center", json!("no")), ("radii", json!(0))] {
t.set_option(key, &value);
@@ -192,8 +195,8 @@ fn anchors_at_the_points_keep_the_path_on_the_canvas() {
let at = |deg: f64| (r * deg.to_radians().cos(), r * deg.to_radians().sin());
let points = [at(0.0), at(70.0), at(180.0)];
let geom: Vec<Point> = points.iter().map(|(x, y)| Point::new(*x, *y)).collect();
assert!(drawn_circle(&geom, true).is_some());
assert_eq!(drawn_circle(&geom, false), None);
assert!(drawn_circle(&geom, false, true).is_some());
assert_eq!(drawn_circle(&geom, false, false), None);
let mut t = CircleTool::default();
t.set_option("standardAnchors", &json!(false));
click(&mut t, &cx, points[0]);
@@ -584,8 +587,8 @@ fn points_on_one_line_say_the_circle_is_too_large() {
assert_eq!(label(&t), None, "a circle is shown");
t.pointer(&cx, &ev(PointerKind::Drag, (200.0, 200.0), Mods::default()));
assert_eq!(label(&t), None, "the third point is on the second");
assert!(too_large(&[Point::new(0.0, 0.0), Point::new(4.1e6, 0.0)], true));
assert!(!too_large(&[Point::new(0.0, 0.0)], true) && !too_large(&[Point::new(1.0, 0.0), Point::new(1.0, 0.0)], true));
assert!(too_large(&[Point::new(0.0, 0.0), Point::new(4.1e6, 0.0)], false, true));
assert!(!too_large(&[Point::new(0.0, 0.0)], false, true) && !too_large(&[Point::new(1.0, 0.0), Point::new(1.0, 0.0)], false, true));
}
/// Escape drops the first point; so do a dropped press and an edit made outside the tool. A
@@ -698,6 +701,193 @@ fn a_huge_circle_is_previewed_solid() {
assert!(preview(&t.overlays(&cx)).is_some());
}
/// The command the tool runs for a circle at `c` whose outline passes through `p`.
fn centered(c: (f64, f64), p: (f64, f64)) -> Vec<Action> {
vec![Action::Exec("shape.circleThroughPoints".into(), json!({ "center": [c.0, c.1], "points": [[p.0, p.1]] }))]
}
fn from_center() -> CircleTool {
let mut t = CircleTool::default();
t.set_option("fromCenter", &json!(true));
t
}
/// With From Center, a drag from the corner anchor of the rectangle at (200, 200) to next to the
/// opposite corner at (100, 100) snaps both ends to the anchors: the circle is centered on one
/// corner, its outline passes through the other, and its radius is the diagonal. Until the release
/// the outline passes through the pointer, with one radius drawn to it.
#[test]
fn from_center_the_outline_passes_through_the_opposite_corner() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = cx(&d, &s, &p);
let mut t = from_center();
assert_eq!(t.options()["fromCenter"], json!(true));
t.pointer(&cx, &ev(PointerKind::Move, (201.0, 199.5), Mods::default()));
t.pointer(&cx, &ev(PointerKind::Down, (201.0, 199.5), Mods::default()));
t.pointer(&cx, &ev(PointerKind::Drag, (150.0, 150.0), Mods::default()));
t.pointer(&cx, &ev(PointerKind::Drag, (101.0, 101.5), Mods::default()));
let r = 100.0 * std::f64::consts::SQRT_2;
let o = t.overlays(&cx);
let shown = o
.iter()
.find_map(|o| match o {
Overlay::Path { path, .. } => Some(vectorcraft_geom::Shape::bounding_box(path)),
_ => None,
})
.expect("the circle is shown");
assert!(near(shown, Rect::new(200.0 - r, 200.0 - r, 200.0 + r, 200.0 + r)), "{o:?}");
let center = Point::new(200.0, 200.0);
let radii: Vec<Point> = o
.iter()
.filter_map(|o| match o {
Overlay::Line { a, b, .. } if *a == center => Some(*b),
_ => None,
})
.collect();
assert_eq!(radii, vec![Point::new(100.0, 100.0)], "one radius, to the pointer: {o:?}");
assert!(o.iter().any(|o| matches!(o, Overlay::Measure { text, .. } if text.starts_with("D: 282.84"))), "{o:?}");
assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (101.0, 101.5), Mods::default())), centered((200.0, 200.0), (100.0, 100.0)));
assert_eq!(circle_for(&[center, Point::new(100.0, 100.0)], true), Some((center, r)));
}
/// With From Center, a click places the center and a second click the point the outline passes
/// through; a second click on the center places nothing, and the center stays.
#[test]
fn from_center_two_clicks_draw_the_circle_through_the_second() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let mut t = from_center();
assert_eq!(click(&mut t, &cx, (300.0, 300.0)), vec![]);
assert_eq!(click(&mut t, &cx, (300.5, 300.0)), vec![], "a double-click places the center alone");
assert!(t.ends_on_escape(&cx));
t.pointer(&cx, &ev(PointerKind::Move, (330.0, 340.0), Mods::default()));
// Center (300, 300), radius 50.
assert!(near(preview(&t.overlays(&cx)).expect("the circle is shown"), Rect::new(250.0, 250.0, 350.0, 350.0)), "{:?}", t.overlays(&cx));
assert_eq!(click(&mut t, &cx, (330.0, 340.0)), centered((300.0, 300.0), (330.0, 340.0)));
// A second press dragged from elsewhere moves the point the outline passes through.
click(&mut t, &cx, (300.0, 300.0));
assert_eq!(drag(&mut t, &cx, (330.0, 340.0), &[(360.0, 300.0)], Mods::default()), centered((300.0, 300.0), (360.0, 300.0)));
}
/// With From Center, the release draws the circle the tool shows: a drag from the center ends
/// where it is let go, and a second press moved less than 2 screen points shows and draws the
/// outline through the point of the press.
#[test]
fn from_center_the_release_draws_the_circle_shown() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let mut t = from_center();
t.pointer(&cx, &ev(PointerKind::Down, (300.0, 300.0), Mods::default()));
t.pointer(&cx, &ev(PointerKind::Drag, (380.0, 300.0), Mods::default()));
assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (400.0, 300.0), Mods::default())), centered((300.0, 300.0), (400.0, 300.0)));
click(&mut t, &cx, (300.0, 300.0));
t.pointer(&cx, &ev(PointerKind::Down, (330.0, 340.0), Mods::default()));
t.pointer(&cx, &ev(PointerKind::Drag, (331.0, 340.0), Mods::default()));
let shown = preview(&t.overlays(&cx)).expect("the circle is shown");
let r = Point::new(300.0, 300.0).distance(Point::new(330.0, 340.0));
assert!(near(shown, Rect::new(300.0 - r, 300.0 - r, 300.0 + r, 300.0 + r)), "{:?}", t.overlays(&cx));
assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (331.0, 340.0), Mods::default())), centered((300.0, 300.0), (330.0, 340.0)));
}
/// A first press let go within 2 screen points of where it was pressed is a click also after a
/// drag that came back to it, from a center and on a diameter: it places the first point.
#[test]
fn a_first_press_dragged_back_near_its_press_places_the_first_point() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let mut t = from_center();
assert_eq!(drag(&mut t, &cx, (300.0, 300.0), &[(320.0, 300.0), (301.0, 300.0)], Mods::default()), vec![]);
assert!(t.ends_on_escape(&cx), "the center is placed");
assert_eq!(click(&mut t, &cx, (380.0, 300.0)), centered((300.0, 300.0), (380.0, 300.0)));
let mut t = CircleTool::default();
assert_eq!(drag(&mut t, &cx, (300.0, 300.0), &[(320.0, 300.0), (301.0, 300.0)], Mods::default()), vec![]);
assert!(t.ends_on_escape(&cx), "the first point is placed");
t.key(&cx, ToolKey::Escape, Mods::default());
// A drag to a circle past the canvas draws nothing and leaves no point behind.
assert_eq!(drag(&mut t, &cx, (300.0, 300.0), &[(4.1e6, 300.0)], Mods::default()), vec![]);
assert!(!t.ends_on_escape(&cx), "nothing is left pending");
}
/// With From Center, Shift keeps the point at 45° steps from the center, and Alt rounds the
/// diameter, twice the radius, to the rulers' ticks (every 5 pt at 100% in points).
#[test]
fn from_center_shift_and_alt_keep_to_the_center() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let mut t = from_center();
let shift = Mods { shift: true, ..Mods::default() };
let acts = drag(&mut t, &cx, (300.0, 300.0), &[(400.0, 310.0)], shift);
let [Action::Exec(_, v)] = acts.as_slice() else { panic!("one circle: {acts:?}") };
assert!((v["points"][0][1].as_f64().unwrap() - 300.0).abs() < 1e-9, "level with the center: {v}");
// Near the diagonal, the point keeps to the 45° line through the center.
let acts = drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 372.0)], shift);
let [Action::Exec(_, v)] = acts.as_slice() else { panic!("one circle: {acts:?}") };
let (x, y) = (v["points"][0][0].as_f64().unwrap(), v["points"][0][1].as_f64().unwrap());
assert!(((x - 300.0) - (y - 300.0)).abs() < 1e-9 && x > 300.0, "on the 45° line from the center: {v}");
let alt = Mods { alt: true, ..Mods::default() };
// A radius of 26 is a diameter of 52, which Alt makes 50.
assert_eq!(drag(&mut t, &cx, (0.0, 0.0), &[(0.0, 26.0)], alt), centered((0.0, 0.0), (0.0, 25.0)));
}
/// The option in force when the first point is placed applies to that circle: turning From Center
/// off part way keeps the circle being drawn centered, and the next circle is drawn on a diameter.
/// A point on the center draws nothing.
#[test]
fn from_center_holds_for_the_circle_being_drawn() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let mut t = from_center();
click(&mut t, &cx, (100.0, 100.0));
t.set_option("fromCenter", &json!(false));
assert_eq!(click(&mut t, &cx, (100.0, 150.0)), centered((100.0, 100.0), (100.0, 150.0)));
assert_eq!(drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 360.0)], Mods::default()), circle(&[(300.0, 300.0), (380.0, 360.0)]));
assert_eq!(circle_for(&[Point::new(1.0, 1.0), Point::new(1.0, 1.0)], true), None);
assert!(too_large(&[Point::new(0.0, 0.0), Point::new(4.1e6, 0.0)], true, true));
// Edges that round to one number at document precision, as `shape.circleThroughPoints` refuses.
let x = 1_048_576.0;
assert_eq!(circle_for(&[Point::new(x, 0.0), Point::new(x, 1e-11)], true), None);
assert_eq!(circle_of(&[Point::new(x, 0.0), Point::new(x, 2e-11)]), None);
t.set_option("fromCenter", &json!("yes"));
assert_eq!(t.options()["fromCenter"], json!(false), "a value that is not true or false is ignored");
}
/// Switching `dragThird` while a center is placed keeps the center: the circle from it is still
/// drawn. Without From Center, the switch drops the point placed.
#[test]
fn switching_third_point_by_dragging_keeps_a_placed_center() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let mut t = from_center();
click(&mut t, &cx, (100.0, 100.0));
t.set_option("dragThird", &json!(false));
assert!(t.ends_on_escape(&cx), "the center is still placed");
assert_eq!(click(&mut t, &cx, (100.0, 150.0)), centered((100.0, 100.0), (100.0, 150.0)));
let mut t = CircleTool::default();
click(&mut t, &cx, (100.0, 100.0));
t.set_option("dragThird", &json!(false));
assert!(!t.ends_on_escape(&cx), "the first point is dropped");
}
/// `tool.setOption` takes `fromCenter` as true or false, and no other key.
#[test]
fn the_options_are_checked() {
let map = |v: Value| v.as_object().cloned().unwrap();
assert_eq!(check_options(&map(json!({ "fromCenter": true }))), Ok(()));
assert_eq!(check_options(&map(json!({ "fromCenter": 1 }))), Err("`fromCenter` must be true or false".into()));
assert_eq!(check_options(&map(json!({ "radius": 5 }))), Err("unknown Circle tool option `radius`".into()));
let t = CircleTool::default();
assert_eq!(t.check_option("fromCenter", &json!(false)), Ok(()));
assert_eq!(t.check_option("fromCenter", &json!(1)), Err("`fromCenter` must be true or false".into()));
assert_eq!(t.check_option("radius", &json!(5)), Err("unknown Circle tool option `radius`".into()));
}
/// The tool is in the Ellipse tool's group, after the Ellipse tool.
#[test]
fn the_circle_tool_follows_the_ellipse_tool() {
+2 -2
View File
@@ -78,8 +78,8 @@ const ROWS: &[Row] = &[
(&["star"], None, &["points"]),
// The Ellipse dialog's Anchors.
(&["ellipse"], None, &["anchors"]),
// Circle Tool Options (`circle::CircleTool`).
(&[crate::circle::ID], None, &["center", "radii", "diameter", "color", "standardAnchors", "dragThird"]),
// Circle Tool Options (`circle::CircleTool`) and the Control bar's From Center.
(&[crate::circle::ID], None, &["center", "radii", "diameter", "color", "standardAnchors", "dragThird", "fromCenter"]),
(&["freeTransform"], None, &["constrain"]),
// Shape Builder Tool Options (`builder::ShapeBuilderOptions`).
(
+21
View File
@@ -1111,6 +1111,27 @@ fn control_shown(app: crate::VectorcraftApp) -> Shown {
Shown::new(app, egui::vec2(1600.0, 300.0), super::control_bar)
}
/// With the Circle tool, the Control bar shows From Center unchecked; a click on it turns the option on and checks
/// it, and a second click turns it off and unchecks it.
#[test]
fn the_circle_tool_s_from_center_checkbox_sets_the_option() {
crate::i18n::set_current(crate::i18n::Lang::EN);
let mut app = crate::VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 200})).unwrap();
app.select_tool("circle");
let mut bar = control_shown(app);
let from_center = |bar: &Shown| bar.app().session.tool_options()["fromCenter"].clone();
assert_eq!(from_center(&bar), json!(false));
let target = bar.named("From Center");
assert!(!bar.checked(&target), "From Center starts unchecked");
for want in [true, false] {
bar.click("From Center").settle();
assert_eq!(from_center(&bar), json!(want));
let target = bar.named("From Center");
assert_eq!(bar.checked(&target), want, "the checkbox shows the option");
}
}
/// The Control bar's isolation button, if it shows: Isolate Selected Object, Exit Isolation Mode or Exit Symbol
/// Editing Mode.
fn isolation_button(bar: &mut Shown) -> Option<Target> {
+16 -2
View File
@@ -560,8 +560,9 @@ pub fn open_options(app: &mut VectorcraftApp, tool: &str) -> Result<serde_json::
}
/// The active tool's options in the Control bar: Mirror & Cut's axis and the side it keeps, Puppet
/// Warp's mesh and pins (set through `tool.setOption`). The Artboard tool's options are drawn by
/// [`crate::panels::artboards::control_bar`]. The bar's rows drop the controls that do not fit.
/// Warp's mesh and pins, the Circle tool's From Center (set through `tool.setOption`). The Artboard
/// tool's options are drawn by [`crate::panels::artboards::control_bar`]. The bar's rows drop the
/// controls that do not fit.
pub fn control_bar_options(app: &mut VectorcraftApp, ui: &mut Ui) {
// PLAN: assumed `addons::shapes::control_bar(app, ui)` and `dimension::controls(app, ui)` lose their `reserve` (chrome-w16 ranks).
if crate::addons::shapes::control_bar(app, ui) {
@@ -583,6 +584,9 @@ pub fn control_bar_options(app: &mut VectorcraftApp, ui: &mut Ui) {
if app.session.tool_id() == vectorcraft_tools::cropimage::ID {
return crop_options(app, ui);
}
if app.session.tool_id() == vectorcraft_tools::circle::ID {
return circle_options(app, ui);
}
if app.session.tool_id() != "mirrorCut" {
return;
}
@@ -600,6 +604,16 @@ pub fn control_bar_options(app: &mut VectorcraftApp, ui: &mut Ui) {
}
}
/// The Circle tool's Control bar: From Center (the first point is the circle's center and the
/// outline passes through the second), set through `tool.setOption`.
fn circle_options(app: &mut VectorcraftApp, ui: &mut Ui) {
let on = app.session.tool_options()["fromCenter"].as_bool().unwrap_or(false);
let picked = Checkbox::new(Bind::given(on)).label(tl!("From Center")).id_salt("fromCenter").show(ui).value().copied();
if let Some(value) = picked.filter(|value| *value != on) {
app.run("tool.setOption", json!({ "key": "fromCenter", "value": value })).ok();
}
}
/// Crop Image's cropping options: the cropped image's resolution (PPI: a list, with the
/// resolutions above what the image allows disabled, or a typed value), the reference point, the
/// box's X and Y (that point) and size (W, H) in the general unit with the link that keeps their
+18 -2
View File
@@ -7466,10 +7466,18 @@ one line (twice the triangle's area at most 10⁻¹⁰ of its longest side squar
canvas (4,000,000 pt from the origin), when `points` is not two or three pairs of numbers, and when `points` is left
out and the selection does not hold two or three anchor points of paths.
`shape.circleThroughPoints {center: [x, y], points: [[x, y]]}` draws the circle centered at `center` whose edge passes
through the one point in `points`: its radius is the distance between them. It returns an error and draws nothing when
the point is on `center`, when the circle would reach past the canvas, and when `center` is not a pair of numbers or
`points` does not hold exactly one pair. With `center`, the selected anchor points are not used. With or without
`center`, a circle whose radius is so small beside its coordinates that its opposite edges round to the same number is
an error, and nothing is drawn.
`anchors` sets where the circle's anchors go. With `"standard"`, the default, the circle has four anchors at 0°, 90°,
180° and 270°. With `"points"`, the circle is a plain path with an anchor exactly at each point, and more anchors
between them, evenly spaced, so that no curve turns more than a quarter of the circle: two points give four anchors,
and three points give four to six. Any other `anchors` value is an error (`` `anchors` must be one of standard, points ``), and nothing
and three points give four to six; with `center`, the one point gives an anchor at that point and three more, a quarter
turn apart. Any other `anchors` value is an error (`` `anchors` must be one of standard, points ``), and nothing
is drawn.
The Circle tool, after the Ellipse tool in its toolbar group, draws with this command. A drag from one point to
@@ -7489,7 +7497,7 @@ dragged out, it draws the circle on the diameter it drags out.
Circle Tool Options (`tool.options {tool: "circle"}`, or a double-click on the tool, dialog `circleOptions`) sets the
tool's options, which `tool.setOption {tool: "circle", values}` also sets and the preferences keep. All are on by
default, and `color` is `"blue"`:
default except `fromCenter`, which is off, and `color` is `"blue"`:
- `center`, `radii` and `diameter` (Show Center, Show Radii, Show Diameter) show or hide the cross at the center, the
lines from the center to the points and the diameter label. The diameter label also needs Measurement Labels on.
@@ -7504,6 +7512,14 @@ default, and `color` is `"blue"`:
point dragged back and let go on it, places nothing, and a click on the line through the first two points draws
nothing and keeps them. A drag from the first point still draws the circle on the diameter it drags out, and a drag
from a second point places it where it is let go. Switching `dragThird` drops the points placed so far.
- `fromCenter` (From Center, also a checkbox in the Control bar) on makes the first point the circle's center and the
outline passes through the second point, which follows the pointer. A drag from the center, or a click on the center
and then a click on a point of the outline, draws the circle with `center`. The second point snaps to Smart Guides,
anchor points included, as the others do, so a circle centered on one corner of a rectangle can pass exactly through
the opposite corner, with the diagonal as its radius. Shift keeps the second point at 45° steps from the center, and
Alt rounds the diameter (twice the distance from the center) to the nearest ruler tick. The tool shows one radius, to
the pointer. A second click on the center places nothing. The setting in force when the first point is placed applies
to that circle, and `dragThird` does not apply to it: switching `dragThird` keeps a placed center.
`tool.setOption` returns an error and changes none of the options when a value is not one the option takes
(`` `radii` must be true or false ``, `` `color` must be one of red, blue, magenta, green, black, gray ``) or the key is