brep_render/engine_state/sketch_input.rs
1use super::*;
2use super::sketch_panel::{sketch_constraint_signature, sketch_perpendicular_should_swap};
3
4// Sketch picking maps camera rays to plane-space coordinates. Hit tests prefer
5// points over geometry within the grab radius. Mutators refresh the live overlay
6// and mark the engine dirty; calls outside sketch mode are no-ops.
7impl EngineState {
8 /// Re-push the sketch overlay reflecting the live hover + selection. Reads the
9 /// active `sketch_edit`'s session; a no-op when not in sketch mode. Called at
10 /// the end of every S2 mutator (the reusable counterpart of the initial
11 /// [`set_sketch_overlay`](Self::set_sketch_overlay) push).
12 pub(super) fn refresh_sketch_overlay(&mut self) {
13 let world_per_pixel = self.camera.world_per_pixel();
14 let (json, preview, leaders, glyphs) = match self.sketch_edit.as_ref() {
15 Some(edit) => (
16 edit.session.overlay_json_with_state(world_per_pixel),
17 edit.session.preview_overlay_json(
18 world_per_pixel,
19 &edit.pending,
20 edit.hover_uv,
21 &edit.handdraw_stroke,
22 ),
23 edit.session.dim_leaders_overlay_json_with_state(world_per_pixel),
24 edit.session
25 .constraint_glyphs_overlay_json_with_state(world_per_pixel),
26 ),
27 None => return,
28 };
29 let _ = self.set_overlay_json(&json);
30 // The draw-tool rubber-band rides in its own `sketch-preview` group so it
31 // upserts/clears independently of the solved geometry + point groups.
32 let _ = self.set_overlay_json(&preview);
33 // The dimension leaders + arrows ride in `sketch-dim-leaders`, refreshed
34 // alongside everything else (S5).
35 let _ = self.set_overlay_json(&leaders);
36 // The geometric-constraint glyphs ride in `sketch-constraint-glyphs` (S6c).
37 let _ = self.set_overlay_json(&glyphs);
38 // Remember the zoom these groups were baked at: their construction dashes,
39 // dimension arrowheads and constraint glyphs are all screen-constant, so
40 // `ensure_sketch_overlay_current` re-bakes them when it moves.
41 self.sketch_overlay_wpp = if world_per_pixel > 0.0 {
42 world_per_pixel
43 } else {
44 f64::MIN_POSITIVE
45 };
46 }
47
48 /// Per-frame upkeep for the live SKETCH overlay (driven by
49 /// [`Self::ensure_overlays_current`]) — the sketch-mode sibling of
50 /// [`Self::ensure_feature_dimension_overlay_current`]. The dimension leaders
51 /// (draggable), constraint glyphs and construction dashes are sized in PIXELS
52 /// against the camera at bake time, so a zoom leaves them stale until
53 /// something else mutates the sketch. Re-bakes on a material
54 /// `world_per_pixel` change only, so a quiet frame stays quiet.
55 pub(super) fn ensure_sketch_overlay_current(&mut self) {
56 if !self.sketch_mode() {
57 self.sketch_overlay_wpp = 0.0;
58 return;
59 }
60 let wpp = self.camera.world_per_pixel();
61 if super::overlay_wpp_stale(self.sketch_overlay_wpp, wpp) {
62 self.refresh_sketch_overlay();
63 }
64 }
65
66 /// Map CSS-pixel `(x, y)` to the active sketch plane's `(u, v)` via the camera
67 /// pick ray ∩ the sketch plane. `None` when not in sketch mode or the ray misses
68 /// the plane (parallel / behind).
69 pub fn sketch_uv_at(&self, x: f64, y: f64) -> Option<(f64, f64)> {
70 let edit = self.sketch_edit.as_ref()?;
71 let ray = self.camera.pick_ray(x, y);
72 crate::sketch::ray_plane_uv(&edit.session.plane, ray.origin, ray.dir)
73 }
74
75 /// The world-space pick tolerance at the current zoom — the ONE radius that
76 /// drives hover-highlight, click-select, drag-grab, draw-snap AND trim, for
77 /// points AND geometry, so "what highlights" is exactly "what you can grab".
78 /// Sized at 1.5× the visualized point (`POINT_SIZE_PX`) for forgiving clicking.
79 pub(super) fn sketch_pick_radius(&self) -> f64 {
80 f64::from(crate::sketch::tessellate::POINT_SIZE_PX) * 1.5 * self.camera.world_per_pixel()
81 }
82
83 /// The entity ref under CSS-pixel `(x, y)` within the grab radius, or `None`.
84 /// Priority is points > geometry > constraint: [`pick_entity`] resolves the first
85 /// two, and only when neither is in range do we consult [`pick_constraint`] (a glyph
86 /// or dimension leader that overlaps a point/edge never shadows it).
87 ///
88 /// [`pick_entity`]: crate::sketch::SketchSession::pick_entity
89 /// [`pick_constraint`]: crate::sketch::SketchSession::pick_constraint
90 fn sketch_entity_at(&self, x: f64, y: f64) -> Option<serde_json::Value> {
91 let (u, v) = self.sketch_uv_at(x, y)?;
92 let radius = self.sketch_pick_radius();
93 let wpp = self.camera.world_per_pixel();
94 self.sketch_edit.as_ref().and_then(|edit| {
95 edit.session
96 .pick_entity(u, v, radius)
97 .or_else(|| edit.session.pick_constraint(u, v, radius, wpp))
98 })
99 }
100
101 /// Set (or clear) the sketch hover, re-pushing the overlay + marking dirty only
102 /// when it actually changed. Returns whether the hover changed.
103 pub(super) fn set_sketch_hover(&mut self, new_hover: Option<serde_json::Value>) -> bool {
104 let changed = match self.sketch_edit.as_ref() {
105 Some(edit) => {
106 !crate::sketch::entity_ref_eq(edit.session.hovered.as_ref(), new_hover.as_ref())
107 }
108 None => false,
109 };
110 if changed {
111 if let Some(edit) = self.sketch_edit.as_mut() {
112 edit.session.set_hover(new_hover);
113 }
114 self.refresh_sketch_overlay();
115 self.dirty = true;
116 }
117 changed
118 }
119
120 /// Update the sketch hover to the entity under CSS-pixel `(x, y)` (S2). Returns
121 /// whether the hover changed. A no-op returning `false` when not in sketch mode.
122 pub fn sketch_hover_at(&mut self, x: f64, y: f64) -> bool {
123 if self.sketch_edit.is_none() {
124 return false;
125 }
126 // Track the live cursor uv for the S3a rubber-band. In DRAW mode with pending
127 // clicks the preview follows the cursor even when the hovered ENTITY is
128 // unchanged, so force an overlay refresh there.
129 let uv = self.sketch_uv_at(x, y);
130 let preview_live = match self.sketch_edit.as_mut() {
131 Some(edit) => {
132 edit.hover_uv = uv;
133 edit.session.tool.is_some() && !edit.pending.is_empty()
134 }
135 None => false,
136 };
137 let new_hover = self.sketch_entity_at(x, y);
138 let changed = self.set_sketch_hover(new_hover);
139 if preview_live && !changed {
140 self.refresh_sketch_overlay();
141 self.dirty = true;
142 }
143 changed
144 }
145
146 /// Clear the sketch hover (pointer left the viewport / moved over the ViewCube).
147 /// Returns whether a hover was cleared.
148 pub fn sketch_clear_hover(&mut self) -> bool {
149 self.set_sketch_hover(None)
150 }
151
152 /// Click-select in sketch mode: pick the entity under `(x, y)`; nothing → clear
153 /// the selection. Otherwise honor the SAME "Multi-select" setting the 3D viewport
154 /// reads (`settings.multi_select`): under `ClickToggles` a plain click toggles the
155 /// hit in the set (no modifier needed for a multi-selection); under
156 /// `CtrlClick` a plain click replaces the set with just the hit and `additive`
157 /// (Ctrl/Cmd) toggles. Re-pushes the overlay + marks dirty.
158 pub fn sketch_click_at(&mut self, x: f64, y: f64, additive: bool) {
159 // Read the setting before the mutable `sketch_edit` borrow.
160 let toggles = self.settings.multi_select == crate::style::MultiSelectMode::ClickToggles;
161 let hit = self.sketch_entity_at(x, y);
162 let Some(edit) = self.sketch_edit.as_mut() else {
163 return;
164 };
165 match hit {
166 None => edit.session.clear_selection(),
167 Some(entity_ref) => {
168 if additive || toggles {
169 edit.session.toggle_selection(entity_ref);
170 } else {
171 edit.session.clear_selection();
172 edit.session.toggle_selection(entity_ref);
173 }
174 }
175 }
176 self.refresh_sketch_overlay();
177 self.dirty = true;
178 }
179
180 /// Begin a point drag if a DRAGGABLE point is under `(x, y)` (S2): remember it
181 /// (id + original `fixed` flag). Returns `true` iff a point was grabbed (the
182 /// viewport routes the drag to the sketch; otherwise it orbits the camera). A
183 /// locked / fully-constrained point is not draggable, so an empty-space or
184 /// locked-point drag falls through to a camera orbit.
185 pub fn sketch_drag_begin(&mut self, x: f64, y: f64) -> bool {
186 let Some((u, v)) = self.sketch_uv_at(x, y) else {
187 return false;
188 };
189 let radius = self.sketch_pick_radius();
190 // Grab EXACTLY what's HIGHLIGHTED: the hovered entity was picked at the exact
191 // cursor position on the last move, so it is immune to egui reporting the
192 // drag-start ~6px into the gesture (the "highlighted but won't grab"
193 // intermittency — and it's what lets a whole geometry drag). A hovered LOCKED
194 // point yields `None` → the drag falls through to a camera gesture; it must
195 // NOT positional-fall-back there (that would grab a nearby UNhighlighted
196 // point). Only an EMPTY hover (a press with no prior move) falls back to a
197 // fresh positional pick.
198 let points = self.sketch_edit.as_ref().and_then(|edit| {
199 match edit.session.hovered.as_ref() {
200 Some(entity_ref) => edit.session.drag_points_from_ref(entity_ref),
201 None => edit
202 .session
203 .pick_draggable_point(u, v, radius)
204 .and_then(|(id, fixed)| {
205 edit.session
206 .doc
207 .point(&id)
208 .map(|p| vec![(id, p.x, p.y, fixed)])
209 }),
210 }
211 });
212 let Some(points) = points else {
213 return false;
214 };
215 if let Some(edit) = self.sketch_edit.as_mut() {
216 // Snapshot ONCE at the gesture start so the whole drag is one undo step
217 // (S6a); `sketch_drag_to` never snapshots. A grab that moves nothing is
218 // discarded in `sketch_drag_end`.
219 edit.record_undo();
220 edit.drag = Some(SketchDrag { points, anchor: (u, v) });
221 }
222 true
223 }
224
225 /// Drag the grabbed target to `(x, y)` (S2): pin every grabbed point at its
226 /// ORIGINAL position plus the cursor delta (`fixed = true`) so the solver anchors
227 /// the whole shape there, re-solve, then restore each point's ORIGINAL `fixed`
228 /// flag. Absolute-from-anchor (never incremental), so a rigid geometry translate
229 /// tracks the cursor 1:1 without drifting as the solver nudges points between
230 /// frames. A resolve error rolls every grabbed point back to its pre-drag coords
231 /// (the last good state). No-op when nothing is grabbed / not in sketch mode / the
232 /// ray misses the plane.
233 pub fn sketch_drag_to(&mut self, x: f64, y: f64) {
234 let Some((u, v)) = self.sketch_uv_at(x, y) else {
235 return;
236 };
237 let Some(edit) = self.sketch_edit.as_mut() else {
238 return;
239 };
240 let Some(drag) = edit.drag.clone() else {
241 return;
242 };
243 let (du, dv) = (u - drag.anchor.0, v - drag.anchor.1);
244 let session = &mut edit.session;
245 let before = session.doc.clone();
246 for (id, ox, oy, _) in &drag.points {
247 if let Some(p) = session.doc.point_mut(id) {
248 p.x = *ox + du;
249 p.y = *oy + dv;
250 p.fixed = true;
251 }
252 }
253 match session.resolve() {
254 Ok(()) => {
255 for (id, _, _, orig_fixed) in &drag.points {
256 if let Some(p) = session.doc.point_mut(id) {
257 p.fixed = *orig_fixed;
258 }
259 }
260 }
261 Err(_) => {
262 // Unsolvable target: roll every grabbed point back to its pre-drag
263 // coords + flag (keep the last good state).
264 for (id, ox, oy, orig_fixed) in &drag.points {
265 if let Some(p) = session.doc.point_mut(id) {
266 p.x = *ox;
267 p.y = *oy;
268 p.fixed = *orig_fixed;
269 }
270 }
271 }
272 }
273 // A drag can collapse a free radius without producing a solver error.
274 // Preserve the last valid geometry, while tolerating pre-existing broken
275 // circles in imported documents so they can still be edited/repaired.
276 if newly_collapsed_radial_geometry(&before, &session.doc) {
277 session.doc = before;
278 let _ = session.resolve();
279 }
280 self.refresh_sketch_overlay();
281 self.dirty = true;
282 }
283
284 /// End a point drag (S2): clear the grab, then one final re-solve + overlay
285 /// refresh. No-op when no drag is live.
286 pub fn sketch_drag_end(&mut self) {
287 let had_grab = self
288 .sketch_edit
289 .as_ref()
290 .map_or(false, |edit| edit.drag.is_some());
291 if !had_grab {
292 return;
293 }
294 // Drop radius for constraint inference == the point grab radius (12 px in
295 // world units) — read before the `&mut` borrow of `sketch_edit`.
296 let drop_tol = self.sketch_pick_radius();
297 if let Some(edit) = self.sketch_edit.as_mut() {
298 let before = edit.session.doc.clone();
299 // Drop-time inference (S6c): a SINGLE-point drop snaps to a coincident
300 // point / point-on-line at the release position, mirroring the previous
301 // coincident-on-drop / point-on-line-on-drop inference. A whole-
302 // geometry drag (multiple points) never infers — running it per
303 // endpoint could glue or collapse the curve in one solve.
304 let dragged_single = edit.drag.as_ref().and_then(|drag| {
305 (drag.points.len() == 1).then(|| drag.points[0].0.clone())
306 });
307 edit.drag = None;
308 if let Some(point_id) = dragged_single {
309 crate::sketch::infer::infer_drop_constraint(
310 &mut edit.session.doc,
311 &point_id,
312 drop_tol,
313 );
314 }
315 let _ = edit.session.resolve();
316 if newly_collapsed_radial_geometry(&before, &edit.session.doc) {
317 edit.session.doc = before;
318 let _ = edit.session.resolve();
319 }
320 // Discard the drag's undo snapshot when the doc is unchanged (a mere
321 // grab-and-release, no move and no inferred constraint), so it neither
322 // pollutes undo nor clobbers redo. An inferred constraint changes the
323 // doc, so the snapshot is kept — one Ctrl+Z then undoes move+constraint.
324 if edit
325 .undo_stack
326 .last()
327 .map_or(false, |snap| snap.doc == edit.session.doc)
328 {
329 edit.undo_stack.pop();
330 }
331 }
332 self.refresh_sketch_overlay();
333 self.dirty = true;
334 }
335
336 /// The number of selected sketch entities (0 when not in sketch mode) — the mode
337 /// bar / verifier readout.
338 pub fn sketch_selection_count(&self) -> usize {
339 self.sketch_edit
340 .as_ref()
341 .map_or(0, |edit| edit.session.selection.len())
342 }
343
344 /// The number of selected CONSTRAINTS (refs whose `kind` is `"constraint"`; 0 when
345 /// not in sketch mode) — the `__brepSketch` verifier readout for constraint
346 /// selection + delete.
347 pub fn sketch_selected_constraint_count(&self) -> usize {
348 self.sketch_edit.as_ref().map_or(0, |edit| {
349 edit.session
350 .selection
351 .iter()
352 .filter(|r| r.get("kind").and_then(|v| v.as_str()) == Some("constraint"))
353 .count()
354 })
355 }
356}
357
358fn radial_distance(doc: &crate::sketch::SketchDoc, points: &[serde_json::Value]) -> f64 {
359 match (doc.point(&points[0]), doc.point(&points[1])) {
360 (Some(a), Some(b)) => (b.x - a.x).hypot(b.y - a.y),
361 _ => 0.0,
362 }
363}
364
365fn newly_collapsed_radial_geometry(
366 before: &crate::sketch::SketchDoc,
367 after: &crate::sketch::SketchDoc,
368) -> bool {
369 before.geometries.iter().any(|g| {
370 matches!(g.geom_type.as_str(), "circle" | "arc")
371 && g.points.len() >= 2
372 && radial_distance(before, &g.points) > 1e-5
373 && radial_distance(after, &g.points) <= 1e-5
374 })
375}
376
377// ===========================================================================
378// Sketch draw tools (S3a) — primitive placement: point / line / rect / circle / arc.
379//
380// A click-state machine over the active `self.sketch_edit`. The active tool lives
381// on `session.tool` ("select"/None = selection mode, S2); a DRAW tool routes clicks
382// to `sketch_tool_click_at` (pixel → plane uv via the same S2 `sketch_uv_at`, then
383// `sketch_tool_place_uv`). Points/geometries are minted through `SketchDoc`
384// (`next_point_id`/`next_geometry_id` + `snap_or_add_point`, so shared vertices
385// coincide). Each placement re-solves (swallowing solve errors), re-pushes the
386// overlay (incl. the rubber-band preview), and marks dirty. The bezier tool has a
387// second mode on the same click: idle, a click ON an existing spline REFINES it
388// rather than starting a new one (`crate::sketch::spline`). Kept in ONE appended
389// block so concurrent edits to the primary impl land clean.
390// ===========================================================================
391impl EngineState {
392 /// Set (or clear) the active draw tool: `"select"`/`None` → selection mode (S2);
393 /// `"point"|"line"|"rect"|"circle"|"arc"|"bezier"` arm the corresponding draw
394 /// tool; `"handdraw"` arms the freehand stroke tool (S6b-3); `"trim"` arms the
395 /// trim tool (S6b); `"pickEdges"` arms the external-edge link tool (S6b-2). Clears
396 /// any in-progress click buffer + preview and refreshes the overlay. No-op when not
397 /// in sketch mode.
398 pub fn sketch_set_tool(&mut self, tool: Option<&str>) {
399 let normalized = normalize_sketch_tool(tool);
400 if let Some(edit) = self.sketch_edit.as_mut() {
401 edit.session.tool = normalized;
402 edit.pending.clear();
403 edit.hover_uv = None;
404 edit.handdraw_stroke.clear();
405 } else {
406 return;
407 }
408 // A context edge lit for pickEdges is only that tool's to show.
409 if self.sketch_active_tool() != Some("pickEdges") {
410 self.hover_context(None);
411 }
412 self.refresh_sketch_overlay();
413 self.dirty = true;
414 }
415
416 /// The active draw tool (`"point"|"line"|"rect"|"circle"|"arc"`), or `None` in
417 /// selection mode / when not in sketch mode.
418 pub fn sketch_active_tool(&self) -> Option<&str> {
419 self.sketch_edit
420 .as_ref()
421 .and_then(|edit| edit.session.tool.as_deref())
422 }
423
424 /// The number of in-progress draw-tool clicks buffered (0 in selection mode /
425 /// when not in sketch mode) — the UI/preview + verifier readout.
426 pub fn sketch_pending_len(&self) -> usize {
427 self.sketch_edit.as_ref().map_or(0, |edit| edit.pending.len())
428 }
429
430 /// A draw-tool click at CSS-pixel `(x, y)`: map to plane uv (the S2 pixel→plane
431 /// math) and drive the tool state machine. No-op when not in sketch mode, in
432 /// selection mode, or the ray misses the plane.
433 pub fn sketch_tool_click_at(&mut self, x: f64, y: f64) {
434 // pickEdges (S6b-2) acts on the 3D SCENE EDGE under the cursor — it needs the
435 // PIXEL coords (a scene pick), not a plane uv, so short-circuit before the
436 // pixel→plane projection (which would drop clicks that miss the plane).
437 if self.sketch_active_tool() == Some("pickEdges") {
438 self.sketch_pick_edge_at(x, y);
439 return;
440 }
441 let Some((u, v)) = self.sketch_uv_at(x, y) else {
442 return;
443 };
444 self.sketch_tool_place_uv(u, v);
445 }
446
447 /// The per-tool placement logic, in plane `(u, v)` (the headless-testable core
448 /// `sketch_tool_click_at` delegates to). Snaps to existing points within the grab
449 /// radius so shared vertices coincide; appends geometry and re-solves when a
450 /// primitive completes; carries the line chain via `pending`.
451 pub fn sketch_tool_place_uv(&mut self, u: f64, v: f64) {
452 let radius = self.sketch_pick_radius();
453 // Selection mode (no tool / "select") never places. Read the tool without
454 // holding a borrow so the trim branch can call back into `self`.
455 let tool = match self.sketch_edit.as_ref() {
456 Some(edit) => match edit.session.tool.clone() {
457 Some(tool) => tool,
458 None => return,
459 },
460 None => return,
461 };
462 // Trim (S6b) is a click tool that acts IMMEDIATELY on the geometry under the
463 // cursor — it never buffers `pending` or places a point. It owns its own undo
464 // snapshot (and pops it on a no-op), so short-circuit before the draw path.
465 if tool == "trim" {
466 self.sketch_trim_uv(u, v);
467 return;
468 }
469 // pickEdges is NOT a uv-placement tool — it acts on a 3D scene edge (routed via
470 // pixel coords in `sketch_tool_click_at`), so a stray uv place is a no-op here.
471 if tool == "pickEdges" {
472 return;
473 }
474 // handdraw (S6b-3) captures a DRAG as a stroke (routed via `sketch_handdraw_*`),
475 // not a click-placed point — a plain click is a no-op (and never records a dead
476 // undo step here, since we return before `record_undo`).
477 if tool == "handdraw" {
478 return;
479 }
480 let Some(edit) = self.sketch_edit.as_mut() else {
481 return;
482 };
483 // Check the SNAP RESULT, not just the cursor: a nearby radius click can
484 // reuse the center id. Keep waiting for a valid radius/end without adding
485 // points or an undo step. Arc endpoints must also be off the center.
486 if matches!(tool.as_str(), "circle" | "arc") && !edit.pending.is_empty() {
487 let doc = &edit.session.doc;
488 let Some(center) = doc.point(&edit.pending[0]) else { return; };
489 let snapped = doc.points.iter()
490 .filter(|p| (p.x - u).hypot(p.y - v) <= radius)
491 .min_by(|a, b| (a.x - u).hypot(a.y - v).total_cmp(&(b.x - u).hypot(b.y - v)));
492 let (x, y) = snapped.map_or((u, v), |p| (p.x, p.y));
493 let distance = (x - center.x).hypot(y - center.y);
494 if !distance.is_finite() || distance <= 1e-5 {
495 return;
496 }
497 }
498 // A draw tool is active → this click WILL mutate the doc (a point and/or a
499 // geometry); snapshot for undo before it does (S6a).
500 edit.record_undo();
501 let doc = &mut edit.session.doc;
502 match tool.as_str() {
503 "point" => {
504 doc.snap_or_add_point(u, v, radius);
505 edit.pending.clear();
506 }
507 "line" => {
508 if edit.pending.is_empty() {
509 let a = doc.snap_or_add_point(u, v, radius);
510 edit.pending.push(a);
511 } else {
512 let start = edit.pending.last().cloned().expect("pending non-empty");
513 let end = doc.snap_or_add_point(u, v, radius);
514 push_sketch_geometry(doc, "line", vec![start, end.clone()]);
515 // Continue the chain: the just-placed end is the next start.
516 edit.pending = vec![end];
517 }
518 }
519 "rect" => {
520 if edit.pending.is_empty() {
521 let a = doc.snap_or_add_point(u, v, radius);
522 edit.pending.push(a);
523 } else {
524 let a_id = edit.pending[0].clone();
525 let Some((ax, ay)) = doc.point(&a_id).map(|p| (p.x, p.y)) else {
526 edit.pending.clear();
527 return;
528 };
529 let (bx, by) = (u, v);
530 // Corners A=(ax,ay), (bx,ay), (bx,by), (ax,by) → 4 closed lines.
531 let b1 = doc.snap_or_add_point(bx, ay, radius);
532 let b2 = doc.snap_or_add_point(bx, by, radius);
533 let b3 = doc.snap_or_add_point(ax, by, radius);
534 push_sketch_geometry(doc, "line", vec![a_id.clone(), b1.clone()]);
535 push_sketch_geometry(doc, "line", vec![b1.clone(), b2.clone()]);
536 push_sketch_geometry(doc, "line", vec![b2.clone(), b3.clone()]);
537 push_sketch_geometry(doc, "line", vec![b3.clone(), a_id.clone()]);
538 // Keep the rectangle rectangular under drag: three ⟂ constraints on
539 // the adjacent-edge pairs (the 4th corner's right angle follows from
540 // the closed loop). This is the minimal rigid set — it removes 3 DOF
541 // from the 8-DOF four-corner quad, leaving position (2) + rotation (1)
542 // + width + height = 5 DOF, so the sketch is neither over-constrained
543 // nor conflicting.
544 push_rect_perpendicular_constraints(doc, [a_id, b1, b2, b3]);
545 edit.pending.clear();
546 }
547 }
548 "circle" => {
549 if edit.pending.is_empty() {
550 let c = doc.snap_or_add_point(u, v, radius);
551 edit.pending.push(c);
552 } else {
553 let center = edit.pending[0].clone();
554 let r = doc.snap_or_add_point(u, v, radius);
555 push_sketch_geometry(doc, "circle", vec![center, r]);
556 edit.pending.clear();
557 }
558 }
559 "arc" => {
560 // Clicks: center, start, then end completes [center, start, end].
561 if edit.pending.len() < 2 {
562 let p = doc.snap_or_add_point(u, v, radius);
563 edit.pending.push(p);
564 } else {
565 let center = edit.pending[0].clone();
566 let start = edit.pending[1].clone();
567 let end = doc.snap_or_add_point(u, v, radius);
568 push_sketch_geometry(doc, "arc", vec![center, start, end]);
569 edit.pending.clear();
570 }
571 }
572 "bezier" => {
573 // Cubic Bezier: 4 clicks place end0, ctrl0, ctrl1, end1 (in order).
574 // The 4th click commits the span [p0, p1, p2, p3] PLUS two dashed
575 // construction guide lines for the control handles (end0→ctrl0 and
576 // end1→ctrl1), matching the previous basic bezier tool. One INVOCATION
577 // authors one span; a chained multi-span polygon (3n+1 ids in ONE
578 // geometry — the model the solver, tessellator and profile builder all
579 // already read) is grown by insertion instead, below.
580 //
581 // IDLE + a click on an existing spline = refine it: subdivide the
582 // clicked span so a new anchor lands under the cursor without the curve
583 // moving (see `crate::sketch::spline`). Only while `pending` is empty —
584 // mid-draw the click still means "place the next control point", so a
585 // new spline can be drawn across an old one. A refusal (nothing under
586 // the cursor, a point winning the pick, a degenerate span) falls
587 // through to that placement, which mutates the doc too, so the
588 // `record_undo` above never leaves a dead step either way.
589 let refined = edit.pending.is_empty() && spline_insert_anchor(doc, u, v, radius);
590 if !refined {
591 if edit.pending.len() < 3 {
592 let p = doc.snap_or_add_point(u, v, radius);
593 edit.pending.push(p);
594 } else {
595 let p0 = edit.pending[0].clone();
596 let p1 = edit.pending[1].clone();
597 let p2 = edit.pending[2].clone();
598 let p3 = doc.snap_or_add_point(u, v, radius);
599 push_sketch_geometry(
600 doc,
601 "bezier",
602 vec![p0.clone(), p1.clone(), p2.clone(), p3.clone()],
603 );
604 // Construction guide lines (dashed, non-modeling) for the two
605 // control handles — separate freshly minted geometry ids.
606 push_sketch_construction_line(doc, vec![p0, p1]);
607 push_sketch_construction_line(doc, vec![p3, p2]);
608 edit.pending.clear();
609 }
610 }
611 }
612 _ => return,
613 }
614 // Every draw click mutates the doc (a new point and/or geometry); re-solve so
615 // coordinates + mobility stay fresh, keeping the doc if the solve fails.
616 self.resolve_active_sketch("draw-tool");
617 self.refresh_sketch_overlay();
618 self.dirty = true;
619 }
620
621 /// Abort the in-progress draw geometry (Escape / right-click): clear the pending
622 /// clicks + preview and refresh. No-op when not in sketch mode.
623 pub fn sketch_tool_cancel(&mut self) {
624 if let Some(edit) = self.sketch_edit.as_mut() {
625 edit.pending.clear();
626 } else {
627 return;
628 }
629 self.refresh_sketch_overlay();
630 self.dirty = true;
631 }
632}
633
634/// Normalize a tool name to the stored form: `None`/`"select"`/`""` → selection mode
635/// (`None`), else the tool string (`"point"|"line"|"rect"|"circle"|"arc"|"bezier"|
636/// "trim"|"pickEdges"|"handdraw"`).
637fn normalize_sketch_tool(tool: Option<&str>) -> Option<String> {
638 match tool {
639 None | Some("select") | Some("") => None,
640 Some(t) => Some(t.to_string()),
641 }
642}
643
644/// Append a geometry to a sketch doc with a freshly minted id (the caller passes the
645/// solver `type` — `rect` corners are pushed as `line`s), carrying an explicit
646/// `construction: false` so it matches the authored shape and round-trips.
647fn push_sketch_geometry(
648 doc: &mut crate::sketch::SketchDoc,
649 geom_type: &str,
650 points: Vec<serde_json::Value>,
651) {
652 let id = doc.next_geometry_id();
653 let mut extra = serde_json::Map::new();
654 extra.insert("construction".to_string(), serde_json::Value::Bool(false));
655 doc.geometries.push(crate::sketch::SketchGeometry {
656 id,
657 geom_type: geom_type.to_string(),
658 points,
659 extra,
660 });
661}
662
663/// Append a CONSTRUCTION `line` geometry (dashed, non-modeling — `construction: true`)
664/// with a freshly minted id: the bezier tool's control-handle guide lines. Mirrors
665/// [`push_sketch_geometry`] but flips the construction flag so the line renders dashed
666/// and is excluded from profiles while still being constrainable.
667fn push_sketch_construction_line(
668 doc: &mut crate::sketch::SketchDoc,
669 points: Vec<serde_json::Value>,
670) {
671 let id = doc.next_geometry_id();
672 let mut extra = serde_json::Map::new();
673 extra.insert("construction".to_string(), serde_json::Value::Bool(true));
674 doc.geometries.push(crate::sketch::SketchGeometry {
675 id,
676 geom_type: "line".to_string(),
677 points,
678 extra,
679 });
680}
681
682/// Subdivide the spline under the plane click `(u, v)` — the bezier tool's "refine
683/// what I already drew" click. Delegates the pick + de Casteljau split to
684/// [`crate::sketch::spline::insert_anchor`] (which decides whether the click is a
685/// subdivision at all) and, when it lands, hangs the SAME two dashed construction
686/// guides on the new anchor that the 4-click path hangs on the two drawn ends:
687/// anchor→handle on each side. Consistency is the whole point — after a refine every
688/// anchor of the spline, drawn or inserted, has a guide to each of its neighbouring
689/// handles, so the handles stay visible and constrainable (a tangent on a guide is
690/// how a spline is made to meet a line smoothly) and a refined curve is
691/// indistinguishable from one drawn that way. The two ORIGINAL guides still read
692/// correctly without being touched, because the split reuses the end handles' ids and
693/// they remain the handles adjacent to those same two end anchors.
694///
695/// Returns whether the click was consumed as an insertion; `false` means the caller
696/// should treat it as an ordinary control-point placement.
697fn spline_insert_anchor(doc: &mut crate::sketch::SketchDoc, u: f64, v: f64, radius: f64) -> bool {
698 let Some(added) = crate::sketch::spline::insert_anchor(doc, u, v, radius) else {
699 return false;
700 };
701 push_sketch_construction_line(doc, vec![added.anchor.clone(), added.before]);
702 push_sketch_construction_line(doc, vec![added.anchor, added.after]);
703 true
704}
705
706/// Append the three perpendicular (`⟂`) constraints that keep a freshly drawn
707/// rectangle rectangular when a corner is dragged. `corners` are the rect's four
708/// points in loop order `[a, b1, b2, b3]` (edges a→b1, b1→b2, b2→b3, b3→a); the
709/// constraints go on the adjacent-edge pairs sharing corners b1 / b2 / b3. The fourth
710/// corner (a) is left implied — a closed quad with three right angles is a rectangle —
711/// so this is the MINIMAL rigid set (3 equations, no over-constraint / redundancy).
712///
713/// Each `⟂` stores the two edges' endpoint pairs `[l1a, l1b, l2a, l2b]`, swap-oriented
714/// exactly like a palette-added perpendicular ([`sketch_build_and_add_constraint`]), and
715/// is deduped on its signature. No-op unless the four corners are all distinct (a
716/// degenerate rect whose corners snapped together would otherwise carry a `⟂` on a
717/// zero-length edge, which is meaningless and can wedge the solver).
718fn push_rect_perpendicular_constraints(
719 doc: &mut crate::sketch::SketchDoc,
720 corners: [serde_json::Value; 4],
721) {
722 use crate::sketch::doc::id_key;
723 let [a, b1, b2, b3] = corners;
724 let keys = [id_key(&a), id_key(&b1), id_key(&b2), id_key(&b3)];
725 for i in 0..keys.len() {
726 for j in (i + 1)..keys.len() {
727 if keys[i] == keys[j] {
728 return; // two corners collapsed → skip (no zero-length-edge ⟂).
729 }
730 }
731 }
732 // Adjacent edge pairs sharing corner b1 / b2 / b3.
733 let pairs = [
734 [a.clone(), b1.clone(), b1.clone(), b2.clone()],
735 [b1.clone(), b2.clone(), b2.clone(), b3.clone()],
736 [b2.clone(), b3.clone(), b3.clone(), a.clone()],
737 ];
738 for pair in pairs {
739 let mut pts = pair.to_vec();
740 if sketch_perpendicular_should_swap(doc, &pts) {
741 pts.swap(0, 1);
742 }
743 push_geometric_constraint(doc, "⟂", pts);
744 }
745}
746
747/// Append a NON-dimensional geometric constraint (`type` + ordered `points`) with a
748/// freshly minted id and the same base fields a palette-added constraint carries
749/// (`labelX`/`labelY` = 0, `displayStyle` = "", `value` = null, `valueNeedsSetup` =
750/// true — see [`sketch_build_and_add_constraint`]). Deduped on `type + sorted-points`
751/// (the solver runs with `remove_implied_duplicates: false`, so this is the only
752/// dedup); a no-op on a duplicate.
753fn push_geometric_constraint(
754 doc: &mut crate::sketch::SketchDoc,
755 ctype: &str,
756 points: Vec<serde_json::Value>,
757) {
758 let sig = sketch_constraint_signature(ctype, &points);
759 let duplicate = doc.constraints.iter().any(|c| match c.ctype() {
760 Some(t) => sketch_constraint_signature(t, c.points()) == sig,
761 None => false,
762 });
763 if duplicate {
764 return;
765 }
766 let id = doc.next_constraint_id();
767 let mut raw = serde_json::Map::new();
768 raw.insert("id".to_string(), id);
769 raw.insert("type".to_string(), serde_json::Value::String(ctype.to_string()));
770 raw.insert("points".to_string(), serde_json::Value::Array(points));
771 raw.insert("labelX".to_string(), serde_json::Value::from(0));
772 raw.insert("labelY".to_string(), serde_json::Value::from(0));
773 raw.insert(
774 "displayStyle".to_string(),
775 serde_json::Value::String(String::new()),
776 );
777 raw.insert("value".to_string(), serde_json::Value::Null);
778 raw.insert("valueNeedsSetup".to_string(), serde_json::Value::Bool(true));
779 doc.constraints.push(crate::sketch::SketchConstraint { raw });
780}
781
782// ===========================================================================
783// Auto-constrain — infer the constraints implied by the rough-in geometry.
784//
785// A one-click "constrain what I drew": snap nearly-axis-aligned lines to `━`/`│` and
786// near-coincident points to `≡`, going through the same `push_geometric_constraint`
787// dedup the palette uses so the solver picks them up and a re-run is idempotent.
788// ===========================================================================
789
790/// Auto-constrain tolerances (v1 constants; a future pass could surface them as
791/// settings). A line whose direction is within [`AUTO_HV_ANGLE_TOL_DEG`] of an axis
792/// gets a horizontal/vertical constraint — loose enough to catch a rough-in, far
793/// below the slope a user clearly intended.
794const AUTO_HV_ANGLE_TOL_DEG: f64 = 3.0;
795/// Two points auto-snap to COINCIDENT when within this fraction of the sketch's
796/// bounding-box diagonal (scale-invariant, so it works at any sketch size)…
797const AUTO_COINCIDENT_FRAC: f64 = 0.01;
798/// …floored at this absolute distance for a tiny or single-cluster sketch.
799const AUTO_COINCIDENT_ABS: f64 = 1e-4;
800
801/// Infer + add the constraints implied by the current geometry: `━`/`│` on
802/// nearly-axis-aligned lines and `≡` between near-coincident points. Conservative —
803/// never adds an unsatisfiable constraint on two already-fixed points, never collapses
804/// a curve by coinciding its own endpoints, never re-adds a coincident already implied
805/// (directly or transitively), and dedups H/V via [`push_geometric_constraint`]. So a
806/// second pass adds nothing (idempotent). Returns the number of constraints added; the
807/// caller re-solves.
808pub(super) fn auto_constrain_doc(doc: &mut crate::sketch::SketchDoc) -> usize {
809 use crate::sketch::doc::id_key;
810 use serde_json::Value;
811 use std::collections::{HashMap, HashSet};
812
813 let before = doc.constraints.len();
814
815 // ---- Horizontal / vertical on nearly-axis-aligned lines. ----
816 // Threshold on |unit component off the axis| = |sin(angle deviation)|.
817 let hv_sin_tol = AUTO_HV_ANGLE_TOL_DEG.to_radians().sin();
818 let mut hv: Vec<(&str, Vec<Value>)> = Vec::new();
819 for g in &doc.geometries {
820 if g.geom_type != "line" || g.points.len() < 2 {
821 continue;
822 }
823 let (Some(a), Some(b)) = (doc.point(&g.points[0]), doc.point(&g.points[1])) else {
824 continue;
825 };
826 // Skip a line pinned at BOTH ends (no freedom → an H/V that isn't already
827 // exactly true is unsatisfiable). This also excludes linked reference lines,
828 // whose endpoints are all fixed.
829 if a.fixed && b.fixed {
830 continue;
831 }
832 let (dx, dy) = (b.x - a.x, b.y - a.y);
833 let len = dx.hypot(dy);
834 if len < 1e-9 {
835 continue;
836 }
837 // Skip a line that already carries an H or V constraint on these endpoints
838 // (never add the opposite one; keeps the pass idempotent).
839 let mut keys: Vec<String> = g.points[..2].iter().map(id_key).collect();
840 keys.sort();
841 let already_hv = doc.constraints.iter().any(|c| {
842 if !matches!(c.ctype(), Some("━") | Some("│")) {
843 return false;
844 }
845 let mut k: Vec<String> = c.points().iter().map(id_key).collect();
846 k.sort();
847 k == keys
848 });
849 if already_hv {
850 continue;
851 }
852 let (ux, uy) = (dx / len, dy / len);
853 if uy.abs() <= hv_sin_tol {
854 hv.push(("━", vec![g.points[0].clone(), g.points[1].clone()]));
855 } else if ux.abs() <= hv_sin_tol {
856 hv.push(("│", vec![g.points[0].clone(), g.points[1].clone()]));
857 }
858 }
859 for (ct, pts) in hv {
860 push_geometric_constraint(doc, ct, pts);
861 }
862
863 // ---- Coincident between near-coincident, mergeable point pairs. ----
864 let n = doc.points.len();
865 if n >= 2 {
866 fn find(parent: &mut [usize], mut x: usize) -> usize {
867 while parent[x] != x {
868 parent[x] = parent[parent[x]]; // path halving
869 x = parent[x];
870 }
871 x
872 }
873 fn union(parent: &mut [usize], a: usize, b: usize) {
874 let (ra, rb) = (find(parent, a), find(parent, b));
875 if ra != rb {
876 parent[ra] = rb;
877 }
878 }
879
880 // Union-find over point indices, SEEDED with the existing coincidents so we
881 // never re-add one (directly or transitively).
882 let index: HashMap<String, usize> = doc
883 .points
884 .iter()
885 .enumerate()
886 .map(|(i, p)| (id_key(&p.id), i))
887 .collect();
888 let mut parent: Vec<usize> = (0..n).collect();
889 for c in &doc.constraints {
890 if c.ctype() == Some("≡") {
891 let pts = c.points();
892 if let (Some(p0), Some(p1)) = (pts.first(), pts.get(1)) {
893 if let (Some(&i), Some(&j)) = (index.get(&id_key(p0)), index.get(&id_key(p1))) {
894 union(&mut parent, i, j);
895 }
896 }
897 }
898 }
899
900 // Distance tolerance relative to the sketch extent — the user's points only:
901 // the part-origin reference may sit far from the drawing and must not widen it.
902 let (mut lo, mut hi) = ([f64::INFINITY; 2], [f64::NEG_INFINITY; 2]);
903 for p in doc.points.iter().filter(|p| !brep_kernel::is_sketch_origin_point_id(&p.id)) {
904 lo[0] = lo[0].min(p.x);
905 lo[1] = lo[1].min(p.y);
906 hi[0] = hi[0].max(p.x);
907 hi[1] = hi[1].max(p.y);
908 }
909 let extent = ((hi[0] - lo[0]).powi(2) + (hi[1] - lo[1]).powi(2)).sqrt();
910 let tol = (extent * AUTO_COINCIDENT_FRAC).max(AUTO_COINCIDENT_ABS);
911
912 // Point-key set per geometry — skip a pair that are the two ends of the SAME
913 // curve (coinciding them would collapse it).
914 let geo_sets: Vec<HashSet<String>> = doc
915 .geometries
916 .iter()
917 .map(|g| g.points.iter().map(id_key).collect())
918 .collect();
919
920 let mut coincidents: Vec<Vec<Value>> = Vec::new();
921 for i in 0..n {
922 for j in (i + 1)..n {
923 let (pi, pj) = (&doc.points[i], &doc.points[j]);
924 if pi.fixed && pj.fixed {
925 continue; // both pinned → a coincident is unsatisfiable
926 }
927 let d = ((pi.x - pj.x).powi(2) + (pi.y - pj.y).powi(2)).sqrt();
928 if d > tol {
929 continue;
930 }
931 if find(&mut parent, i) == find(&mut parent, j) {
932 continue; // already coincident (directly or transitively)
933 }
934 let (ki, kj) = (id_key(&pi.id), id_key(&pj.id));
935 if geo_sets.iter().any(|s| s.contains(&ki) && s.contains(&kj)) {
936 continue; // endpoints of one curve — do not collapse it
937 }
938 union(&mut parent, i, j);
939 coincidents.push(vec![pi.id.clone(), pj.id.clone()]);
940 }
941 }
942 for pts in coincidents {
943 push_geometric_constraint(doc, "≡", pts);
944 }
945 }
946
947 doc.constraints.len().saturating_sub(before)
948}
949
950impl EngineState {
951 /// Auto-constrain the active sketch (the toolbar's one-click "constrain what I
952 /// roughed in"): infer `━`/`│` on nearly-axis-aligned lines and `≡` between
953 /// near-coincident points, then re-solve. Records ONE undo step, popped when the
954 /// pass adds nothing so a dead click neither pollutes undo nor clobbers redo.
955 /// Returns the number of constraints added; a no-op (0) when not in sketch mode.
956 pub fn sketch_auto_constrain(&mut self) -> usize {
957 let Some(edit) = self.sketch_edit.as_mut() else {
958 return 0;
959 };
960 edit.record_undo();
961 let added = auto_constrain_doc(&mut edit.session.doc);
962 if added == 0 {
963 edit.undo_stack.pop();
964 return 0;
965 }
966 self.resolve_active_sketch("auto-constrain");
967 self.refresh_sketch_overlay();
968 self.dirty = true;
969 added
970 }
971}
972
973// ===========================================================================
974// Sketch delete-selected (S3b) — remove the selected entities + orphan cleanup.
975//
976// Operates on the active `self.sketch_edit`. Rule (chosen so a remaining geometry
977// NEVER references a missing point):
978// 1. Partition the selection into selected geometry / point / constraint ids.
979// 2. Drop every geometry that is SELECTED *or* references any selected point (the
980// remove-point cascade — deleting a vertex kills geometry that used it).
981// 3. Drop the selected points.
982// 4. Orphan cleanup: drop any remaining point NOT referenced by any surviving
983// geometry (a shared vertex — still referenced — stays; a deleted line's now
984// unshared endpoints vanish). Always on for this slice.
985// 5. Drop any constraint that is SELECTED *or* references a removed point (selected ∪
986// orphaned) — done LAST, over the full removed-point set, so no constraint dangles
987// either. A selected constraint drops ONLY itself; the geometry/points it
988// referenced are untouched (deleting a constraint never deletes geometry).
989// Then clear selection + hover, re-solve (swallowing errors), refresh, mark dirty.
990// Kept in ONE appended block so concurrent edits to the primary impl land clean.
991// ===========================================================================
992impl EngineState {
993 /// Delete the selected sketch entities (S3b): the selected geometries + points,
994 /// plus any geometry orphaned by a deleted vertex, plus orphaned points and the
995 /// constraints referencing any removed point. Re-solves + refreshes the overlay.
996 /// Returns `true` when something was deleted; `false` when not in sketch mode or
997 /// the selection is empty.
998 pub fn sketch_delete_selection(&mut self) -> bool {
999 use crate::sketch::doc::id_key;
1000 use std::collections::HashSet;
1001
1002 let Some(edit) = self.sketch_edit.as_mut() else {
1003 return false;
1004 };
1005 if edit.session.selection.is_empty() {
1006 return false;
1007 }
1008 // A non-empty selection always removes something → snapshot for undo (S6a).
1009 edit.record_undo();
1010
1011 // 1. Partition the selection into selected geometry / point / constraint ids
1012 // (keyed via `id_key`, so 4 / 4.0 / "4" all match).
1013 let mut sel_geo: HashSet<String> = HashSet::new();
1014 let mut sel_pt: HashSet<String> = HashSet::new();
1015 let mut sel_constraint: HashSet<String> = HashSet::new();
1016 for r in &edit.session.selection {
1017 match (r.get("kind").and_then(|v| v.as_str()), r.get("id")) {
1018 (Some("geometry"), Some(id)) => {
1019 sel_geo.insert(id_key(id));
1020 }
1021 (Some("point"), Some(id)) => {
1022 sel_pt.insert(id_key(id));
1023 }
1024 (Some("constraint"), Some(id)) => {
1025 sel_constraint.insert(id_key(id));
1026 }
1027 _ => {}
1028 }
1029 }
1030
1031 // The part-origin reference and its ground are permanent: never deleted,
1032 // selected or orphaned.
1033 let origin_key = id_key(&serde_json::Value::String(
1034 brep_kernel::SKETCH_ORIGIN_POINT_ID.to_string(),
1035 ));
1036 sel_pt.remove(&origin_key);
1037 sel_constraint.remove(&origin_key);
1038
1039 let doc = &mut edit.session.doc;
1040
1041 // 2. Drop geometries that are selected OR reference any selected point (so a
1042 // deleted vertex never leaves a geometry dangling).
1043 doc.geometries.retain(|g| {
1044 if sel_geo.contains(&id_key(&g.id)) {
1045 return false;
1046 }
1047 !g.points.iter().any(|pid| sel_pt.contains(&id_key(pid)))
1048 });
1049
1050 // 3. Drop the explicitly-selected points.
1051 doc.points.retain(|p| !sel_pt.contains(&id_key(&p.id)));
1052
1053 // 4. Orphan cleanup: drop points no longer referenced by any surviving
1054 // geometry. Accumulate every removed point id (selected ∪ orphaned).
1055 let referenced: HashSet<String> = doc
1056 .geometries
1057 .iter()
1058 .flat_map(|g| g.points.iter().map(id_key))
1059 .collect();
1060 let mut removed_pts = sel_pt;
1061 doc.points.retain(|p| {
1062 let key = id_key(&p.id);
1063 if referenced.contains(&key) || key == origin_key {
1064 true
1065 } else {
1066 removed_pts.insert(key);
1067 false
1068 }
1069 });
1070
1071 // 5. Drop constraints that are EXPLICITLY selected OR reference ANY removed
1072 // point (done last, over the full removed set, so no constraint dangles onto
1073 // a missing point). A selected constraint drops ONLY itself — the geometry /
1074 // points it references are left intact (deleting a constraint never deletes
1075 // geometry).
1076 doc.constraints.retain(|c| {
1077 if let Some(id) = c.raw.get("id") {
1078 if sel_constraint.contains(&id_key(id)) {
1079 return false;
1080 }
1081 }
1082 !c.points().iter().any(|pid| removed_pts.contains(&id_key(pid)))
1083 });
1084
1085 // Drop any external-reference bookkeeping whose materialized entities this
1086 // delete removed — otherwise its stale entry (keyed by edge name, now holding
1087 // dangling point ids) permanently blocks RE-LINKING the same edge.
1088 crate::sketch::external_ref::prune_dead_refs(&edit.session.doc, &mut edit.external_refs);
1089
1090 // Clear the interaction state, re-solve (keep the doc on failure), refresh.
1091 edit.session.clear_selection();
1092 edit.session.set_hover(None);
1093 self.resolve_active_sketch("delete");
1094 self.refresh_sketch_overlay();
1095 self.dirty = true;
1096 true
1097 }
1098}