Shapes: Circle Tool Options set what the Circle tool shows and where its anchors go

Double-clicking the Circle tool, or `tool.options {tool: "circle"}`, opens
Circle Tool Options. Show Center, Show Radii and Show Diameter switch the
center cross, the radius lines and the diameter label the tool shows while
a circle is drawn, and Color sets the color of the cross and the lines
(red, blue, magenta, green, black or gray). With Anchors at Standard
Positions off, the circle's anchors are at the points it was drawn
through, plus evenly spaced anchors between them so that no curve turns
more than a quarter of the circle. With Third Point by Dragging off, a
second click places the second point and a third click draws the circle
through the three; a double-click on the second point draws the circle on
the two. Every option is on by default, and the options are kept with the
preferences.

`shape.circleThroughPoints` takes `anchors: "standard"|"points"`.
`tool.setOption` rejects a value the Circle tool's options do not take.
This commit is contained in:
dotCooCoo
2026-11-17 16:30:02 -08:00
parent e6ec393062
commit 1901799b76
41 changed files with 838 additions and 22 deletions
+1
View File
@@ -139,6 +139,7 @@ Ranked; detail in [docs/roadmap.md](docs/roadmap.md) and [docs/gaps.md](docs/gap
- 2026-11-02: Mouse wheel over a closed font-family field in Character, Properties or Control changes selected text through the family list using saved font filters (excluding search text), one undo step per notch, stopping at the ends (#5253). Scores and estimates unchanged.
- 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-10-31: Pattern libraries: Window › Swatch Libraries › Patterns and the Swatches panel's library menu open Geometric Patterns, a built-in library of eleven pattern swatches (dots, stripes, checks, a grid and shapes); clicking one adds its pattern and swatch to the document, once, and applies it to the active fill or stroke (`swatch.library.add`).
- 2026-11-11: Pattern libraries: Patterns › Grit Textures, a second built-in pattern library, holds eight seamless black textures (Fine Grain, Coarse Grit, Sand, Speckle, Stipple, Scratches, Sparse Flecks and Dense Flecks) on tiles of 18 to 36 pt, each drawn the same way every time; marks that reach past a tile edge continue on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
- 2026-11-11: Pattern libraries: Patterns › Optical Effects, a third built-in pattern library, of VectorCraft's own designs, holds eight black wave, moiré and op-art tiles (Sine Bands, Ripple Lines, Interference Rings, Offset Rings, Warped Checks, Pinched Stripes, Chevron Pulse and Radiating Lenses) of 32 to 48 pt, each drawn the same way every time; each tile is one period of its design, and art that reaches past a tile edge continues on the next tile, so the tiles join without a seam (`swatch.library.add`). Scores and estimates unchanged.
+18 -6
View File
@@ -62,7 +62,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)} → {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), 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",
has_doc,
circle_through_points
),
@@ -414,20 +414,32 @@ fn ellipse(s: &mut Session, p: &Value) -> Result<Value> {
}
/// A live ellipse whose edge passes through two or three points: `points`, or the two or three
/// selected anchor points ([`selected_anchor_points`]). Two points are the ends of a diameter. One
/// undo step, named as an Ellipse tool drag is.
/// selected anchor points ([`selected_anchor_points`]). Two points are the ends of a diameter. With
/// `anchors: "points"` the circle is a plain path with an anchor at each point
/// ([`shapes::circle_with_anchors_at`]); otherwise it is a live ellipse. One undo step, named as an
/// 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`"))?,
};
let key = "anchors";
let at_points = match p.get(key).filter(|v| !v.is_null()).map(Value::as_str) {
None | Some(Some("standard")) => false,
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);
let live = LiveShape::Ellipse { w: r.width(), h: r.height(), pie: (0.0, 360.0), xf: Affine::translate(r.origin().to_vec2()) };
// Not pixel-aligned: the circle stays through the points.
let mut out = add_art_unaligned(s, "Ellipse", path_kind(live.to_path(), Some(live)))?;
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)))?
};
out["cx"] = json!(center.x);
out["cy"] = json!(center.y);
out["radius"] = json!(radius);
+29
View File
@@ -204,6 +204,35 @@ fn the_circle_is_not_moved_onto_the_pixel_grid() {
assert!(!node(&s, id).extras().pixel_aligned);
}
/// `anchors: "points"` puts an anchor exactly at each point, with one more on each half of a
/// diameter's circle; the circle is a plain path, not pixel-aligned, and one undo step. Any other
/// `anchors` value is an error and draws nothing.
#[test]
fn anchors_at_the_points_puts_an_anchor_at_each_point() {
let mut s = session();
s.execute("document.setup", &json!({"alignNewObjectsToPixelGrid": true})).unwrap();
let undo = undo_len(&s);
let points = [Point::new(0.3, 0.2), Point::new(80.6, 0.1), Point::new(0.4, 60.7)];
let pairs: Vec<Value> = points.iter().map(|p| json!([p.x, p.y])).collect();
let id = id_of(&s.execute(C, &json!({ "points": pairs, "anchors": "points" })).unwrap());
let n = node(&s, id);
let anchors: Vec<Point> = n.path_data().unwrap().subpaths[0].anchors.iter().map(|a| a.p).collect();
assert!(points.iter().all(|p| anchors.contains(p)), "{anchors:?}");
assert!(matches!(n.kind, NodeKind::Path { live: None, .. }), "{:?}", n.kind);
assert!(!n.extras().pixel_aligned);
assert_eq!(undo_len(&s), undo + 1);
let id = id_of(&s.execute(C, &json!({ "points": [[0, 0], [100, 0]], "anchors": "points" })).unwrap());
let anchors: Vec<Point> = node(&s, id).path_data().unwrap().subpaths[0].anchors.iter().map(|a| a.p).collect();
assert_eq!(anchors.len(), 4, "{anchors:?}");
assert_eq!((anchors[0], anchors[2]), (Point::new(0.0, 0.0), Point::new(100.0, 0.0)));
let (count, undo) = (object_count(&s), undo_len(&s));
for bad in [json!("corners"), json!(true), json!(4)] {
let e = s.execute(C, &json!({ "points": [[0, 0], [100, 0]], "anchors": bad })).unwrap_err().to_string();
assert!(e.contains("`anchors` must be one of standard, points"), "{e}");
}
assert_eq!((object_count(&s), undo_len(&s)), (count, undo));
}
fn view() -> ViewInfo {
ViewInfo { smart_guides: false, ..ViewInfo::default() }
}
+3
View File
@@ -1369,6 +1369,9 @@ impl Session {
}
// Every value is checked before any is set, so an invalid one changes nothing.
vectorcraft_tools::builder::check_builder_options(tool.unwrap_or(self.tool.id()), &values)?;
if tool.unwrap_or(self.tool.id()) == vectorcraft_tools::circle::ID {
vectorcraft_tools::circle::check_options(&values)?;
}
if tool.unwrap_or(self.tool.id()) == vectorcraft_tools::cropimage::ID {
use vectorcraft_tools::cropimage as crop;
// The most the selected image can be cropped to, when one is selected.
+80
View File
@@ -367,6 +367,53 @@ pub fn circle_through_points(points: &[Point]) -> Option<(Point, f64)> {
circle.filter(|(c, r)| c.is_finite() && r.is_finite() && *r > 0.0)
}
/// The circle at `center` with `radius` as a closed path whose anchors are `points` (points on the
/// circle, as [`circle_through_points`] gives it) plus as many more as split each arc between two
/// of them into equal parts of at most a quarter turn. The path starts at the first point and runs
/// as [`ellipse`] does (left, top, right on the page); each curve's handles are 4/3·tan(θ/4) of
/// the radius along the tangents at its ends (θ, its turn). A point given twice is one anchor;
/// with no points it starts at the left, as [`ellipse`] does.
pub fn circle_with_anchors_at(center: Point, radius: f64, points: &[Point]) -> PathData {
let quarter = PI / 2.0;
let angle = |p: Point| (p.y - center.y).atan2(p.x - center.x);
let start = points.first().map_or(PI, |p| angle(*p));
// (turn from the first point, the point itself).
let mut placed: Vec<(f64, Point)> = points.iter().map(|p| ((angle(*p) - start).rem_euclid(TAU), *p)).collect();
placed.sort_by(|a, b| a.0.total_cmp(&b.0));
placed.dedup_by(|a, b| a.1 == b.1);
if placed.is_empty() {
placed.push((0.0, Point::new(center.x - radius, center.y)));
}
let on_circle = |t: f64| Point::new(center.x + radius * (start + t).cos(), center.y + radius * (start + t).sin());
// Every anchor: (turn, position), the given points where they are and the others on the circle.
let mut turns: Vec<(f64, Point)> = Vec::new();
for (i, &(t, p)) in placed.iter().enumerate() {
turns.push((t, p));
let next = placed.get(i + 1).map_or(TAU, |n| n.0);
let gap = next - t;
// At most 4 parts for the whole turn: a gap is never more than a full turn.
let parts = (gap / quarter - 1e-9).ceil().clamp(1.0, 4.0);
for k in 1..parts as u32 {
let tk = t + gap * f64::from(k) / parts;
turns.push((tk, on_circle(tk)));
}
}
let n = turns.len();
let anchors = (0..n)
.filter_map(|i| {
let &(t, p) = turns.get(i)?;
let prev = if i == 0 { turns.last()?.0 - TAU } else { turns.get(i - 1)?.0 };
let next = turns.get(i + 1).map_or(TAU, |n| n.0);
// The unit tangent along the run (y down: increasing angle).
let a = start + t;
let tangent = Vec2::new(-a.sin(), a.cos());
let handle = |turn: f64| radius * 4.0 / 3.0 * (turn / 4.0).tan();
Some(Anchor { p, h_in: p - tangent * handle(t - prev), h_out: p + tangent * handle(next - t), kind: AnchorKind::Smooth })
})
.collect();
PathData::single(SubPath::new(anchors, true))
}
/// Regular polygon with `sides` (≥ 3), first vertex straight up from the centre.
pub fn polygon(center: Point, radius: f64, sides: u32, rotation_deg: f64) -> PathData {
let n = sides.max(3);
@@ -781,6 +828,39 @@ mod tests {
}
}
/// The anchors are the given points exactly, plus enough more that no curve turns more than a
/// quarter; every anchor and every curve's middle lies on the circle, and the path starts at
/// the first point.
#[test]
fn a_circle_with_its_anchors_at_given_points() {
use kurbo::ParamCurve;
let (a, b, c) = (Point::new(8.0, 0.0), Point::new(0.0, 6.0), Point::ORIGIN);
let center = Point::new(4.0, 3.0);
for (points, count) in [(&[a, b][..], 4), (&[a, b, c][..], 5), (&[b, a, c, b][..], 5), (&[][..], 4)] {
let path = circle_with_anchors_at(center, 5.0, points);
let sub = &path.subpaths[0];
assert!(sub.closed, "{points:?}");
assert_eq!(sub.anchors.len(), count, "{points:?}: {sub:?}");
for p in points {
assert!(sub.anchors.iter().any(|q| q.p == *p), "{p:?} is an anchor: {sub:?}");
}
if let Some(first) = points.first() {
assert_eq!(sub.anchors[0].p, *first);
}
for q in &sub.anchors {
assert!((q.p.distance(center) - 5.0).abs() < 1e-9, "{q:?}");
}
for seg in path.to_bezpath().segments() {
let turn = {
let (p0, p1) = (seg.start() - center, seg.end() - center);
p0.cross(p1).atan2(p0.dot(p1))
};
assert!(turn > 0.0 && turn <= PI / 2.0 + 1e-9, "{turn} for {seg:?}");
assert!((seg.eval(0.5).distance(center) - 5.0).abs() < 5.0 * 1e-3, "{seg:?}");
}
}
}
/// Nearly on one line: a point 10⁻⁴ off a chord 2000 long still gives the circle (its sagitta
/// formula `r = (h² + (L/2)²) / 2h`), and its center sits on the chord's perpendicular
/// bisector; a point 10⁻¹² off it does not.
+205 -14
View File
@@ -15,8 +15,17 @@
//! circle passes through the points (two are the same, three lie on one line) or the circle would
//! 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".
//!
//! 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`]);
//! `standardAnchors` off puts the circle's anchors at the points it was drawn through instead of
//! 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.
use serde_json::{Value, json};
use serde_json::{Map, Value, json};
use vectorcraft_doc::MAX_COORD;
use vectorcraft_geom::{Point, Rect, Vec2, shapes};
@@ -34,6 +43,71 @@ const REACH_PX: f64 = 3.0;
/// The longest outline (screen points) the preview draws dashed, about 7,000 dashes.
const DASHED_PX: f64 = 50_000.0;
/// The colors the center cross and the radius lines can be drawn in, by option value. Blue is the
/// feedback color the other drawing tools use.
pub const COLORS: &[(&str, [u8; 3])] = &[
("red", [0xe5, 0x2d, 0x27]),
("blue", crate::draw2::FEEDBACK),
("magenta", [0xd6, 0x2c, 0xd6]),
("green", [0x1f, 0xb4, 0x4b]),
("black", [0x00, 0x00, 0x00]),
("gray", [0x80, 0x80, 0x80]),
];
/// The option keys that are true or false.
const SWITCHES: &[&str] = &["center", "radii", "diameter", "standardAnchors", "dragThird"];
/// The tool's options (see the module comment).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
struct Options {
center: bool,
radii: bool,
diameter: bool,
/// An entry of [`COLORS`].
color: usize,
standard_anchors: bool,
drag_third: bool,
}
impl Default for Options {
fn default() -> Self {
Options { center: true, radii: true, diameter: true, color: 1, standard_anchors: true, drag_third: true }
}
}
impl Options {
fn switch(&mut self, key: &str) -> Option<&mut bool> {
Some(match key {
"center" => &mut self.center,
"radii" => &mut self.radii,
"diameter" => &mut self.diameter,
"standardAnchors" => &mut self.standard_anchors,
"dragThird" => &mut self.drag_third,
_ => return None,
})
}
}
/// Is every value in `values` one the tool takes? `tool.setOption` checks them all before setting
/// any; [`Tool::set_option`] skips a value it cannot read.
pub fn check_options(values: &Map<String, Value>) -> Result<(), String> {
for (key, v) in values {
if SWITCHES.contains(&key.as_str()) {
if !v.is_boolean() {
return Err(format!("`{key}` must be true or false"));
}
} else if key == "color" {
if !v.as_str().is_some_and(|s| COLORS.iter().any(|(name, _)| *name == s)) {
let names: Vec<&str> = COLORS.iter().map(|(name, _)| *name).collect();
return Err(format!("`{key}` must be one of {}", names.join(", ")));
}
} else {
return Err(format!("unknown Circle tool option `{key}`"));
}
}
Ok(())
}
/// The press in progress.
#[derive(Clone, Copy, Debug, PartialEq)]
enum Press {
@@ -46,23 +120,36 @@ enum Press {
/// places the third point and the circle passes through `snapped`. A press within
/// [`REACH_PX`] of the first point, or one that snaps to it (`on_first`), is a press on it: let
/// go there it places nothing, and dragged out it draws the circle on the diameter it drags out.
/// With `dragThird` off, a drag moves the second point and the release places it.
Second { at: Point, snapped: Point, from: Point, on_first: bool, dragged: bool },
/// With `dragThird` off, the press after the second point was placed, at `at` (snapped). Let go
/// on the second point (`on_second`), it draws the circle on the two points; let go on the
/// first point it places nothing; otherwise it draws the circle through the three points.
Third { at: Point, from: Point, on_first: bool, on_second: bool, dragged: bool },
}
#[derive(Default)]
pub struct CircleTool {
snap: DrawSnap,
options: Options,
/// The first point, placed by a click (or by the press of a drag in progress).
first: Option<Point>,
/// With `dragThird` off, the second point, placed by a click where it is shown (snapped, with
/// Alt's rounding of the diameter when Alt was held), and where the click let go: a press near
/// either is a press on the second point, so the second click of a double-click finds it even
/// where Alt's rounding moved it away from the pointer.
second: Option<(Point, Point)>,
press: Option<Press>,
/// Where the pointer is, snapped: the point the next press or release places.
pointer: Option<Point>,
}
/// The command the tool runs for `points`.
fn command(points: &[Point]) -> (String, Value) {
/// 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();
("shape.circleThroughPoints".into(), json!({ "points": pairs }))
let params = if standard_anchors { json!({ "points": pairs }) } else { json!({ "points": pairs, "anchors": "points" }) };
("shape.circleThroughPoints".into(), params)
}
/// The circle through two points (the ends of a diameter) or three, as `shape.circleThroughPoints`
@@ -91,35 +178,49 @@ fn too_large(points: &[Point]) -> bool {
impl CircleTool {
fn clear(&mut self) {
self.first = None;
self.second = None;
self.press = None;
self.pointer = None;
self.snap.clear();
}
/// How the second point keeps to the first: Shift's 45° steps and the construction guides.
/// 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> {
self.first.map(|a| Leave::segment(cx, a, mods.shift))
self.first.filter(|_| self.second.is_none()).map(|a| Leave::segment(cx, a, mods.shift))
}
/// The points the circle passes through as the tool shows it now.
fn points(&self) -> Vec<Point> {
let mut out: Vec<Point> = self.first.into_iter().collect();
if let Some((b, _)) = self.second {
out.push(b);
out.extend(self.pointer);
return out;
}
match self.press {
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)),
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 { snapped, dragged: true, .. }) => {
out.push(snapped);
out.extend(self.pointer);
}
Some(Press::Third { .. }) => {}
}
out
}
/// The second point as the tool shows it: none for a press on the first point.
fn second(&self) -> Option<Point> {
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, dragged: false, at, .. }) => Some(at),
Some(Press::Second { on_first: false, dragged: true, snapped, .. }) => Some(snapped),
_ => None,
@@ -133,9 +234,25 @@ impl CircleTool {
if circle_of(points).is_none() {
return vec![];
}
let (c, v) = command(points);
let (c, v) = command(points, self.options.standard_anchors);
vec![Action::Exec(c, v)]
}
/// With `dragThird` off, the release of a press after the second point was placed: on the
/// second point it draws the circle on the two points, on the first it places nothing, and
/// elsewhere it draws the circle through the three, or keeps the points where none passes
/// through them.
fn third_up(&mut self, at: Point, on_first: bool, on_second: bool, dragged: bool) -> Vec<Action> {
let (Some(a), Some((b, _))) = (self.first, self.second) else { return vec![] };
if on_second && !dragged {
return self.draw(&[a, b]);
}
if (on_first && !dragged) || circle_of(&[a, b, at]).is_none() {
self.snap.clear();
return vec![];
}
self.draw(&[a, b, at])
}
}
impl Tool for CircleTool {
@@ -151,10 +268,20 @@ impl Tool for CircleTool {
PointerKind::Move => {
let leave = self.leave(cx, ev.mods);
let p = self.snap.hover(cx, ev.pos, &[], leave.as_ref());
self.pointer = Some(self.first.map_or(p, |a| round_diameter(cx, a, p, ev.mods)));
// 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)));
vec![]
}
PointerKind::Down => {
if let (Some(a), Some((b, clicked))) = (self.first, self.second) {
let at = self.snap.press(cx, ev.pos, &[], None);
let on = |q: Point| at == q || ev.pos.distance(q) <= cx.tol(REACH_PX);
let on_second = on(b) || ev.pos.distance(clicked) <= cx.tol(REACH_PX);
self.press = Some(Press::Third { at, from: ev.pos, on_first: on(a), on_second, dragged: false });
self.pointer = Some(at);
return vec![];
}
match self.first {
None => {
let at = self.snap.press(cx, ev.pos, &[], None);
@@ -174,7 +301,23 @@ impl Tool for CircleTool {
vec![]
}
PointerKind::Drag => {
let drag_third = self.options.drag_third;
let first = self.first;
match &mut self.press {
// With `dragThird` off, the second point follows the pointer as it does before
// the press.
Some(Press::Second { at, snapped, from, on_first: false, dragged }) if !drag_third => {
*dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX);
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));
self.pointer = Some(*at);
}
Some(Press::Third { at, from, dragged, .. }) => {
*dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX);
*at = self.snap.drag(cx, ev.pos, None);
self.pointer = Some(*at);
}
Some(Press::First { at, from, dragged }) => {
*dragged |= ev.pos.distance(*from) >= cx.tol(DRAG_PX);
let leave = Leave::segment(cx, *at, ev.mods.shift);
@@ -197,6 +340,16 @@ impl Tool for CircleTool {
vec![]
}
PointerKind::Up => match (self.press.take(), self.first, self.pointer) {
(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 => {
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.
(Some(Press::First { .. }), ..) => {
@@ -269,13 +422,19 @@ impl Tool for CircleTool {
// than DASHED_PX on screen is drawn solid instead.
let dashed = std::f64::consts::TAU * r <= cx.tol(DASHED_PX);
o.push(Overlay::Path { path, color, width: 1.0, dashed });
for p in &points {
o.push(Overlay::Line { a: c, b: *p, color, dashed: false });
let opts = self.options;
let lines = COLORS.get(opts.color).map_or(color, |(_, rgb)| *rgb);
if opts.radii {
for p in &points {
o.push(Overlay::Line { a: c, b: *p, color: lines, dashed: false });
}
}
let arm = cx.tol(CROSS_PX);
o.push(Overlay::Line { a: c - Vec2::new(arm, 0.0), b: c + Vec2::new(arm, 0.0), color, dashed: false });
o.push(Overlay::Line { a: c - Vec2::new(0.0, arm), b: c + Vec2::new(0.0, arm), color, dashed: false });
if let Some(p) = self.pointer.filter(|_| cx.measurement_labels) {
if opts.center {
let arm = cx.tol(CROSS_PX);
o.push(Overlay::Line { a: c - Vec2::new(arm, 0.0), b: c + Vec2::new(arm, 0.0), color: lines, dashed: false });
o.push(Overlay::Line { a: c - Vec2::new(0.0, arm), b: c + Vec2::new(0.0, arm), color: lines, dashed: false });
}
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)) {
@@ -290,6 +449,38 @@ impl Tool for CircleTool {
fn cursor(&self, _cx: &ToolContext, _p: Point, _mods: Mods) -> Cursor {
Cursor::Crosshair
}
fn options(&self) -> Value {
let o = self.options;
let color = COLORS.get(o.color).map_or("blue", |(name, _)| *name);
json!({
"center": o.center,
"radii": o.radii,
"diameter": o.diameter,
"color": color,
"standardAnchors": o.standard_anchors,
"dragThird": o.drag_third,
})
}
/// Sets one option; a value the option does not take leaves it as it was. Switching
/// `dragThird` drops the points placed so far.
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)) {
self.options.color = i;
}
return;
}
let Some(on) = value.as_bool() else { return };
let was = self.options.drag_third;
if let Some(switch) = self.options.switch(key) {
*switch = on;
}
if self.options.drag_third != was {
self.clear();
}
}
}
#[cfg(test)]
+175
View File
@@ -94,6 +94,181 @@ fn a_click_and_a_drag_draw_the_circle_through_three_points() {
assert_eq!(t.pointer(&cx, &ev(PointerKind::Up, (300.0, 360.0), Mods::default())), circle(&[(300.0, 300.0), (380.0, 300.0), (300.0, 360.0)]));
}
/// The lines the tool shows from the center `c`: (radius lines, arms of the center cross), each
/// with its color.
fn annotations(o: &[Overlay], c: Point) -> (Vec<[u8; 3]>, Vec<[u8; 3]>) {
let (mut radii, mut cross) = (vec![], vec![]);
for o in o {
if let Overlay::Line { a, b, color, .. } = o {
if *a == c {
radii.push(*color);
} else if a.midpoint(*b).distance(c) < 1e-9 {
cross.push(*color);
}
}
}
(radii, cross)
}
/// `center`, `radii` and `diameter` show or hide the center cross, the radius lines and the
/// diameter label, each on its own, and `color` is the color of the cross and the lines; the
/// outline stays in the feedback color. Each option lasts in [`Tool::options`].
#[test]
fn the_options_show_or_hide_the_center_radii_and_diameter_in_their_color() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let mut t = CircleTool::default();
click(&mut t, &cx, (300.0, 300.0));
t.pointer(&cx, &ev(PointerKind::Move, (380.0, 360.0), Mods::default()));
let c = Point::new(340.0, 330.0);
let blue = crate::draw2::FEEDBACK;
assert_eq!(annotations(&t.overlays(&cx), c), (vec![blue; 2], vec![blue; 2]));
let diameter = |t: &CircleTool| t.overlays(&cx).iter().any(|o| matches!(o, Overlay::Measure { .. }));
assert!(diameter(&t));
t.set_option("center", &json!(false));
assert_eq!(annotations(&t.overlays(&cx), c), (vec![blue; 2], vec![]));
t.set_option("radii", &json!(false));
assert_eq!(annotations(&t.overlays(&cx), c), (vec![], vec![]));
assert!(diameter(&t));
t.set_option("diameter", &json!(false));
assert!(!diameter(&t));
t.set_option("center", &json!(true));
t.set_option("radii", &json!(true));
t.set_option("color", &json!("red"));
let red = [0xe5, 0x2d, 0x27];
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}));
// 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);
}
assert_eq!(t.options()["color"], json!("red"));
assert_eq!((&t.options()["center"], &t.options()["radii"]), (&json!(true), &json!(true)));
}
/// With `standardAnchors` off, the circle's anchors go at the points it was drawn through.
#[test]
fn anchors_at_the_points_asks_for_them() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let mut t = CircleTool::default();
t.set_option("standardAnchors", &json!(false));
let acts = drag(&mut t, &cx, (300.0, 300.0), &[(380.0, 360.0)], Mods::default());
let points = json!([[300.0, 300.0], [380.0, 360.0]]);
assert_eq!(acts, vec![Action::Exec("shape.circleThroughPoints".into(), json!({"points": points, "anchors": "points"}))]);
}
/// With `dragThird` off, a second click places the second point and a third click draws the circle
/// through the three; a click on the second point again (as a double-click there does) draws the
/// circle on the two; a second point let go on the first places nothing; a drag from the first
/// point still draws the circle on its diameter.
#[test]
fn with_third_point_by_dragging_off_three_clicks_draw_the_circle() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let mut t = CircleTool::default();
t.set_option("dragThird", &json!(false));
click(&mut t, &cx, (300.0, 300.0));
assert_eq!(click(&mut t, &cx, (380.0, 300.0)), vec![]);
t.pointer(&cx, &ev(PointerKind::Move, (300.0, 360.0), Mods::default()));
let o = t.overlays(&cx);
assert!(near(preview(&o).expect("the circle through the three is shown"), Rect::new(290.0, 280.0, 390.0, 380.0)), "{o:?}");
assert_eq!(o.iter().filter(|o| matches!(o, Overlay::Anchor { .. })).count(), 2, "{o:?}");
// A click on the first point places nothing and keeps both points.
assert_eq!(click(&mut t, &cx, (300.0, 300.0)), vec![]);
assert!(t.busy());
assert_eq!(click(&mut t, &cx, (300.0, 360.0)), circle(&[(300.0, 300.0), (380.0, 300.0), (300.0, 360.0)]));
assert!(!t.busy());
// The events of a double-click on the second point: its first click places it, the second
// draws the circle on the two points, and the double-click event that follows adds nothing.
click(&mut t, &cx, (100.0, 100.0));
assert_eq!(click(&mut t, &cx, (200.0, 100.0)), vec![]);
assert_eq!(click(&mut t, &cx, (200.0, 100.0)), circle(&[(100.0, 100.0), (200.0, 100.0)]));
assert_eq!(t.pointer(&cx, &ev(PointerKind::DoubleClick, (200.0, 100.0), Mods::default())), vec![]);
assert!(!t.busy());
// A drag that moves the second point places it where it is let go.
click(&mut t, &cx, (100.0, 100.0));
assert_eq!(drag(&mut t, &cx, (150.0, 100.0), &[(180.0, 100.0), (200.0, 100.0)], Mods::default()), vec![]);
assert_eq!(click(&mut t, &cx, (100.0, 200.0)), circle(&[(100.0, 100.0), (200.0, 100.0), (100.0, 200.0)]));
// Three points on one line keep the two placed: the next click elsewhere draws.
click(&mut t, &cx, (100.0, 100.0));
click(&mut t, &cx, (200.0, 100.0));
assert_eq!(click(&mut t, &cx, (300.0, 100.0)), vec![]);
assert_eq!(click(&mut t, &cx, (100.0, 200.0)), circle(&[(100.0, 100.0), (200.0, 100.0), (100.0, 200.0)]));
// A second press elsewhere, dragged back and let go on the first point, places nothing: the
// next click places the second point.
click(&mut t, &cx, (100.0, 100.0));
assert_eq!(drag(&mut t, &cx, (200.0, 100.0), &[(150.0, 100.0), (100.0, 100.0)], Mods::default()), vec![]);
assert!(t.busy());
assert_eq!(click(&mut t, &cx, (200.0, 100.0)), vec![]);
assert_eq!(click(&mut t, &cx, (100.0, 200.0)), circle(&[(100.0, 100.0), (200.0, 100.0), (100.0, 200.0)]));
// A drag from the first point.
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)]));
// Switching the option drops the points placed so far.
click(&mut t, &cx, (100.0, 100.0));
t.set_option("dragThird", &json!(true));
assert!(!t.busy());
}
/// With `dragThird` off, an Alt-click places the second point where Alt's rounding of the diameter
/// puts it (88 pt rounds to 90 pt at 100%), and the tool shows it there: the marker, the preview,
/// the circle on the two points and the circle through three all use it.
#[test]
fn an_alt_click_places_the_second_point_where_it_is_shown() {
let (d, _) = doc_with_rect();
let (s, p) = (Selection::default(), paint());
let cx = ToolContext { smart_guides: false, ..cx(&d, &s, &p) };
let alt = Mods { alt: true, ..Mods::default() };
let mut t = CircleTool::default();
t.set_option("dragThird", &json!(false));
click(&mut t, &cx, (300.0, 300.0));
t.pointer(&cx, &ev(PointerKind::Down, (388.0, 300.0), alt));
t.pointer(&cx, &ev(PointerKind::Up, (388.0, 300.0), alt));
t.pointer(&cx, &ev(PointerKind::Move, (300.0, 390.0), Mods::default()));
let o = t.overlays(&cx);
let second = Point::new(390.0, 300.0);
assert!(o.iter().any(|o| matches!(o, Overlay::Anchor { p, .. } if p.distance(second) < 1e-9)), "{o:?}");
// (300, 300), (390, 300) and (300, 390): center (345, 345), radius 45·√2.
let r = 45.0 * 2f64.sqrt();
assert!(near(preview(&o).unwrap(), Rect::new(345.0 - r, 345.0 - r, 345.0 + r, 345.0 + r)), "{o:?}");
assert_eq!(click(&mut t, &cx, (300.0, 390.0)), circle(&[(300.0, 300.0), (390.0, 300.0), (300.0, 390.0)]));
click(&mut t, &cx, (300.0, 300.0));
t.pointer(&cx, &ev(PointerKind::Down, (388.0, 300.0), alt));
t.pointer(&cx, &ev(PointerKind::Up, (388.0, 300.0), alt));
assert_eq!(click(&mut t, &cx, (390.0, 300.0)), circle(&[(300.0, 300.0), (390.0, 300.0)]));
// In inches the ticks are farther apart, and the rounding can move the point more than the
// 3 screen points a click reaches: the second click of a double-click, where the first let go,
// still draws the circle on the two points, at the rounded point.
let inches = ToolContext { unit: vectorcraft_doc::Unit::Inches, ..cx };
let d = 94.4;
let rounded = vectorcraft_doc::Unit::Inches.snap_to_ruler_tick(d, 1.0);
assert!((rounded - d).abs() > 3.0, "{rounded}");
click(&mut t, &inches, (300.0, 300.0));
t.pointer(&inches, &ev(PointerKind::Down, (300.0 + d, 300.0), alt));
t.pointer(&inches, &ev(PointerKind::Up, (300.0 + d, 300.0), alt));
assert_eq!(click(&mut t, &inches, (300.0 + d, 300.0)), circle(&[(300.0, 300.0), (300.0 + rounded, 300.0)]));
}
/// `tool.setOption`'s check takes the values the options take and nothing else.
#[test]
fn check_options_takes_only_the_values_the_options_take() {
let ok = json!({"center": false, "radii": true, "diameter": false, "color": "gray", "standardAnchors": false, "dragThird": false});
assert_eq!(check_options(ok.as_object().unwrap()), Ok(()));
for (bad, error) in [
(json!({"center": 1}), "`center` must be true or false"),
(json!({"dragThird": null}), "`dragThird` must be true or false"),
(json!({"color": "orange"}), "`color` must be one of red, blue, magenta, green, black, gray"),
(json!({"colour": "red"}), "unknown Circle tool option `colour`"),
] {
assert_eq!(check_options(bad.as_object().unwrap()), Err(error.to_string()), "{bad}");
}
}
/// Three points on one line show no circle, and the release draws nothing and starts afresh. A
/// circle past the canvas is not shown either.
#[test]
+2
View File
@@ -53,6 +53,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"]),
(&["freeTransform"], None, &["constrain"]),
// Shape Builder Tool Options (`builder::ShapeBuilderOptions`).
(
+2
View File
@@ -23,6 +23,7 @@ pub mod brush_replace_art;
pub mod bullets_numbering;
pub mod char_style_options;
pub mod check_spelling;
pub mod circle_options;
pub mod color_balance;
pub mod color_guide_options;
mod color_picker;
@@ -449,6 +450,7 @@ registry! {
FreehandOptions: [freehand::KIND] => freehand::SPEC,
ShapeBuilderOptions: [shape_builder_options::KIND] => shape_builder_options::SPEC,
ObjectsOnPathOptions: [objects_on_path_options::KIND] => objects_on_path_options::SPEC,
CircleOptions: [circle_options::KIND] => circle_options::SPEC,
FlareOptions: [flare_options::KIND] => flare_options::SPEC,
SymbolOptions: [symbol_options::KIND] => symbol_options::SPEC,
DeleteSymbol: [symbol_delete::KIND] => symbol_delete::SPEC,
@@ -0,0 +1,169 @@
//! Circle Tool Options (double-click the Circle tool, or `tool.options`): Show Center, Show Radii
//! and Show Diameter switch the center cross, the radius lines and the diameter label the tool
//! shows while a circle is drawn; Color is the color of the cross and the lines; Anchors at
//! Standard Positions off puts the circle's anchors at the points it was drawn through; Third
//! Point by Dragging off places the second point with a click and the third with another. OK sets
//! them with `tool.setOption {tool: "circle", values}`; they last across tool switches and are
//! saved with the preferences.
use serde_json::{Map, Value, json};
use vectorcraft_tools::circle::{COLORS, ID as TOOL};
use super::{DialogSpec, run_and_close};
use crate::state::Dialog;
use crate::{VectorcraftApp, widgets};
/// The dialog kind of Circle Tool Options.
pub const KIND: &str = "circleOptions";
pub(super) const SPEC: DialogSpec = DialogSpec { heading, body, confirm, min_width: 300.0, ..DialogSpec::FORM };
/// The options the dialog edits, in the order it shows its check boxes, with their labels.
const SWITCHES: [(&str, &str); 5] = [
("center", "Show Center"),
("radii", "Show Radii"),
("diameter", "Show Diameter"),
("standardAnchors", "Anchors at Standard Positions"),
("dragThird", "Third Point by Dragging"),
];
/// The labels of [`COLORS`], in its order.
const COLOR_LABELS: [&str; 6] = ["Red", "Blue", "Magenta", "Green", "Black", "Gray"];
/// Width of the label column.
const LABEL_W: f32 = 60.0;
fn heading(_: &Dialog) -> String {
let label = vectorcraft_tools::tool_info(TOOL).map_or("", |t| t.label);
crate::i18n::fmt(tl!("{tool} Options"), &[("tool", tl!(label))])
}
/// Open the tool's options with their current values.
pub fn open(app: &mut VectorcraftApp) -> Value {
let o = app.session.tool_options_of(TOOL);
let keys = SWITCHES.iter().map(|(key, _)| *key).chain(["color"]);
let fields: Map<String, Value> = keys.filter_map(|key| Some((key.to_string(), o.get(key)?.clone()))).collect();
app.ui.dialog = Some(Dialog { kind: KIND.into(), fields });
json!({ "dialog": KIND })
}
fn check(ui: &mut egui::Ui, d: &mut Dialog, key: &str, label: &str) {
let on = d.bool(key);
if widgets::check(ui, tl!(label), on, true) {
d.fields.insert(key.into(), json!(!on));
}
}
fn body(_app: &mut VectorcraftApp, ui: &mut egui::Ui, d: &mut Dialog) -> bool {
for (key, label) in &SWITCHES[..3] {
check(ui, d, key, label);
}
let color = d.str("color");
let at = COLORS.iter().position(|(name, _)| *name == color).unwrap_or(1);
widgets::label_row(ui, tl!("Color:"), LABEL_W, |ui| {
let shown = COLOR_LABELS.get(at).copied().unwrap_or("Blue");
if let Some((name, _)) =
widgets::dropdown_named(ui, "circle-options-color", Some(tl!("Color:")), shown, &COLOR_LABELS, 110.0).and_then(|i| COLORS.get(i))
{
d.fields.insert("color".into(), json!(name));
}
});
ui.add_space(8.0);
for (key, label) in &SWITCHES[3..] {
check(ui, d, key, label);
}
false
}
/// OK: set the tool's options.
fn confirm(app: &mut VectorcraftApp, d: &Dialog) -> Result<Value, String> {
let keys = SWITCHES.iter().map(|(key, _)| *key).chain(["color"]);
let values: Map<String, Value> = keys.filter_map(|key| Some((key.to_string(), d.fields.get(key)?.clone()))).collect();
run_and_close(app, "tool.setOption", json!({ "tool": TOOL, "values": values }))
}
#[cfg(test)]
mod tests {
use super::*;
use vectorcraft_engine::Session;
fn app() -> VectorcraftApp {
let mut app = VectorcraftApp::new(Session::new(), Default::default());
app.run("file.new", json!({"width": 400, "height": 400})).unwrap();
app
}
/// The labels the open dialog paints.
fn painted(app: &mut VectorcraftApp) -> String {
crate::tests_labels::painted_text(app, |app, ui| super::super::show(app, ui.ctx()))
}
/// Every label the dialog shows has a row for each of [`COLORS`].
#[test]
fn every_color_has_a_label() {
assert_eq!(COLOR_LABELS.len(), COLORS.len());
for (label, (name, _)) in COLOR_LABELS.iter().zip(COLORS) {
assert_eq!(label.to_lowercase(), *name);
}
}
#[test]
fn double_clicking_the_tool_opens_its_options_and_ok_sets_them() {
let mut app = app();
let o = app.session.tool_options_of(TOOL);
for key in ["center", "radii", "diameter", "standardAnchors", "dragThird"] {
assert_eq!(o[key], json!(true), "{key}");
}
assert_eq!(o["color"], json!("blue"));
let r = app.run("tool.options", json!({"tool": TOOL})).unwrap();
assert_eq!(r["dialog"], json!(KIND));
let text = painted(&mut app);
for label in [
"Circle Tool Options",
"Show Center",
"Show Radii",
"Show Diameter",
"Color:",
"Blue",
"Anchors at Standard Positions",
"Third Point by Dragging",
"OK",
"Cancel",
] {
assert!(text.contains(label), "{label} in {text}");
}
let d = app.ui.dialog.as_mut().unwrap();
for key in ["radii", "standardAnchors", "dragThird"] {
assert!(d.bool(key), "{key}");
d.fields.insert(key.into(), json!(false));
}
d.fields.insert("color".into(), json!("magenta"));
super::super::confirm(&mut app).unwrap();
assert!(app.ui.dialog.is_none());
let o = app.session.tool_options_of(TOOL);
let got: Vec<&Value> = ["center", "radii", "diameter", "standardAnchors", "dragThird", "color"].iter().map(|k| &o[*k]).collect();
assert_eq!(got, [&json!(true), &json!(false), &json!(true), &json!(false), &json!(false), &json!("magenta")]);
// They last while another tool is chosen, and the dialog opens on them again.
app.select_tool(TOOL);
app.select_tool("selection");
app.run("tool.options", json!({"tool": TOOL})).unwrap();
let d = app.ui.dialog.as_ref().unwrap();
assert!(!d.bool("standardAnchors") && d.bool("center"));
assert_eq!(d.str("color"), "magenta");
}
/// `tool.setOption` takes only the values the options take, and an invalid one changes none.
#[test]
fn invalid_values_are_errors_and_change_nothing() {
let mut app = app();
for (values, error) in [
(json!({"center": false, "radii": "no"}), "`radii` must be true or false"),
(json!({"center": false, "color": "orange"}), "`color` must be one of red, blue, magenta, green, black, gray"),
(json!({"center": false, "size": 3}), "unknown Circle tool option `size`"),
] {
let e = app.run("tool.setOption", json!({"tool": TOOL, "values": values})).unwrap_err();
assert!(e.contains(error), "{e}");
assert_eq!(app.session.tool_options_of(TOOL)["center"], json!(true));
}
}
}
+4
View File
@@ -467,6 +467,10 @@ font-technology Variable Променливи
Circle Кръг
Circle Tool Инструмент Кръг
Circle too large Кръгът е твърде голям
Show Radii Показване на радиуси
Show Diameter Показване на диаметър
Anchors at Standard Positions Опорни точки в стандартни позиции
Third Point by Dragging Трета точка чрез плъзгане
Classic Defaults Класически по подразбиране
Clean Up… Почистване…
Clear Изчистване
Can't render this file because it is too large.
+4
View File
@@ -4527,6 +4527,10 @@ font-technology Variable Varijabilni
Circle Krug
Circle Tool Alat za krug
Circle too large Krug je prevelik
Show Radii Prikaži poluprečnike
Show Diameter Prikaži prečnik
Anchors at Standard Positions Sidrene tačke na standardnim položajima
Third Point by Dragging Treća tačka povlačenjem
Clip to Art Isijeci prema crtežu
Colorize Oboji
Gamma Gama
Can't render this file because it contains an unexpected character in line 2 and column 73.
+4
View File
@@ -702,6 +702,10 @@ antiAlias Sharp Nítid
Circle Cercle
Circle Tool Eina de cercle
Circle too large El cercle és massa gran
Show Radii Mostra els radis
Show Diameter Mostra el diàmetre
Anchors at Standard Positions Punts d’ancoratge en posicions estàndard
Third Point by Dragging Tercer punt arrossegant
Circle (open) Cercle (obert)
Classic Clàssic
Classic Defaults Valors predeterminats clàssics
Can't render this file because it contains an unexpected character in line 2 and column 73.
+4
View File
@@ -4631,6 +4631,10 @@ font-technology Variable Variabilní
Circle Kruh
Circle Tool Nástroj Kruh
Circle too large Kruh je příliš velký
Show Radii Zobrazit poloměry
Show Diameter Zobrazit průměr
Anchors at Standard Positions Kotevní body ve standardních polohách
Third Point by Dragging Třetí bod tažením
Clip to Art Oříznout podle kresby
Colorize Obarvit
Gamma Gama
Can't render this file because it is too large.
+4
View File
@@ -7030,6 +7030,10 @@ font-technology Variable Variable
Circle Cirkel
Circle Tool Cirkelværktøj
Circle too large Cirklen er for stor
Show Radii Vis radier
Show Diameter Vis diameter
Anchors at Standard Positions Ankerpunkter i standardpositioner
Third Point by Dragging Tredje punkt ved træk
Clip to Art Beskær til grafik
Colorize Farvelæg
Gamma Gamma
Can't render this file because it is too large.
+5
View File
@@ -458,6 +458,11 @@ font-technology Variable Variabel
Circle Kreis
Circle Tool Kreis-Werkzeug
Circle too large Kreis zu groß
Show Radii Radien anzeigen
Show Diameter Durchmesser anzeigen
Anchors at Standard Positions Ankerpunkte an Standardpositionen
Third Point by Dragging Dritter Punkt durch Ziehen
Gray Grau
Classic Defaults Klassische Standardwerte
Clean Up… Aufräumen…
Clear Löschen
Can't render this file because it is too large.
+4
View File
@@ -451,6 +451,10 @@ font-technology Variable Μεταβλητές
Circle Κύκλος
Circle Tool Εργαλείο κύκλου
Circle too large Ο κύκλος είναι πολύ μεγάλος
Show Radii Εμφάνιση ακτίνων
Show Diameter Εμφάνιση διαμέτρου
Anchors at Standard Positions Σημεία αγκύρωσης σε τυπικές θέσεις
Third Point by Dragging Τρίτο σημείο με σύρσιμο
Classic Defaults Κλασικές προεπιλογές
Clean Up… Εκκαθάριση…
Clear Εκκαθάριση
Can't render this file because it is too large.
+4
View File
@@ -481,6 +481,10 @@ font-technology Variable Variables
Circle Círculo
Circle Tool Herramienta Círculo
Circle too large Círculo demasiado grande
Show Radii Mostrar radios
Show Diameter Mostrar diámetro
Anchors at Standard Positions Puntos de ancla en posiciones estándar
Third Point by Dragging Tercer punto arrastrando
Classic Defaults Valores predeterminados clásicos
Clean Up… Limpiar…
Clear Borrar
Can't render this file because it contains an unexpected character in line 2 and column 73.
+4
View File
@@ -4550,6 +4550,10 @@ font-technology Variable Muuttuvat
Circle Ympyrä
Circle Tool Ympyrätyökalu
Circle too large Ympyrä on liian suuri
Show Radii Näytä säteet
Show Diameter Näytä halkaisija
Anchors at Standard Positions Ankkuripisteet vakiokohdissa
Third Point by Dragging Kolmas piste vetämällä
Clip to Art Rajaa kuvitukseen
Colorize Väritä
Gamma Gamma
Can't render this file because it contains an unexpected character in line 2 and column 73.
+4
View File
@@ -482,6 +482,10 @@ font-technology Variable Variables
Circle Cercle
Circle Tool Outil Cercle
Circle too large Cercle trop grand
Show Radii Afficher les rayons
Show Diameter Afficher le diamètre
Anchors at Standard Positions Points d’ancrage aux positions standard
Third Point by Dragging Troisième point par glissement
Classic Defaults Valeurs par défaut classiques
Clean Up… Nettoyer…
Clear Effacer
Can't render this file because it is too large.
+5
View File
@@ -564,6 +564,11 @@
Circle વર્તુળ
Circle Tool વર્તુળ ટૂલ
Circle too large વર્તુળ ખૂબ મોટું છે
Show Radii ત્રિજ્યાઓ બતાવો
Show Diameter વ્યાસ બતાવો
Anchors at Standard Positions પ્રમાણભૂત સ્થાનો પર એન્કર બિંદુઓ
Third Point by Dragging ખેંચીને ત્રીજું બિંદુ
Gray રાખોડી
Circle: વર્તુળ:
Classic ક્લાસિક
Clean Up સાફ કરો
Can't render this file because it contains an unexpected character in line 72 and column 5.
+4
View File
@@ -822,6 +822,10 @@ antiAlias Sharp शार्प
Circle वृत्त
Circle Tool वृत्त टूल
Circle too large वृत्त बहुत बड़ा है
Show Radii त्रिज्याएँ दिखाएँ
Show Diameter व्यास दिखाएँ
Anchors at Standard Positions मानक स्थानों पर एंकर पॉइंट्स
Third Point by Dragging खींचकर तीसरा बिंदु
Circle (open) सर्किल (ओपन)
Circle: वृत्त:
Classic क्लासिक
Can't render this file because it is too large.
+4
View File
@@ -643,6 +643,10 @@ font-technology Variable Változó
Circle Kör
Circle Tool Kör eszköz
Circle too large A kör túl nagy
Show Radii Sugarak megjelenítése
Show Diameter Átmérő megjelenítése
Anchors at Standard Positions Horgonypontok szabványos helyeken
Third Point by Dragging Harmadik pont húzással
Circle (open) Kör (nyitott)
Classic Defaults Klasszikus alapértékek
Clean Up… Tisztítás…
Can't render this file because it is too large.
+4
View File
@@ -4282,6 +4282,10 @@ font-technology Variable Variabel
Circle Lingkaran
Circle Tool Alat lingkaran
Circle too large Lingkaran terlalu besar
Show Radii Tampilkan jari-jari
Show Diameter Tampilkan diameter
Anchors at Standard Positions Titik jangkar di posisi standar
Third Point by Dragging Titik ketiga dengan menyeret
Clip to Art Pangkas ke karya seni
Colorize Warnai
Gamma Gamma
Can't render this file because it contains an unexpected character in line 2511 and column 5.
+5
View File
@@ -483,6 +483,11 @@ font-technology Variable Variabili
Circle Cerchio
Circle Tool Strumento Cerchio
Circle too large Cerchio troppo grande
Show Radii Mostra raggi
Show Diameter Mostra diametro
Anchors at Standard Positions Punti di ancoraggio in posizioni standard
Third Point by Dragging Terzo punto trascinando
Gray Grigio
Classic Defaults Valori predefiniti classici
Clean Up… Pulisci…
Clear Cancella
Can't render this file because it is too large.
+5
View File
@@ -1299,6 +1299,11 @@ antiAlias Sharp シャープ
Circle 円
Circle Tool 円ツール
Circle too large 円が大きすぎます
Show Radii 半径を表示
Show Diameter 直径を表示
Anchors at Standard Positions アンカーポイントを標準位置に配置
Third Point by Dragging 3 点目をドラッグで指定
Gray グレー
Clear All Tabs すべてのタブを消去
Above Text テキストの上
Position Panel Above Text テキストの上にパネルを配置
Can't render this file because it is too large.
+4
View File
@@ -6348,6 +6348,10 @@ font-technology Variable ცვლადი
Circle წრე
Circle Tool წრის ხელსაწყო
Circle too large წრე ზედმეტად დიდია
Show Radii რადიუსების ჩვენება
Show Diameter დიამეტრის ჩვენება
Anchors at Standard Positions საყრდენი წერტილები სტანდარტულ პოზიციებზე
Third Point by Dragging მესამე წერტილი გადათრევით
Clip to Art ნახატზე მოჭრა
Colorize გაფერადება
Gamma გამა
Can't render this file because it is too large.
+5
View File
@@ -1289,6 +1289,11 @@ antiAlias Sharp 날카롭게
Circle 원
Circle Tool 점 기준 원 도구
Circle too large 원이 너무 큽니다
Show Radii 반지름 표시
Show Diameter 지름 표시
Anchors at Standard Positions 표준 위치에 앵커 포인트
Third Point by Dragging 드래그로 세 번째 점 지정
Gray 회색
Clear All Tabs 모든 탭 지우기
Above Text 문자 위
Position Panel Above Text 패널을 문자 위에 배치
Can't render this file because it is too large.
+4
View File
@@ -4904,6 +4904,10 @@ font-technology Variable Variabel
Circle Cirkel
Circle Tool Cirkelgereedschap
Circle too large Cirkel te groot
Show Radii Stralen tonen
Show Diameter Diameter tonen
Anchors at Standard Positions Ankerpunten op standaardposities
Third Point by Dragging Derde punt door slepen
Clip to Art Clippen op artwork
Colorize Inkleuren
Gamma Gamma
Can't render this file because it is too large.
+5
View File
@@ -4472,6 +4472,11 @@ font-technology Variable Zmienne
Circle Okrąg
Circle Tool Narzędzie Okrąg
Circle too large Okrąg jest za duży
Show Radii Pokaż promienie
Show Diameter Pokaż średnicę
Anchors at Standard Positions Punkty kontrolne w standardowych położeniach
Third Point by Dragging Trzeci punkt przez przeciągnięcie
Gray Szary
Clip to Art Przytnij do kompozycji
Colorize Koloruj
Gamma Gamma
Can't render this file because it is too large.
+4
View File
@@ -448,6 +448,10 @@ antiAlias Sharp Nítido
Circle Círculo
Circle Tool Ferramenta Círculo
Circle too large Círculo grande demais
Show Radii Mostrar Raios
Show Diameter Mostrar Diâmetro
Anchors at Standard Positions Pontos de Ancoragem em Posições Padrão
Third Point by Dragging Terceiro Ponto Arrastando
Clean Up… Limpar…
Clear Limpar
Clear All Tabs Limpar Todas as Paradas de Tabulação
Can't render this file because it is too large.
+4
View File
@@ -479,6 +479,10 @@ font-technology Variable Вариативные
Circle Круг
Circle Tool Инструмент «Круг»
Circle too large Круг слишком большой
Show Radii Показать радиусы
Show Diameter Показать диаметр
Anchors at Standard Positions Опорные точки в стандартных позициях
Third Point by Dragging Третья точка перетаскиванием
Classic Defaults Классические значения по умолчанию
Clean Up… Очистить…
Clear Очистить
Can't render this file because it is too large.
+4
View File
@@ -469,6 +469,10 @@ font-technology Variable Variabla
Circle Cirkel
Circle Tool Cirkelverktyg
Circle too large Cirkeln är för stor
Show Radii Visa radier
Show Diameter Visa diameter
Anchors at Standard Positions Ankarpunkter på standardpositioner
Third Point by Dragging Tredje punkt genom att dra
Classic Defaults Klassiska standardvärden
Clean Up… Rensa upp…
Clear Rensa
Can't render this file because it is too large.
+4
View File
@@ -463,6 +463,10 @@ font-technology Variable Değişken
Circle daire
Circle Tool Daire Aracı
Circle too large Daire çok büyük
Show Radii Yarıçapları Göster
Show Diameter Çapı Göster
Anchors at Standard Positions Standart Konumlarda Bağlantı Noktaları
Third Point by Dragging Sürükleyerek Üçüncü Nokta
Classic Defaults Klasik Varsayılanlar
Clean Up… Temizleme…
Clear Temizle
Can't render this file because it is too large.
+5
View File
@@ -477,6 +477,11 @@ font-technology Variable Варіативні
Circle Коло
Circle Tool Інструмент «Коло»
Circle too large Коло завелике
Show Radii Показати радіуси
Show Diameter Показати діаметр
Anchors at Standard Positions Опорні точки в стандартних позиціях
Third Point by Dragging Третя точка перетягуванням
Gray Сірий
Classic Defaults Класичні значення за промовчанням
Clean Up… Очистити…
Clear Очистити
Can't render this file because it is too large.
+5
View File
@@ -559,6 +559,11 @@ font-technology Variable Biến thiên
Circle Hình tròn
Circle Tool Công cụ Hình tròn
Circle too large Hình tròn quá lớn
Show Radii Hiện bán kính
Show Diameter Hiện đường kính
Anchors at Standard Positions Điểm neo ở vị trí chuẩn
Third Point by Dragging Điểm thứ ba bằng cách kéo
Gray Xám
Classic Cổ điển
Classic Defaults Mặc định cổ điển
Clean Up… Dọn dẹp…
Can't render this file because it contains an unexpected character in line 205 and column 5.
+4
View File
@@ -430,6 +430,10 @@ antiAlias Sharp 锐利
Circle 圆形
Circle Tool 圆形工具
Circle too large 圆形过大
Show Radii 显示半径
Show Diameter 显示直径
Anchors at Standard Positions 锚点位于标准位置
Third Point by Dragging 拖动放置第三点
Classic Defaults 经典默认
Clean Up… 清理…
Clear 清除
Can't render this file because it is too large.
+5
View File
@@ -445,6 +445,11 @@ font-technology Variable 可變
Circle 圓形
Circle Tool 圓形工具
Circle too large 圓形過大
Show Radii 顯示半徑
Show Diameter 顯示直徑
Anchors at Standard Positions 錨點位於標準位置
Third Point by Dragging 拖曳放置第三點
Gray 灰
Classic Defaults 經典預設值
Clean Up… 清除…
Clear 清除
Can't render this file because it is too large.
File diff suppressed because one or more lines are too long
+4 -1
View File
@@ -423,7 +423,7 @@ pub(crate) fn flyout_press(ui: &Ui, resp: &egui::Response, rect: egui::Rect) ->
/// Reflect and Shear tools' are their Object › Transform dialogs, the selection tools' are the
/// Move dialog, and the Pencil, Paintbrush, Smooth, Blob Brush, Eraser, Shape Builder and Objects
/// on Path tools' are their Tool Options, as are the Line Segment, Arc, Rectangular Grid and Polar Grid tools'
/// ([`crate::dialogs::shapes::open_options`]). The Type on a Path and Vertical Type on a Path
/// ([`crate::dialogs::shapes::open_options`]) and the Circle tool's ([`crate::dialogs::circle_options::open`]). The Type on a Path and Vertical Type on a Path
/// tools' are Type on a Path Options for the selected type on a path.
pub fn open_options(app: &mut VectorcraftApp, tool: &str) -> Result<serde_json::Value, String> {
match tool {
@@ -460,6 +460,9 @@ pub fn open_options(app: &mut VectorcraftApp, tool: &str) -> Result<serde_json::
// The Line Segment, Arc and grid tools: their Tool Options, the options of their next
// drag and click.
_ if crate::dialogs::shapes::OPTION_TOOLS.contains(&tool) => crate::dialogs::shapes::open_options(app, tool),
// The Circle tool: what it shows while a circle is drawn, where its anchors go and how
// the third point is placed.
vectorcraft_tools::circle::ID => Ok(crate::dialogs::circle_options::open(app)),
// The Flare tool: its options, which draw the next flare (OK draws none).
"flare" => Ok(crate::dialogs::flare_options::open(app, None)),
// A double click on the Print Tiling tool puts the pages back where the placement puts them.
+28
View File
@@ -6189,6 +6189,12 @@ 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.
`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
is drawn.
The Circle tool, after the Ellipse tool in its toolbar group, draws with this command. A drag from one point to
another, or a click on each, draws the circle with the two points as the ends of a diameter. A click on a first point,
then a press on a second point dragged to a third, draws the circle through the three. Shift keeps the second point at
@@ -6203,6 +6209,28 @@ Escape, a dropped press, and an edit, Undo or Redo made outside the tool drop th
screen points of the first point, or one that snaps to it, is a press on it: let go there (a double-click), it places no second point, and
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"`:
- `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.
- `color` (Color) is the color of the cross and the lines: `"red"`, `"blue"`, `"magenta"`, `"green"`, `"black"` or
`"gray"`. The outline stays blue.
- `standardAnchors` (Anchors at Standard Positions) off draws the circle with `anchors: "points"`, so its anchors are
at the points it was drawn through.
- `dragThird` (Third Point by Dragging) off changes how the points are placed. A click on a second point places it, and
a click on a third point draws the circle through the three. A click on the second point again, as the second click
of a double-click there is, draws the circle on the two points. An Alt-click places the second point where Alt's
rounding of the diameter puts it, and both circles pass through it there. A click on the first point, or a second
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.
`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
not one of these (`` unknown Circle tool option `size` ``).
With the Ellipse tool, the first two Shift-clicks place points, and the third draws the circle through the three with
this command. After two points the tool previews the circle through them and the pointer as a dashed outline. Once a
point is placed, a Shift-click on the selection's handles, center point or shape widgets places a point too. Escape, a