Skip to main content

brep_render/engine_state/
sketch_panel.rs

1use super::*;
2
3/// One row in a sketch entity-LIST panel (Points / Curves / Constraints) — the
4/// display label plus the `(kind, id)` needed to select / hover / delete it, and
5/// its current selected/construction state for row styling. Built by
6/// [`EngineState::sketch_point_rows`] / `sketch_geometry_rows` /
7/// `sketch_constraint_rows`; the panel renders them and routes clicks back through
8/// [`EngineState::sketch_select_entity`] / `sketch_hover_entity`.
9#[derive(Clone, Debug, PartialEq)]
10pub struct SketchEntityRow {
11    /// Entity ref kind: `"point"` | `"geometry"` | `"constraint"`.
12    pub kind: &'static str,
13    /// The entity id (opaque `Value`, passed straight back to select/hover).
14    pub id: serde_json::Value,
15    /// Human display label (mirrors the previous list rows).
16    pub label: String,
17    /// Whether this entity is in the current sketch selection (row highlight).
18    pub selected: bool,
19    /// Construction-only entity (dashed / de-emphasized styling).
20    pub construction: bool,
21    /// The solver names this entity in a CONSTRAINT CONFLICT (constraint rows
22    /// only) — the panel paints the row red to match its canvas annotation.
23    pub conflicting: bool,
24}
25
26/// How a notice is drawn: an [`Error`](Self::Error) (a refusal, a failure —
27/// what [`EngineState::push_notice`] queues), a [`Warning`](Self::Warning)
28/// (it worked, and something needs a look) or [`Info`](Self::Info) (it worked:
29/// "Updated 2 part(s)", "Saved 'widget'").
30#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
31pub enum NoticeSeverity {
32    #[default]
33    Error,
34    Warning,
35    Info,
36}
37
38impl EngineState {
39    /// Queue a notice of `severity`. [`Self::push_notice`] is this with
40    /// [`NoticeSeverity::Error`]; bounded the same way.
41    pub fn push_notice_as(&mut self, severity: NoticeSeverity, message: impl Into<String>) {
42        if severity == NoticeSeverity::Error {
43            return self.push_notice(message);
44        }
45        let message = message.into();
46        #[cfg(not(target_arch = "wasm32"))]
47        eprintln!("{message}");
48        self.graded_notices.push((severity, message));
49        if self.graded_notices.len() > 8 {
50            let overflow = self.graded_notices.len() - 8;
51            self.graded_notices.drain(0..overflow);
52        }
53    }
54
55    /// Drain every queued notice with its severity: the errors, then the
56    /// warnings and successes. The shell's toast overlay reads this.
57    pub fn take_graded_notices(&mut self) -> Vec<(NoticeSeverity, String)> {
58        let errors = std::mem::take(&mut self.notices).into_iter().map(|text| (NoticeSeverity::Error, text));
59        errors.chain(std::mem::take(&mut self.graded_notices)).collect()
60    }
61
62    /// Queue a transient user-facing notice (shown as a toast by the shell) and,
63    /// on native, also log it. Bounded so a pathological loop can't grow it.
64    pub fn push_notice(&mut self, message: impl Into<String>) {
65        let message = message.into();
66        #[cfg(not(target_arch = "wasm32"))]
67        eprintln!("{message}");
68        self.notices.push(message);
69        if self.notices.len() > 8 {
70            let overflow = self.notices.len() - 8;
71            self.notices.drain(0..overflow);
72        }
73    }
74
75    /// Drain the queued notices (the shell calls this once per frame and shows
76    /// each as a toast).
77    pub fn take_notices(&mut self) -> Vec<String> {
78        self.take_graded_notices().into_iter().map(|(_, text)| text).collect()
79    }
80
81    /// Re-solve the ACTIVE sketch session and, on failure, queue a user notice
82    /// naming `context`. Replaces the scattered swallowed `eprintln!` on the
83    /// interactive re-solve paths — the solver rarely fails, but when an edit
84    /// leaves the sketch unsolvable the user should see why.
85    pub(super) fn resolve_active_sketch(&mut self, context: &str) {
86        let error = self
87            .sketch_edit
88            .as_mut()
89            .and_then(|edit| edit.session.resolve().err());
90        if let Some(error) = error {
91            self.push_notice(format!("Sketch solve failed ({context}): {error}"));
92        }
93    }
94
95    /// Whether `(kind, id)` is in the current sketch selection.
96    fn sketch_ref_selected(session: &crate::sketch::SketchSession, kind: &str, id: &serde_json::Value) -> bool {
97        use crate::sketch::doc::id_key;
98        let key = id_key(id);
99        session.selection.items.iter().any(|r| {
100            r.get("kind").and_then(serde_json::Value::as_str) == Some(kind)
101                && r.get("id").map(id_key).as_deref() == Some(key.as_str())
102        })
103    }
104
105    /// The Points list: `P{id} (x, y)` plus ⛓ external / ◐ construction / ⏚ ground
106    /// markers, mirroring the previous Points rows.
107    pub fn sketch_point_rows(&self) -> Vec<SketchEntityRow> {
108        use crate::sketch::doc::id_key;
109        let Some(edit) = self.sketch_edit.as_ref() else {
110            return Vec::new();
111        };
112        let session = &edit.session;
113        session
114            .doc
115            .points
116            .iter()
117            .map(|p| {
118                let grounded = session.doc.constraints.iter().any(|c| {
119                    c.ctype() == Some("⏚")
120                        && c.points().first().map(id_key).as_deref() == Some(id_key(&p.id).as_str())
121                });
122                let mut marks = String::new();
123                if p.external_reference {
124                    marks.push_str(" \u{26D3}"); // ⛓ chain-links (bundled font; 🔗 is not)
125                }
126                if p.construction {
127                    marks.push_str(" ◐");
128                }
129                if grounded {
130                    marks.push_str(" ⏚");
131                }
132                SketchEntityRow {
133                    kind: "point",
134                    id: p.id.clone(),
135                    label: if crate::sketch::external_ref::is_origin_id(&p.id) {
136                        format!("Origin ({:.1}, {:.1}){marks}", p.x, p.y)
137                    } else {
138                        format!("P{} ({:.1}, {:.1}){marks}", id_key(&p.id), p.x, p.y)
139                    },
140                    selected: Self::sketch_ref_selected(session, "point", &p.id),
141                    construction: p.construction,
142                    conflicting: false,
143                }
144            })
145            .collect()
146    }
147
148    /// The Curves list: `{type}:{id} [p0,p1,…]` (◐ for construction), mirroring the
149    /// previous Curves rows.
150    pub fn sketch_geometry_rows(&self) -> Vec<SketchEntityRow> {
151        use crate::sketch::doc::id_key;
152        let Some(edit) = self.sketch_edit.as_ref() else {
153            return Vec::new();
154        };
155        let session = &edit.session;
156        session
157            .doc
158            .geometries
159            .iter()
160            .map(|g| {
161                let pts = g
162                    .points
163                    .iter()
164                    .map(id_key)
165                    .collect::<Vec<_>>()
166                    .join(",");
167                let construction = g.construction();
168                let mark = if construction { " ◐" } else { "" };
169                // A copy of another part's edge says so ("copied from …, not linked").
170                let note = g.extra.get("note").and_then(serde_json::Value::as_str).map(|n| format!(" \u{2014} {n}")).unwrap_or_default();
171                SketchEntityRow {
172                    kind: "geometry",
173                    id: g.id.clone(),
174                    label: if g.geom_type == "text" {
175                        format!("Text: {}", g.extra.get("text").and_then(|v|v.as_str()).unwrap_or(""))
176                    } else { format!("{}:{}{mark} [{pts}]{note}", g.geom_type, id_key(&g.id)) },
177                    selected: Self::sketch_ref_selected(session, "geometry", &g.id),
178                    construction,
179                    conflicting: false,
180                }
181            })
182            .collect()
183    }
184
185    /// The Constraints list: `{id} {type} {value} [points]`, mirroring the previous
186    /// Constraints rows.
187    pub fn sketch_constraint_rows(&self) -> Vec<SketchEntityRow> {
188        use crate::sketch::doc::id_key;
189        let Some(edit) = self.sketch_edit.as_ref() else {
190            return Vec::new();
191        };
192        let session = &edit.session;
193        session
194            .doc
195            .constraints
196            .iter()
197            .filter_map(|c| {
198                let id = c.raw.get("id")?.clone();
199                let ctype = c.ctype().unwrap_or("?");
200                let value = c
201                    .raw
202                    .get("value")
203                    .and_then(serde_json::Value::as_f64)
204                    .map(|v| format!(" {v:.3}"))
205                    .unwrap_or_default();
206                let pts = c
207                    .points()
208                    .iter()
209                    .map(id_key)
210                    .collect::<Vec<_>>()
211                    .join(",");
212                Some(SketchEntityRow {
213                    kind: "constraint",
214                    id: id.clone(),
215                    label: format!("{} {ctype}{value} [{pts}]", id_key(&id)),
216                    selected: Self::sketch_ref_selected(session, "constraint", &id),
217                    construction: false,
218                    conflicting: session.diagnostics.constraint_conflicting(&id),
219                })
220            })
221            .collect()
222    }
223
224    /// The Issues list: the constraints the solver names as conflicting (first),
225    /// then the redundant ones (consistent repeats of earlier constraints), as
226    /// Constraints rows whose label notes which (`… — conflicting` /
227    /// `… — redundant`). Empty when the sketch has neither.
228    pub fn sketch_issue_rows(&self) -> Vec<SketchEntityRow> {
229        let Some(edit) = self.sketch_edit.as_ref() else {
230            return Vec::new();
231        };
232        let diag = &edit.session.diagnostics;
233        let rows = self.sketch_constraint_rows();
234        let mut out: Vec<SketchEntityRow> = Vec::new();
235        for (note, pick) in [("conflicting", true), ("redundant", false)] {
236            for row in &rows {
237                let hit = if pick {
238                    diag.constraint_conflicting(&row.id)
239                } else {
240                    diag.constraint_redundant(&row.id) && !diag.constraint_conflicting(&row.id)
241                };
242                if hit {
243                    let mut r = row.clone();
244                    r.label = format!("{} \u{2014} {note}", row.label);
245                    out.push(r);
246                }
247            }
248        }
249        out
250    }
251
252    /// Select an entity BY ref from a list row (mirrors [`sketch_click_at`](Self::sketch_click_at)): honors the
253    /// SAME "Multi-select" setting — under `ClickToggles` a plain click toggles the row
254    /// (no modifier needed); under `CtrlClick` a plain click replaces the
255    /// selection and an additive (Ctrl/Cmd) click toggles.
256    pub fn sketch_select_entity(&mut self, kind: &str, id: serde_json::Value, additive: bool) {
257        let toggles = self.settings.multi_select == crate::style::MultiSelectMode::ClickToggles;
258        let entity_ref = serde_json::json!({ "kind": kind, "id": id });
259        let Some(edit) = self.sketch_edit.as_mut() else {
260            return;
261        };
262        if !additive && !toggles {
263            edit.session.clear_selection();
264        }
265        edit.session.toggle_selection(entity_ref);
266        self.refresh_sketch_overlay();
267        self.dirty = true;
268    }
269
270    /// Delete exactly ONE entity BY ref — a list row's ✕ (owner bug 2026-11-04). The
271    /// row ✕ used to select the row and run [`sketch_delete_selection`](Self::sketch_delete_selection),
272    /// but under the `ClickToggles` multi-select setting a plain select does not
273    /// replace the selection, so the ✕ deleted everything selected (or, on an
274    /// already-selected row, toggled it OFF and deleted the rest). This deletes
275    /// only the clicked entity (with the usual dependent cleanup) and keeps the
276    /// rest of the selection where its entities survive. Returns whether
277    /// something was deleted.
278    pub fn sketch_delete_entity(&mut self, kind: &str, id: serde_json::Value) -> bool {
279        use crate::sketch::doc::id_key;
280        let target = serde_json::json!({ "kind": kind, "id": id });
281        let same = |r: &serde_json::Value| {
282            r.get("kind") == target.get("kind")
283                && r.get("id").map(id_key) == target.get("id").map(id_key)
284        };
285        let Some(edit) = self.sketch_edit.as_mut() else {
286            return false;
287        };
288        let kept: Vec<serde_json::Value> =
289            edit.session.selection.items.iter().filter(|r| !same(r)).cloned().collect();
290        edit.session.clear_selection();
291        edit.session.toggle_selection(target);
292        let deleted = self.sketch_delete_selection();
293        if let Some(edit) = self.sketch_edit.as_mut() {
294            let doc = &edit.session.doc;
295            let alive = |r: &serde_json::Value| {
296                let Some(id) = r.get("id") else { return false };
297                match r.get("kind").and_then(|k| k.as_str()) {
298                    Some("geometry") => doc.geometry(id).is_some(),
299                    Some("point") => doc.point(id).is_some(),
300                    Some("constraint") => doc
301                        .constraints
302                        .iter()
303                        .any(|c| c.raw.get("id").map(id_key) == Some(id_key(id))),
304                    _ => false,
305                }
306            };
307            let restore: Vec<serde_json::Value> = kept.into_iter().filter(|r| alive(r)).collect();
308            if !deleted {
309                edit.session.clear_selection();
310            }
311            for r in restore {
312                edit.session.toggle_selection(r);
313            }
314        }
315        self.refresh_sketch_overlay();
316        self.dirty = true;
317        deleted
318    }
319
320    /// Hover an entity BY ref from a list row (list→canvas highlight). Sets the
321    /// one-frame guard so the viewport — which draws after the panel and would
322    /// otherwise clear the hover because the pointer is off the viewport — keeps it.
323    pub fn sketch_hover_entity(&mut self, kind: &str, id: serde_json::Value) {
324        if self.sketch_edit.is_none() {
325            return;
326        }
327        // `set_sketch_hover` re-tessellates only when the hovered ref actually
328        // changes, so holding the pointer on one row does not churn the overlay.
329        let entity_ref = serde_json::json!({ "kind": kind, "id": id });
330        self.set_sketch_hover(Some(entity_ref));
331        self.sketch_list_hover_active = true;
332    }
333
334    /// Consume the "list panel set the hover this frame" guard (read + reset). The
335    /// viewport calls this before its off-viewport `sketch_clear_hover` so a
336    /// panel-set hover survives the frame.
337    pub fn take_sketch_list_hover(&mut self) -> bool {
338        std::mem::take(&mut self.sketch_list_hover_active)
339    }
340
341    /// The active sketch's solver settings (the Solver Settings panel reads this).
342    /// `None` when not editing a sketch.
343    pub fn sketch_solver_settings(&self) -> Option<crate::sketch::SketchSolverSettings> {
344        self.sketch_edit
345            .as_ref()
346            .map(|edit| edit.session.solver_settings.clone())
347    }
348
349    /// Replace the active sketch's solver settings and re-solve so the change
350    /// takes effect immediately. No-op when not editing a sketch.
351    pub fn sketch_set_solver_settings(&mut self, settings: crate::sketch::SketchSolverSettings) {
352        if let Some(edit) = self.sketch_edit.as_mut() {
353            edit.session.solver_settings = settings;
354        } else {
355            return;
356        }
357        self.resolve_active_sketch("solver settings");
358        self.refresh_sketch_overlay();
359        self.dirty = true;
360    }
361}
362
363/// One applicable-constraint palette entry: the glyph passed back to
364/// [`EngineState::sketch_add_constraint`] plus a human tooltip and a dimensional
365/// tag (whether it opens a value the solver seeds from the current measurement).
366#[derive(Clone, Debug, PartialEq)]
367pub struct SketchConstraintAction {
368    /// The constraint glyph (e.g. `"━"`, `"⟂"`, `"R"`) — the argument to
369    /// [`EngineState::sketch_add_constraint`].
370    pub symbol: String,
371    /// A human tooltip label (e.g. `"Horizontal"`, `"Radius"`).
372    pub label: String,
373    /// Whether this is a dimensional constraint (its value is seeded from the
374    /// current measurement; S5 makes it editable).
375    pub dimensional: bool,
376}
377
378impl EngineState {
379    /// The ordered palette of constraints applicable to the active sketch selection
380    /// (a faithful port of `#refreshContextBar`). Empty when not in sketch mode or
381    /// the selection surfaces no constraint. The Fix/Unfix + construction + cleanup
382    /// affordances are exposed separately (see [`sketch_selection_all_grounded`] /
383    /// [`sketch_selection_all_construction`] / [`sketch_cleanup_unused_points`]).
384    ///
385    /// [`sketch_selection_all_grounded`]: Self::sketch_selection_all_grounded
386    /// [`sketch_selection_all_construction`]: Self::sketch_selection_all_construction
387    /// [`sketch_cleanup_unused_points`]: Self::sketch_cleanup_unused_points
388    pub fn sketch_applicable_constraints(&self) -> Vec<SketchConstraintAction> {
389        match self.sketch_edit.as_ref() {
390            Some(edit) => sketch_palette_for(&edit.session),
391            None => Vec::new(),
392        }
393    }
394
395    /// Add the constraint named by `symbol` from the current selection (a port of
396    /// `createConstraint`): build the ordered point-id list, dedup on
397    /// `type + sorted-points`, append (dimensional → `value:null`), then re-solve +
398    /// refresh (keeping the selection). Returns whether a constraint was added.
399    pub fn sketch_add_constraint(&mut self, symbol: &str) -> bool {
400        // Snapshot BEFORE the (in-place) add; discard it below when the add is a
401        // dedup no-op so a dead click neither pollutes undo nor clobbers redo (S6a).
402        let added = match self.sketch_edit.as_mut() {
403            Some(edit) => {
404                edit.record_undo();
405                sketch_build_and_add_constraint(&mut edit.session, symbol)
406            }
407            None => return false,
408        };
409        if added {
410            self.resolve_active_sketch("add-constraint");
411            self.refresh_sketch_overlay();
412            self.dirty = true;
413        } else if let Some(edit) = self.sketch_edit.as_mut() {
414            edit.undo_stack.pop();
415        }
416        added
417    }
418
419    /// Toggle the ground (`⏚`) constraint on the selected points: if ALL selected
420    /// points are already grounded → remove those grounds (and clear their `fixed`
421    /// flag); else add a `⏚` for each ungrounded selected point (and set `fixed`).
422    /// Re-solves + refreshes. Returns whether anything changed. No-op with no point
423    /// selected / not in sketch mode.
424    pub fn sketch_toggle_ground(&mut self) -> bool {
425        use crate::sketch::doc::id_key;
426        use std::collections::HashSet;
427
428        let Some(edit) = self.sketch_edit.as_mut() else {
429            return false;
430        };
431        let sel_ids: Vec<serde_json::Value> = edit
432            .session
433            .selection.items
434            .iter()
435            .filter(|r| r.get("kind").and_then(|v| v.as_str()) == Some("point"))
436            .filter_map(|r| r.get("id").cloned())
437            // The part-origin reference stays grounded.
438            .filter(|id| !crate::sketch::external_ref::is_origin_id(id))
439            .collect();
440        if sel_ids.is_empty() {
441            return false;
442        }
443        // Selected points → the toggle always adds or removes grounds; snapshot (S6a).
444        edit.record_undo();
445        let doc = &mut edit.session.doc;
446        let has_ground = |doc: &crate::sketch::SketchDoc, id: &serde_json::Value| -> bool {
447            doc.constraints.iter().any(|c| {
448                c.ctype() == Some("⏚")
449                    && c.points().first().map(id_key) == Some(id_key(id))
450            })
451        };
452        let all_grounded = sel_ids.iter().all(|id| has_ground(doc, id));
453        if all_grounded {
454            let sel_keys: HashSet<String> = sel_ids.iter().map(id_key).collect();
455            doc.constraints.retain(|c| {
456                if c.ctype() != Some("⏚") {
457                    return true;
458                }
459                match c.points().first() {
460                    Some(p) => !sel_keys.contains(&id_key(p)),
461                    None => true,
462                }
463            });
464            for id in &sel_ids {
465                if let Some(p) = doc.point_mut(id) {
466                    p.fixed = false;
467                }
468            }
469        } else {
470            for id in &sel_ids {
471                if has_ground(doc, id) {
472                    continue;
473                }
474                let cid = doc.next_constraint_id();
475                let mut raw = serde_json::Map::new();
476                raw.insert("id".to_string(), cid);
477                raw.insert("type".to_string(), serde_json::Value::String("⏚".to_string()));
478                raw.insert(
479                    "points".to_string(),
480                    serde_json::Value::Array(vec![id.clone()]),
481                );
482                doc.constraints.push(crate::sketch::SketchConstraint { raw });
483                if let Some(p) = doc.point_mut(id) {
484                    p.fixed = true;
485                }
486            }
487        }
488        self.resolve_active_sketch("toggle-ground");
489        self.refresh_sketch_overlay();
490        self.dirty = true;
491        true
492    }
493
494    /// Flip the `construction` flag on ALL selected points AND geometries: if every
495    /// selected entity is already construction → make them regular, else make them
496    /// all construction. Re-solves + refreshes. Returns whether anything was
497    /// selected. No-op with nothing selected / not in sketch mode.
498    pub fn sketch_toggle_construction(&mut self) -> bool {
499        if self.sketch_selection_has_text_frame() { return false; }
500        let Some(edit) = self.sketch_edit.as_mut() else {
501            return false;
502        };
503        let mut pt_ids: Vec<serde_json::Value> = Vec::new();
504        let mut geo_ids: Vec<serde_json::Value> = Vec::new();
505        for r in &edit.session.selection.items {
506            match r.get("kind").and_then(|v| v.as_str()) {
507                Some("point") => {
508                    // The part-origin reference stays construction.
509                    if let Some(id) = r.get("id").filter(|id| !crate::sketch::external_ref::is_origin_id(id)) {
510                        pt_ids.push(id.clone());
511                    }
512                }
513                Some("geometry") => {
514                    if let Some(id) = r.get("id") {
515                        geo_ids.push(id.clone());
516                    }
517                }
518                _ => {}
519            }
520        }
521        if pt_ids.is_empty() && geo_ids.is_empty() {
522            return false;
523        }
524        // Selected entities → the flip always changes something; snapshot (S6a).
525        edit.record_undo();
526        let doc = &mut edit.session.doc;
527        let all_construction = pt_ids
528            .iter()
529            .all(|id| doc.point(id).map_or(false, |p| p.construction))
530            && geo_ids
531                .iter()
532                .all(|id| doc.geometry(id).map_or(false, |g| g.construction()));
533        let next = !all_construction;
534        for id in &pt_ids {
535            if let Some(p) = doc.point_mut(id) {
536                p.construction = next;
537            }
538        }
539        for id in &geo_ids {
540            if let Some(g) = doc.geometry_mut(id) {
541                g.extra
542                    .insert("construction".to_string(), serde_json::Value::Bool(next));
543            }
544        }
545        self.resolve_active_sketch("toggle-construction");
546        self.refresh_sketch_overlay();
547        self.dirty = true;
548        true
549    }
550
551    /// Remove points referenced by NO geometry AND no constraint (the 🧹 action).
552    /// Re-solves + refreshes only when something was dropped. Returns whether a
553    /// point was removed. No-op when not in sketch mode.
554    pub fn sketch_cleanup_unused_points(&mut self) -> bool {
555        use crate::sketch::doc::id_key;
556        use std::collections::HashSet;
557
558        let Some(edit) = self.sketch_edit.as_mut() else {
559            return false;
560        };
561        // Snapshot before the cleanup; discarded below when nothing is removed (S6a).
562        edit.record_undo();
563        let doc = &mut edit.session.doc;
564        let mut used: HashSet<String> = HashSet::new();
565        for g in &doc.geometries {
566            for pid in &g.points {
567                used.insert(id_key(pid));
568            }
569        }
570        for c in &doc.constraints {
571            for pid in c.points() {
572                used.insert(id_key(pid));
573            }
574        }
575        let before = doc.points.len();
576        doc.points.retain(|p| used.contains(&id_key(&p.id)));
577        let removed = doc.points.len() != before;
578        if !removed {
579            edit.undo_stack.pop();
580            return false;
581        }
582        self.resolve_active_sketch("cleanup");
583        self.refresh_sketch_overlay();
584        self.dirty = true;
585        true
586    }
587
588    /// The number of constraints in the active sketch (0 when not in sketch mode) —
589    /// the verifier / palette readout.
590    pub fn sketch_constraint_count(&self) -> usize {
591        self.sketch_edit
592            .as_ref()
593            .map_or(0, |edit| edit.session.doc.constraints.len())
594    }
595
596    /// Whether the selected points are ALL grounded (`Some(true)`), NOT all grounded
597    /// (`Some(false)`), or no point is selected (`None`) — labels the Fix vs Unfix
598    /// button.
599    pub fn sketch_selection_all_grounded(&self) -> Option<bool> {
600        use crate::sketch::doc::id_key;
601        let edit = self.sketch_edit.as_ref()?;
602        let doc = &edit.session.doc;
603        let sel: Vec<&serde_json::Value> = edit
604            .session
605            .selection.items
606            .iter()
607            .filter(|r| r.get("kind").and_then(|v| v.as_str()) == Some("point"))
608            .filter_map(|r| r.get("id"))
609            .collect();
610        if sel.is_empty() {
611            return None;
612        }
613        let all = sel.iter().all(|id| {
614            doc.constraints.iter().any(|c| {
615                c.ctype() == Some("⏚")
616                    && c.points().first().map(id_key) == Some(id_key(id))
617            })
618        });
619        Some(all)
620    }
621
622    /// Whether the selected points + geometries are ALL construction (`Some(true)`),
623    /// NOT all construction (`Some(false)`), or nothing is selected (`None`) — labels
624    /// the ◐ construction-toggle button's direction.
625    pub fn sketch_selection_all_construction(&self) -> Option<bool> {
626        if self.sketch_selection_has_text_frame() { return None; }
627        let edit = self.sketch_edit.as_ref()?;
628        let doc = &edit.session.doc;
629        let mut any = false;
630        let mut all = true;
631        for r in &edit.session.selection.items {
632            match r.get("kind").and_then(|v| v.as_str()) {
633                Some("point") => {
634                    any = true;
635                    if let Some(id) = r.get("id") {
636                        if !doc.point(id).map_or(false, |p| p.construction) {
637                            all = false;
638                        }
639                    }
640                }
641                Some("geometry") => {
642                    any = true;
643                    if let Some(id) = r.get("id") {
644                        if !doc.geometry(id).map_or(false, |g| g.construction()) {
645                            all = false;
646                        }
647                    }
648                }
649                _ => {}
650            }
651        }
652        if !any {
653            return None;
654        }
655        Some(all)
656    }
657}
658
659/// Build the applicable-constraint palette for a session's selection — the port of
660/// `SketchMode3D.#refreshContextBar`'s branch logic (constraint buttons only; the
661/// state toggles + cleanup + delete are returned via companion accessors).
662fn sketch_palette_for(session: &crate::sketch::SketchSession) -> Vec<SketchConstraintAction> {
663    use crate::sketch::doc::id_key;
664    use std::collections::HashSet;
665
666    let doc = &session.doc;
667    let mut sel_points: Vec<serde_json::Value> = Vec::new();
668    let mut geos: Vec<&crate::sketch::SketchGeometry> = Vec::new();
669    for r in &session.selection.items {
670        match r.get("kind").and_then(|v| v.as_str()) {
671            Some("point") => {
672                if let Some(id) = r.get("id") {
673                    sel_points.push(id.clone());
674                }
675            }
676            Some("geometry") => {
677                if let Some(id) = r.get("id") {
678                    if let Some(g) = doc.geometry(id) {
679                        geos.push(g);
680                    }
681                }
682            }
683            _ => {}
684        }
685    }
686
687    if geos.iter().any(|g| g.geom_type == "text") { return Vec::new(); }
688
689    // point-coverage = selected point ids ∪ endpoints of selected geometries
690    // (arc: only points[0..2] — center + start).
691    let mut point_set: HashSet<String> = HashSet::new();
692    for id in &sel_points {
693        point_set.insert(id_key(id));
694    }
695    for g in &geos {
696        let pts: &[serde_json::Value] = if g.geom_type == "arc" {
697            &g.points[..g.points.len().min(2)]
698        } else {
699            &g.points
700        };
701        for pid in pts {
702            point_set.insert(id_key(pid));
703        }
704    }
705    let point_count = point_set.len();
706    let selected_point_ids_len = sel_points.len();
707    let is_radial =
708        |g: &crate::sketch::SketchGeometry| g.geom_type == "arc" || g.geom_type == "circle";
709
710    let mut out: Vec<SketchConstraintAction> = Vec::new();
711    let mut push = |symbol: &str, label: &str, dimensional: bool| {
712        out.push(SketchConstraintAction {
713            symbol: symbol.to_string(),
714            label: label.to_string(),
715            dimensional,
716        });
717    };
718
719    // 1 arc/circle → radial dims (defer the leader to S5).
720    if geos.len() == 1 && is_radial(geos[0]) {
721        push("R", "Radius", true);
722        push("⌀", "Diameter", true);
723        return out;
724    }
725    // 2 lines → parallel / perp / angle / equal-length / collinear / point-on-line,
726    // plus tangent when either line is a spline HANDLE GUIDE. A guide IS a line, so
727    // every offer above stays legitimate on one (its two ends are still two points
728    // whose direction can be made parallel to another line's); tangency is the extra
729    // question only a guide can be asked, and it is the reason a guide gets selected
730    // at all. Both new pairs — guide + line and guide + guide — are pairs the
731    // solver's `c_tangent` already reads as a spline tangent, at a drawn end and at
732    // an inserted interior anchor alike.
733    if geos.len() == 2 && geos.iter().all(|g| g.geom_type == "line") {
734        push("∥", "Parallel", false);
735        push("⟂", "Perpendicular", false);
736        push("∠", "Angle", true);
737        push("⇌", "Equal distance", false);
738        push("⋰", "Collinear", false);
739        push("⏛", "Point on line", false);
740        if geos
741            .iter()
742            .any(|g| crate::sketch::spline::is_handle_guide(doc, g))
743        {
744            push("⌒", "Tangent", false);
745        }
746        // Curvature (G2) is the narrower question: the two guides have to be the
747        // two sides of ONE joint — either side of one interior anchor, or two
748        // ends the document already holds together. A guide paired with a plain
749        // line is never one (a line has no curvature to match), and neither are
750        // two guides at unrelated anchors.
751        if crate::sketch::spline::is_curvature_joint(doc, geos[0], geos[1]) {
752            push("ϰ", "Curvature (G2)", false);
753        }
754        return out;
755    }
756    // 2 arcs/circles → equal-radius / concentric / tangent.
757    if geos.len() == 2 && geos.iter().all(|g| is_radial(g)) {
758        push("⊜", "Equal radius", false);
759        push("◎", "Concentric", false);
760        push("⌒", "Tangent", false);
761        return out;
762    }
763    // 3+ lines → equal length; 3+ arcs/circles → equal radius. The other pair
764    // relations have no many-geometry reading, so equality is the only offer; the
765    // build anchors every further geometry to the first selected (N−1 constraints).
766    if geos.len() > 2 && sel_points.is_empty() {
767        if geos.iter().all(|g| g.geom_type == "line") {
768            push("⇌", "Equal distance", false);
769            return out;
770        }
771        if geos.iter().all(|g| is_radial(g)) {
772            push("⊜", "Equal radius", false);
773            return out;
774        }
775    }
776    // line + arc/circle → tangent, plus curvature when the line is a spline
777    // handle guide at an END anchor: the spline's curvature there becomes the
778    // circle's 1/ρ, which is how a curve is continued into an arc.
779    if geos.len() == 2
780        && ((geos[0].geom_type == "line" && is_radial(geos[1]))
781            || (geos[1].geom_type == "line" && is_radial(geos[0])))
782    {
783        push("⌒", "Tangent", false);
784        if geos
785            .iter()
786            .any(|g| crate::sketch::spline::is_end_handle_guide(doc, g))
787        {
788            push("ϰ", "Curvature (G2)", false);
789        }
790        return out;
791    }
792    // A spline BODY + a line, or a spline body + an arc/circle → tangency at a
793    // point INTERIOR to one of the spline's spans (`∿`).
794    //
795    // The PICK is the whole difference from `⌒`. Selecting an anchor's handle
796    // guide asks for tangency AT that anchor, where the spline's tangent has a
797    // name (anchor→handle) and no touch parameter is needed — that stays `⌒`.
798    // Selecting the curve ITSELF asks for tangency wherever the two geometries
799    // actually touch, which is the foot-parameter lane and a different
800    // constraint type. So a guide is refused here, and a body is refused there.
801    if sketch_foot_tangent_pair(doc, &geos).is_some() {
802        push("∿", "Tangent (span point)", false);
803        return out;
804    }
805    // 1 line + 2 selected points → perpendicular / symmetric-about-line (no return).
806    if geos.len() == 1 && geos[0].geom_type == "line" && selected_point_ids_len == 2 {
807        push("⟂", "Perpendicular", false);
808        push("⋈", "Symmetric about line", false);
809    }
810
811    if point_count == 1 {
812        push("⏚", "Ground (fix point)", false);
813    }
814    if point_count == 2 {
815        push("━", "Horizontal", false);
816        push("│", "Vertical", false);
817        push("≡", "Coincident", false);
818        push("⟺", "Distance", true);
819    }
820    if point_count == 3 {
821        push("⋯", "Midpoint", false);
822        push("⏛", "Point on line", false);
823        push("↥", "Line to point distance", true);
824        push("∠", "Angle", true);
825        // Collinear needs 3+ ACTUAL selected points (not derived from geometry).
826        if selected_point_ids_len >= 3 {
827            push("⋰", "Collinear", false);
828        }
829    }
830    // 4+ free-standing points → still offer Collinear.
831    if point_count > 3 && geos.is_empty() && selected_point_ids_len >= 3 {
832        push("⋰", "Collinear", false);
833    }
834
835    out
836}
837
838/// The point-id list for a tangent (`⌒`) constraint
839/// from two selected geometries — `[lineA, lineB, center, boundary]` for line+circle,
840/// `[c1, boundary1, c2, boundary2]` for circle+circle, and `[a0, a1, b0, b1]` for two
841/// lines of which at least one is a spline handle guide. `None` for any other pair.
842///
843/// The guide gate on the two-line case is not decoration: the solver's `c_tangent`
844/// falls through to `c_tangent_line_circle` for a pair it cannot read as a spline,
845/// which would take the second line's two ends for a circle's centre and rim. A pair
846/// of plain lines has no tangency to state, so it is refused here rather than
847/// silently stored as a nonsense circle.
848fn sketch_build_tangent_points(
849    doc: &crate::sketch::SketchDoc,
850    geos: &[&crate::sketch::SketchGeometry],
851) -> Option<Vec<serde_json::Value>> {
852    if geos.len() != 2 {
853        return None;
854    }
855    let is_radial = |g: &crate::sketch::SketchGeometry| g.geom_type == "arc" || g.geom_type == "circle";
856    if geos.iter().all(|g| g.geom_type == "line") {
857        let (a, b) = (geos[0], geos[1]);
858        if a.points.len() < 2 || b.points.len() < 2 {
859            return None;
860        }
861        if !crate::sketch::spline::is_handle_guide(doc, a)
862            && !crate::sketch::spline::is_handle_guide(doc, b)
863        {
864            return None;
865        }
866        return Some(vec![
867            a.points[0].clone(),
868            a.points[1].clone(),
869            b.points[0].clone(),
870            b.points[1].clone(),
871        ]);
872    }
873    let line = geos.iter().find(|g| g.geom_type == "line");
874    let circ = geos.iter().find(|g| is_radial(g));
875    if let (Some(line), Some(circ)) = (line, circ) {
876        if line.points.len() < 2 || circ.points.len() < 2 {
877            return None;
878        }
879        return Some(vec![
880            line.points[0].clone(),
881            line.points[1].clone(),
882            circ.points[0].clone(),
883            circ.points[1].clone(),
884        ]);
885    }
886    if geos.iter().all(|g| is_radial(g)) {
887        let (a, b) = (geos[0], geos[1]);
888        if a.points.len() < 2 || b.points.len() < 2 {
889            return None;
890        }
891        return Some(vec![
892            a.points[0].clone(),
893            a.points[1].clone(),
894            b.points[0].clone(),
895            b.points[1].clone(),
896        ]);
897    }
898    None
899}
900
901/// The `(spline body, line-or-circle)` pair a foot-parameter tangency (`∿`) is
902/// offered for, or `None` for any other selection.
903///
904/// ONE gate, read by both the palette offer and the point-list builder, so an
905/// offered `∿` is an `∿` that builds and solves — the same contract the tangent's
906/// guide gate carries. What it admits:
907///
908/// * exactly two geometries, one of them a spline (a `3n + 1` control polygon),
909/// * the other a plain line or an arc/circle,
910/// * and NOT a spline handle guide: a guide is a line whose two ends are the
911///   spline's own control points, so tangency to it would be tangency of the
912///   curve to its own construction artifact. Tangency at the anchor a guide
913///   stands for is `⌒`'s lane, which is where that selection belongs.
914fn sketch_foot_tangent_pair<'a>(
915    doc: &crate::sketch::SketchDoc,
916    geos: &[&'a crate::sketch::SketchGeometry],
917) -> Option<(&'a crate::sketch::SketchGeometry, &'a crate::sketch::SketchGeometry)> {
918    if geos.len() != 2 {
919        return None;
920    }
921    let is_spline = |g: &crate::sketch::SketchGeometry| {
922        crate::sketch::spline::is_spline_type(&g.geom_type)
923    };
924    let is_radial =
925        |g: &crate::sketch::SketchGeometry| g.geom_type == "arc" || g.geom_type == "circle";
926    let spline = *geos.iter().find(|g| is_spline(g))?;
927    let target = *geos.iter().find(|g| !is_spline(g))?;
928    if spline.points.len() < 4 || target.points.len() < 2 {
929        return None;
930    }
931    let target_is_usable = if target.geom_type == "line" {
932        !crate::sketch::spline::is_handle_guide(doc, target)
933    } else {
934        is_radial(target)
935    };
936    target_is_usable.then_some((spline, target))
937}
938
939/// The point-id list for a foot-parameter tangency (`∿`) —
940/// `[lineA, lineB, s0, s1]` against a line, `[center, boundary, s0, s1]` against
941/// an arc/circle, where `(s0, s1)` are the SPLINE's first two control ids acting
942/// as a geometry handle.
943///
944/// The spline is named by a pair rather than by its geometry id because a
945/// constraint record's only geometric field is `points` — the same reason the
946/// tangent names a circle by `(centre, rim)`. Two leading controls identify one
947/// spline: a document cannot hold two curves that start from the same two points
948/// without them being the same curve.
949fn sketch_build_foot_tangent_points(
950    doc: &crate::sketch::SketchDoc,
951    geos: &[&crate::sketch::SketchGeometry],
952) -> Option<Vec<serde_json::Value>> {
953    let (spline, target) = sketch_foot_tangent_pair(doc, geos)?;
954    Some(vec![
955        target.points[0].clone(),
956        target.points[1].clone(),
957        spline.points[0].clone(),
958        spline.points[1].clone(),
959    ])
960}
961
962/// The point-id list for a curvature (`ϰ`) constraint from two selected
963/// geometries — the SAME two-pair shape the tangent uses, so the solver's
964/// dispatch reads it the same way: `[anchorA, handleA, anchorB, handleB]` for a
965/// joint, `[anchor, handle, center, boundary]` against a circle/arc.
966///
967/// Gated on exactly what the palette offers, for the same reason the tangent's
968/// guide gate exists: an offered curvature continuity is one that solves. A
969/// spline end against a circle is a join; two guides are a join only when they
970/// are the two sides of one joint; anything else — two plain lines, a guide and
971/// an unrelated line, two ends with nothing holding them together — has no
972/// curvature continuity to state and is refused here rather than stored as a
973/// constraint the solver would have to name an error on.
974fn sketch_build_curvature_points(
975    doc: &crate::sketch::SketchDoc,
976    geos: &[&crate::sketch::SketchGeometry],
977) -> Option<Vec<serde_json::Value>> {
978    if geos.len() != 2 {
979        return None;
980    }
981    let is_radial =
982        |g: &crate::sketch::SketchGeometry| g.geom_type == "arc" || g.geom_type == "circle";
983    if geos.iter().all(|g| g.geom_type == "line") {
984        if !crate::sketch::spline::is_curvature_joint(doc, geos[0], geos[1]) {
985            return None;
986        }
987        let (a, b) = (geos[0], geos[1]);
988        return Some(vec![
989            a.points[0].clone(),
990            a.points[1].clone(),
991            b.points[0].clone(),
992            b.points[1].clone(),
993        ]);
994    }
995    let guide = geos
996        .iter()
997        .find(|g| crate::sketch::spline::is_end_handle_guide(doc, g))?;
998    let circ = geos.iter().find(|g| is_radial(g))?;
999    if circ.points.len() < 2 {
1000        return None;
1001    }
1002    Some(vec![
1003        guide.points[0].clone(),
1004        guide.points[1].clone(),
1005        circ.points[0].clone(),
1006        circ.points[1].clone(),
1007    ])
1008}
1009
1010/// Whether the perpendicular (`⟂`) 4-point list should SWAP its first two points to
1011/// orient line 1 closer to 90° against line 2 — a faithful port of the previous
1012/// angle-calculation block. `pts = [l1a, l1b, l2a, l2b]`.
1013pub(super) fn sketch_perpendicular_should_swap(
1014    doc: &crate::sketch::SketchDoc,
1015    pts: &[serde_json::Value],
1016) -> bool {
1017    let coord = |v: &serde_json::Value| doc.point(v).map(|p| (p.x, p.y));
1018    let (Some(p0), Some(p1), Some(p2), Some(p3)) =
1019        (coord(&pts[0]), coord(&pts[1]), coord(&pts[2]), coord(&pts[3]))
1020    else {
1021        return false;
1022    };
1023    // calculateAngle(a, b) = atan2(b.y-a.y, b.x-a.x) in [0, 360).
1024    let angle = |a: (f64, f64), b: (f64, f64)| -> f64 {
1025        let deg = (b.1 - a.1).atan2(b.0 - a.0) * 180.0 / std::f64::consts::PI;
1026        (deg + 360.0) % 360.0
1027    };
1028    // Fold into (-180, 180]: (a + 180) % 360 - 180.
1029    let fold = |a: f64| (a + 180.0) % 360.0 - 180.0;
1030    let line1_a = fold(angle(p0, p1));
1031    let line1_b = fold(angle(p1, p0));
1032    let line2 = fold(angle(p2, p3));
1033    let diff_a = line1_a - line2;
1034    let diff_b = line1_b - line2;
1035    (90.0 - diff_a).abs() > (90.0 - diff_b).abs()
1036}
1037
1038/// The `type + sorted-point-ids` dedup signature (the solver runs with
1039/// `remove_implied_duplicates:false`, so this is the only dedup on adds).
1040pub(super) fn sketch_constraint_signature(ctype: &str, points: &[serde_json::Value]) -> String {
1041    use crate::sketch::doc::id_key;
1042    let mut keys: Vec<String> = points.iter().map(id_key).collect();
1043    keys.sort();
1044    format!("{ctype}|{}", keys.join(","))
1045}
1046
1047/// The port of `ConstraintEngine.createConstraint`: from the session's selection build
1048/// the ordered point-id list(s) for `symbol`, dedup on `type + sorted-points`, and
1049/// append the constraint(s) (dimensional → `value:null` + `valueNeedsSetup:true`).
1050/// Returns whether at least one constraint was added. The caller re-solves.
1051fn sketch_build_and_add_constraint(
1052    session: &mut crate::sketch::SketchSession,
1053    symbol: &str,
1054) -> bool {
1055    /// The constraint(s) to append for a symbol: the stored solver `type`, its
1056    /// display style, and one or more ordered point-id lists (`⏛`-from-2-lines and
1057    /// the like push several).
1058    struct Built {
1059        store_type: String,
1060        display_style: &'static str,
1061        lists: Vec<Vec<serde_json::Value>>,
1062    }
1063
1064    /// `[first.p0, first.p1, other.p0, other.p1]` for every geometry after the first:
1065    /// line ends for `⇌`, centre + rim for `⊜`.
1066    fn sketch_equal_to_first(t: &str, geos: &[&crate::sketch::SketchGeometry]) -> Built {
1067        let first = geos[0];
1068        Built {
1069            store_type: t.to_string(),
1070            display_style: "",
1071            lists: geos[1..]
1072                .iter()
1073                .map(|g| {
1074                    vec![
1075                        first.points[0].clone(),
1076                        first.points[1].clone(),
1077                        g.points[0].clone(),
1078                        g.points[1].clone(),
1079                    ]
1080                })
1081                .collect(),
1082        }
1083    }
1084
1085    // --- Phase 1: read-only — assemble the constraint(s) from the selection. ---
1086    let built: Option<Built> = {
1087        let doc = &session.doc;
1088        // `selected` mirrors the previous behavior: point → push it; geometry → push all its
1089        // points, arc pops the last (center + start). `geo_items`/`point_items` are
1090        // the role-based lists the specials use; `geometry_type` is the LAST
1091        // geometry's type; `first_kind` drives the `⋯` reverse.
1092        let mut selected: Vec<serde_json::Value> = Vec::new();
1093        let mut geo_items: Vec<&crate::sketch::SketchGeometry> = Vec::new();
1094        let mut point_items: Vec<serde_json::Value> = Vec::new();
1095        let mut geometry_type: Option<String> = None;
1096        let mut first_kind: Option<String> = None;
1097        let mut has_geometry = false;
1098        for (i, r) in session.selection.items.iter().enumerate() {
1099            let kind = r.get("kind").and_then(|v| v.as_str());
1100            let Some(id) = r.get("id") else { continue };
1101            if i == 0 {
1102                first_kind = kind.map(|k| k.to_string());
1103            }
1104            match kind {
1105                Some("point") => {
1106                    if let Some(p) = doc.point(id) {
1107                        selected.push(p.id.clone());
1108                        point_items.push(p.id.clone());
1109                    }
1110                }
1111                Some("geometry") => {
1112                    if let Some(g) = doc.geometry(id) {
1113                        for pid in &g.points {
1114                            if doc.point(pid).is_some() {
1115                                selected.push(pid.clone());
1116                            }
1117                        }
1118                        if g.geom_type == "arc" {
1119                            selected.pop();
1120                        }
1121                        geometry_type = Some(g.geom_type.clone());
1122                        geo_items.push(g);
1123                        has_geometry = true;
1124                    }
1125                }
1126                _ => {}
1127            }
1128        }
1129        if selected.is_empty() {
1130            None
1131        } else {
1132            let radial = |g: &crate::sketch::SketchGeometry| {
1133                g.geom_type == "arc" || g.geom_type == "circle"
1134            };
1135            let simple = |t: &str, list: Vec<serde_json::Value>, ds: &'static str| Built {
1136                store_type: t.to_string(),
1137                display_style: ds,
1138                lists: vec![list],
1139            };
1140
1141            // ---- Geometry-role specials (dispatched by role, not point count). ----
1142            match symbol {
1143                "◎" => {
1144                    if geo_items.len() == 2 && geo_items.iter().all(|g| radial(g)) {
1145                        Some(simple(
1146                            "◎",
1147                            vec![geo_items[0].points[0].clone(), geo_items[1].points[0].clone()],
1148                            "",
1149                        ))
1150                    } else {
1151                        None
1152                    }
1153                }
1154                // Equal radius over 2+ arcs/circles: one `⊜` per further geometry,
1155                // each tied to the first selected, so N geometries give N−1
1156                // constraints and deleting one frees exactly one geometry.
1157                "⊜" => {
1158                    if geo_items.len() >= 2
1159                        && geo_items.iter().all(|g| radial(g) && g.points.len() >= 2)
1160                    {
1161                        Some(sketch_equal_to_first("⊜", &geo_items))
1162                    } else {
1163                        None
1164                    }
1165                }
1166                // Equal length over 2+ lines (and nothing else selected), anchored the
1167                // same way. Point selections fall through to the count-based `⇌`.
1168                "⇌" if geo_items.len() >= 2
1169                    && point_items.is_empty()
1170                    && geo_items
1171                        .iter()
1172                        .all(|g| g.geom_type == "line" && g.points.len() >= 2) =>
1173                {
1174                    Some(sketch_equal_to_first("⇌", &geo_items))
1175                }
1176                "⌒" => sketch_build_tangent_points(doc, &geo_items).map(|pts| simple("⌒", pts, "")),
1177                "ϰ" => {
1178                    sketch_build_curvature_points(doc, &geo_items).map(|pts| simple("ϰ", pts, ""))
1179                }
1180                "∿" => sketch_build_foot_tangent_points(doc, &geo_items)
1181                    .map(|pts| simple("∿", pts, "")),
1182                "⋰" => {
1183                    let ids = if geo_items.len() >= 2
1184                        && geo_items.iter().all(|g| g.geom_type == "line")
1185                    {
1186                        let mut v = Vec::new();
1187                        for g in &geo_items {
1188                            v.push(g.points[0].clone());
1189                            v.push(g.points[1].clone());
1190                        }
1191                        Some(v)
1192                    } else if point_items.len() >= 3 {
1193                        Some(point_items.clone())
1194                    } else {
1195                        None
1196                    };
1197                    ids.filter(|v| v.len() >= 3).map(|v| simple("⋰", v, ""))
1198                }
1199                "⋈" => geo_items
1200                    .iter()
1201                    .find(|g| g.geom_type == "line")
1202                    .filter(|line| line.points.len() >= 2 && point_items.len() == 2)
1203                    .map(|line| {
1204                        simple(
1205                            "⋈",
1206                            vec![
1207                                line.points[0].clone(),
1208                                line.points[1].clone(),
1209                                point_items[0].clone(),
1210                                point_items[1].clone(),
1211                            ],
1212                            "",
1213                        )
1214                    }),
1215                // Radial dims: a `⟺` on [center, boundary] with a radius/diameter
1216                // display style (single arc/circle; `selected` is arc-popped to 2).
1217                "R" | "⌀" => {
1218                    if selected.len() == 2 {
1219                        let ds = if symbol == "⌀" { "diameter" } else { "radius" };
1220                        Some(Built {
1221                            store_type: "⟺".to_string(),
1222                            display_style: ds,
1223                            lists: vec![selected.clone()],
1224                        })
1225                    } else {
1226                        None
1227                    }
1228                }
1229                _ => {
1230                    // ---- Count-based (mirrors the previous `selected.length` blocks). ----
1231                    match selected.len() {
1232                        1 => match symbol {
1233                            "⏚" => Some(simple("⏚", selected.clone(), "")),
1234                            _ => None,
1235                        },
1236                        2 => match symbol {
1237                            "━" | "│" | "≡" => Some(simple(symbol, selected.clone(), "")),
1238                            "⟺" => {
1239                                let ds = if matches!(
1240                                    geometry_type.as_deref(),
1241                                    Some("arc") | Some("circle")
1242                                ) {
1243                                    "radius"
1244                                } else {
1245                                    ""
1246                                };
1247                                Some(Built {
1248                                    store_type: "⟺".to_string(),
1249                                    display_style: ds,
1250                                    lists: vec![selected.clone()],
1251                                })
1252                            }
1253                            _ => None,
1254                        },
1255                        3 => match symbol {
1256                            "⏛" => Some(simple("⏛", selected.clone(), "")),
1257                            "⋯" => {
1258                                let mut pts = selected.clone();
1259                                if has_geometry && first_kind.as_deref() == Some("point") {
1260                                    pts.reverse();
1261                                }
1262                                Some(simple("⋯", pts, ""))
1263                            }
1264                            "↥" => {
1265                                if geo_items.len() == 1 && point_items.len() == 1 {
1266                                    let line = geo_items[0];
1267                                    if line.geom_type == "line" && line.points.len() >= 2 {
1268                                        Some(simple(
1269                                            "↥",
1270                                            vec![
1271                                                line.points[0].clone(),
1272                                                line.points[1].clone(),
1273                                                point_items[0].clone(),
1274                                            ],
1275                                            "",
1276                                        ))
1277                                    } else {
1278                                        None
1279                                    }
1280                                } else {
1281                                    // 3 raw points (no geometry) → point-line-distance
1282                                    // over the selection as-is.
1283                                    Some(simple("↥", selected.clone(), ""))
1284                                }
1285                            }
1286                            "⇌" => Some(simple("⇌", selected.clone(), "")),
1287                            _ => None,
1288                        },
1289                        4 | 5 => match symbol {
1290                            "⏛" => {
1291                                // Two lines → constrain BOTH endpoints of line 2 onto
1292                                // line 1 (two point-on-line constraints).
1293                                if geo_items.len() == 2
1294                                    && geo_items.iter().all(|g| g.geom_type == "line")
1295                                    && geo_items[0].points.len() >= 2
1296                                    && geo_items[1].points.len() >= 2
1297                                {
1298                                    let (g0, g1) = (geo_items[0], geo_items[1]);
1299                                    Some(Built {
1300                                        store_type: "⏛".to_string(),
1301                                        display_style: "",
1302                                        lists: vec![
1303                                            vec![
1304                                                g0.points[0].clone(),
1305                                                g0.points[1].clone(),
1306                                                g1.points[0].clone(),
1307                                            ],
1308                                            vec![
1309                                                g0.points[0].clone(),
1310                                                g0.points[1].clone(),
1311                                                g1.points[1].clone(),
1312                                            ],
1313                                        ],
1314                                    })
1315                                } else {
1316                                    None
1317                                }
1318                            }
1319                            "⟂" => {
1320                                if selected.len() != 4 {
1321                                    None
1322                                } else {
1323                                    let mut pts = selected.clone();
1324                                    if sketch_perpendicular_should_swap(doc, &pts) {
1325                                        pts.swap(0, 1);
1326                                    }
1327                                    Some(simple("⟂", pts, ""))
1328                                }
1329                            }
1330                            "∥" => Some(simple("∥", selected.clone(), "")),
1331                            "∠" => Some(simple("∠", selected.clone(), "")),
1332                            "⇌" => Some(simple("⇌", selected.clone(), "")),
1333                            _ => None,
1334                        },
1335                        _ => None,
1336                    }
1337                }
1338            }
1339        }
1340    };
1341
1342    let Some(built) = built else {
1343        return false;
1344    };
1345
1346    // --- Phase 2: mutate — dedup + append (every constraint carries the base
1347    //     fields; the solver seeds a null value from the current measurement). ---
1348    let doc = &mut session.doc;
1349    let mut added_any = false;
1350    for pts in &built.lists {
1351        let sig = sketch_constraint_signature(&built.store_type, pts);
1352        let duplicate = doc.constraints.iter().any(|c| match c.ctype() {
1353            Some(t) => sketch_constraint_signature(t, c.points()) == sig,
1354            None => false,
1355        });
1356        if duplicate {
1357            continue;
1358        }
1359        let id = doc.next_constraint_id();
1360        let mut raw = serde_json::Map::new();
1361        raw.insert("id".to_string(), id);
1362        raw.insert(
1363            "type".to_string(),
1364            serde_json::Value::String(built.store_type.clone()),
1365        );
1366        raw.insert("points".to_string(), serde_json::Value::Array(pts.clone()));
1367        raw.insert("labelX".to_string(), serde_json::Value::from(0));
1368        raw.insert("labelY".to_string(), serde_json::Value::from(0));
1369        raw.insert(
1370            "displayStyle".to_string(),
1371            serde_json::Value::String(built.display_style.to_string()),
1372        );
1373        raw.insert("value".to_string(), serde_json::Value::Null);
1374        raw.insert("valueNeedsSetup".to_string(), serde_json::Value::Bool(true));
1375        doc.constraints.push(crate::sketch::SketchConstraint { raw });
1376        added_any = true;
1377    }
1378    added_any
1379}
1380
1381
1382impl EngineState {
1383    fn sketch_selection_has_text_frame(&self) -> bool {
1384        let Some(edit) = &self.sketch_edit else { return false; };
1385        edit.session.selection.items.iter().any(|r| {
1386            let id = &r["id"];
1387            if r["kind"] == "geometry" {
1388                edit.session.doc.geometry(id).is_some_and(|g| g.geom_type == "text" || g.extra.contains_key("textFrame"))
1389            } else {
1390                edit.session.doc.geometries.iter().any(|g| g.geom_type == "text" && g.points.contains(id))
1391            }
1392        })
1393    }
1394
1395    pub fn sketch_selected_text(&self) -> Option<(serde_json::Value, String, String)> {
1396        let session = &self.sketch_edit.as_ref()?.session;
1397        if session.selection.items.len() != 1 { return None; }
1398        let r = &session.selection.items[0];
1399        if r["kind"] != "geometry" { return None; }
1400        let g = session.doc.geometry(&r["id"])?;
1401        if g.geom_type != "text" { return None; }
1402        Some((g.id.clone(), g.extra["text"].as_str()?.into(), g.extra["font"].as_str()?.into()))
1403    }
1404
1405    pub fn sketch_edit_text(&mut self, id: &serde_json::Value, text: &str, font: &str) -> Result<(), String> {
1406        let contours = crate::sketch::text::outlines(text,font)?;
1407        let edit = self.sketch_edit.as_mut().ok_or("No active sketch")?;
1408        let g = edit.session.doc.geometry(id).filter(|g| g.geom_type == "text").ok_or("Text object no longer exists")?;
1409        if g.extra["text"] == text && g.extra["font"] == font { return Ok(()); }
1410        edit.record_undo();
1411        let g = edit.session.doc.geometry_mut(id).unwrap();
1412        g.extra.insert("text".into(), serde_json::json!(text));
1413        g.extra.insert("font".into(), serde_json::json!(font));
1414        g.extra.insert("textContours".into(), contours);
1415        self.refresh_sketch_overlay();
1416        self.dirty = true;
1417        Ok(())
1418    }
1419}