1use super::*;
2
3#[derive(Clone, Debug, PartialEq)]
10pub struct SketchEntityRow {
11 pub kind: &'static str,
13 pub id: serde_json::Value,
15 pub label: String,
17 pub selected: bool,
19 pub construction: bool,
21 pub conflicting: bool,
24}
25
26#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
31pub enum NoticeSeverity {
32 #[default]
33 Error,
34 Warning,
35 Info,
36}
37
38impl EngineState {
39 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 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 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 pub fn take_notices(&mut self) -> Vec<String> {
78 self.take_graded_notices().into_iter().map(|(_, text)| text).collect()
79 }
80
81 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 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 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}"); }
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 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 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 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 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 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 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 pub fn sketch_hover_entity(&mut self, kind: &str, id: serde_json::Value) {
324 if self.sketch_edit.is_none() {
325 return;
326 }
327 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 pub fn take_sketch_list_hover(&mut self) -> bool {
338 std::mem::take(&mut self.sketch_list_hover_active)
339 }
340
341 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 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#[derive(Clone, Debug, PartialEq)]
367pub struct SketchConstraintAction {
368 pub symbol: String,
371 pub label: String,
373 pub dimensional: bool,
376}
377
378impl EngineState {
379 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 pub fn sketch_add_constraint(&mut self, symbol: &str) -> bool {
400 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 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 .filter(|id| !crate::sketch::external_ref::is_origin_id(id))
439 .collect();
440 if sel_ids.is_empty() {
441 return false;
442 }
443 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 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 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 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 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 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 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 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 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
659fn 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 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 if geos.len() == 1 && is_radial(geos[0]) {
721 push("R", "Radius", true);
722 push("⌀", "Diameter", true);
723 return out;
724 }
725 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 if crate::sketch::spline::is_curvature_joint(doc, geos[0], geos[1]) {
752 push("ϰ", "Curvature (G2)", false);
753 }
754 return out;
755 }
756 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 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 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 if sketch_foot_tangent_pair(doc, &geos).is_some() {
802 push("∿", "Tangent (span point)", false);
803 return out;
804 }
805 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 if selected_point_ids_len >= 3 {
827 push("⋰", "Collinear", false);
828 }
829 }
830 if point_count > 3 && geos.is_empty() && selected_point_ids_len >= 3 {
832 push("⋰", "Collinear", false);
833 }
834
835 out
836}
837
838fn 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
901fn 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
939fn 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
962fn 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
1010pub(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 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 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
1038pub(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
1047fn sketch_build_and_add_constraint(
1052 session: &mut crate::sketch::SketchSession,
1053 symbol: &str,
1054) -> bool {
1055 struct Built {
1059 store_type: String,
1060 display_style: &'static str,
1061 lists: Vec<Vec<serde_json::Value>>,
1062 }
1063
1064 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 let built: Option<Built> = {
1087 let doc = &session.doc;
1088 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 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 "⊜" => {
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 "⇌" 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 "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 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 Some(simple("↥", selected.clone(), ""))
1284 }
1285 }
1286 "⇌" => Some(simple("⇌", selected.clone(), "")),
1287 _ => None,
1288 },
1289 4 | 5 => match symbol {
1290 "⏛" => {
1291 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 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}