1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
//! Sketch panel (S1) — the engine-native sketcher's mode surfaces.
//!
//! Thin surfaces over [`EngineState`] (the single brain — it owns the sketch
//! edit; this panel only triggers its methods and reads it back), all drawn while
//! [`EngineState::sketch_mode`]:
//!
//! * The sketch STATUS row ([`SketchPanel::show_status_bar`]): the sketch title +
//! DOF readout + selection count + the in-progress click count + Lock-to-sketch
//! (undo/redo is on the main toolbar, which routes to the sketch history while
//! a sketch is open), rendered into the shell's persistent bottom status bar
//! (the same bar that hosts the modeling selection filter out of sketch mode).
//! * The LEFT entity lists ([`SketchPanel::show_entity_lists`]) and the top-right
//! CONTEXT actions ([`SketchPanel::context_card`]).
//!
//! There is NO draw-tools strip: the primitive draw tools (select / point /
//! line / rect / circle / …) and the one-shot Auto-constrain are workbench
//! buttons in the main toolbar row, declared once in [`crate::workbench::sketch`]
//! and offered by every workbench while a sketch is being edited. A mode's
//! tools live in one place, and that place is the row.
//!
//! Finish / Cancel (→ [`EngineState::exit_sketch_mode`]) live in the shared
//! top-right mode-exit card. Enter/exit rolls the model to the step before the
//! sketch and orients the camera onto the plane — all handled by the engine; the
//! shell just keeps the 3D viewport visible as the sketching surface.
use super::action_rail::{action_rail, ActionItem};
use crate::automation::hit_keys::HitKeyDoc;
use crate::panels::tree::{self, TreeRow};
use brep_render::engine_state::{EngineState, SketchEntityRow};
use brep_render::sketch::doc::id_key;
use eframe::egui;
use std::collections::HashMap;
/// The sketch panel's transient UI state (the sketch itself lives in the engine).
#[derive(Default)]
pub struct SketchPanel {
text_dialog: Option<(serde_json::Value, String, String)>,
text_error: Option<String>,
text_hits: HashMap<String, egui::Rect>,
/// Per-frame Sketch-actions card widget rects, published as `__brepSketchHit`.
ctx_hits: HashMap<String, egui::Rect>,
/// Per-frame entity-list widget rects, published as `__brepSketchListHit`.
/// A SEPARATE blob from the card's: the list scrolls and therefore carries a
/// `panel:clip`, while the card floats in the top-right overlay with no clip of
/// its own. Merged into one panel the automation host would test the card's rect
/// against the list's viewport and scroll for a widget that was never in it.
list_hits: HashMap<String, egui::Rect>,
/// Per-frame fillet/chamfer tool-options card widget rects (`tool:` keys),
/// published with the actions card in `__brepSketchHit`.
tool_hits: HashMap<String, egui::Rect>,
/// Collapse state for the entity-list sections (default open = false).
curves_collapsed: bool,
points_collapsed: bool,
constraints_collapsed: bool,
/// Solver Settings section starts COLLAPSED (advanced/rarely-touched).
solver_collapsed: bool,
/// The Issues section (conflicting + redundant constraints) collapse state.
issues_collapsed: bool,
/// The status dot was clicked: open the Issues section and scroll it into view
/// on the next list frame.
issues_reveal: bool,
/// The status row's clickable DOF readout (`issues`), published with the card
/// rects as `sketch/issues`.
status_hits: HashMap<String, egui::Rect>,
}
impl SketchPanel {
pub(crate) fn clear_context_hits(&mut self) { self.ctx_hits.clear(); }
pub(crate) fn clear_list_hits(&mut self) { self.list_hits.clear(); }
pub fn new() -> Self {
Self {
// Solver Settings is advanced — start it collapsed.
solver_collapsed: true,
..Self::default()
}
}
/// The sketch STATUS row, rendered into the shell's persistent bottom status
/// bar while [`EngineState::sketch_mode`]: the sketch title + DOF readout +
/// selection count + the in-progress click count + Lock-to-sketch. Draws
/// directly into the bottom bar's `ui` (no inner panel) so the bar can host it
/// in place of the modeling selection-filter row — demonstrating the status
/// bar's dynamic, context-selected content.
///
/// The "… N placed" readout came here when the draw-tools strip was folded
/// into the toolbar row: it is STATUS, not a tool — how many clicks of the
/// armed tool are buffered — so it belongs beside the selection count and not
/// among the buttons. A tool that swallows the next three clicks has to say
/// so, the same reason the sheet's armed-tool prompt is painted on the desk.
pub fn show_status_bar(&mut self, ui: &mut egui::Ui, state: &mut EngineState) {
ui.horizontal_wrapped(|ui| {
let id = state.sketch_edit_feature_id().unwrap_or("").to_string();
ui.label(egui::RichText::new(format!("Sketch: {id}")).strong());
ui.separator();
// The conflict red is read from the display settings (one editable
// palette entry drives the dot, the list rows, the glyphs and the
// dimension text), so it must be taken BEFORE the session borrow.
let colors = status_colors(state);
if let Some(session) = state.sketch_edit_session() {
// The readout is the way into the Issues list: a click opens it.
let resp = dof_readout(ui, &session.diagnostics, colors);
self.status_hits.insert("issues".to_string(), resp.rect);
if resp.clicked() {
self.issues_collapsed = false;
self.issues_reveal = true;
}
}
ui.separator();
ui.label(
egui::RichText::new(format!("{} selected", state.sketch_selection_count())).weak(),
);
let pending = state.sketch_pending_len();
if pending > 0 {
ui.separator();
ui.label(
egui::RichText::new(format!("\u{2026} {pending} placed"))
.weak()
.italics(),
);
}
ui.separator();
// Undo/redo is NOT here — while a sketch is open the MAIN toolbar's
// undo/redo pair drives the per-session sketch history (see
// `toolbar::Toolbar::edit_actions`), alongside the Ctrl+Z / Ctrl+Y
// keyboard router. Keeping one pair avoids a duplicate control.
// Camera lock (on by default): hold the view flat to the sketch plane
// and allow only panning. Toggling it back on re-faces the camera to
// the plane; off frees orbiting.
let mut locked = state.sketch_camera_locked();
if ui
.checkbox(&mut locked, "Lock to sketch")
.on_hover_text(
"Face the sketch plane and pan only. Uncheck to orbit; \
re-check to snap back flat.",
)
.changed()
{
state.toggle_sketch_camera_lock();
}
});
}
/// The armed fillet or chamfer tool's options, through the shared form view:
/// the fillet radius, or the chamfer's sizing (an `Equal distance` /
/// `Distance + angle` dropdown, the distance, the angle), with the last
/// refusal as an error banner. Its exit button puts the tool down. No-op
/// unless one of the two is armed. Hit keys carry the `tool:` prefix.
pub fn tool_options_card(&mut self, ui: &mut egui::Ui, state: &mut EngineState) {
use crate::form_view::{form_view, FormBanner, FormViewSpec};
use serde_json::{json, Value};
self.tool_hits.clear();
let fillet = match state.sketch_active_tool() {
Some("fillet") => true,
Some("chamfer") => false,
_ => return,
};
let Some(mut options) = state.sketch_corner_options() else { return };
const EQUAL: &str = "Equal distance";
const BY_ANGLE: &str = "Distance + angle";
let schema = if fillet {
json!({ "inputParamsSchema": {
"radius": { "type": "number", "label": "Radius (mm)", "default_value": 1.0,
"hint": "The arc's radius; it stays a dimension you can edit or drag afterwards" }
}})
} else {
json!({ "inputParamsSchema": {
"mode": { "type": "options", "label": "Size by", "options": [EQUAL, BY_ANGLE], "default_value": EQUAL },
"distance": { "type": "number", "label": "Distance (mm)", "default_value": 1.0,
"hint": "From the corner along the first line (and the second, when equal)" },
"angle": { "type": "number", "label": "Angle (deg)", "default_value": 45.0,
"hint": "The cut's angle to the first line" }
}})
};
let fields = brep_render::features::form_fields_from_schema(&schema);
let mut params = if fillet {
json!({ "radius": options.radius })
} else {
json!({
"mode": if options.chamfer_by_angle { BY_ANGLE } else { EQUAL },
"distance": options.chamfer_distance,
"angle": options.chamfer_angle_degrees,
})
};
let mut hidden: std::collections::HashSet<String> = Default::default();
if !fillet && !options.chamfer_by_angle {
hidden.insert("angle".to_string());
}
let message = state.sketch_corner_message();
let spec = FormViewSpec {
title: if fillet { "Fillet corner" } else { "Chamfer corner" },
subtitle: Some("Click where two lines meet"),
fields: &fields,
hidden: Some(&hidden),
banner: message.as_deref().map(|text| FormBanner::error(text, egui::Color32::from_rgb(0xf8, 0x51, 0x49))),
trailing: None,
exit_label: "Done",
extra: None,
rollback: false,
hits_prefix: "tool:",
read_only: None,
picking: None,
};
let out = form_view(ui, &spec, &mut params, Some(&mut self.tool_hits));
if out.changed {
let number = |key: &str| params.get(key).and_then(Value::as_f64).filter(|v| v.is_finite() && *v > 0.0);
if fillet {
if let Some(radius) = number("radius") {
options.radius = radius;
}
} else {
options.chamfer_by_angle = params.get("mode").and_then(Value::as_str) == Some(BY_ANGLE);
if let Some(distance) = number("distance") {
options.chamfer_distance = distance;
}
if let Some(angle) = number("angle") {
options.chamfer_angle_degrees = angle;
}
}
state.set_sketch_corner_options(options);
}
if out.exit_clicked {
state.sketch_set_tool(None);
}
}
/// The in-sketch CONTEXT actions — the selection-driven constraint palette
/// (applicable constraints + Fix/Unfix + ◐ construction + ∠ angle measure for
/// one selected angle constraint + 🧹 cleanup + 🗑 delete) — rendered through the SAME shared rail as the modeling context
/// bar ([`super::action_rail`]), so both look and behave identically. The
/// shell draws it into the top-right overlay, below the mode-exit card. No-op
/// unless a sketch is being edited AND something is selected.
pub fn context_card(&mut self, ui: &mut egui::Ui, state: &mut EngineState) {
self.ctx_hits.clear();
if !state.sketch_mode() || state.sketch_selection_count() == 0 {
return;
}
let actions = state.sketch_applicable_constraints();
let grounded = state.sketch_selection_all_grounded();
let construction = state.sketch_selection_all_construction();
let mut items: Vec<ActionItem> = Vec::new();
if state.sketch_selected_text().is_some() {
items.push(ActionItem::new("text", "Edit text", "Edit text contents and font"));
}
for action in &actions {
items.push(ActionItem::new(
format!("constraint:{}", action.symbol),
format!("{} {}", action.symbol, action.label),
action.label.clone(),
));
}
if let Some(all_grounded) = grounded {
let (label, tip) = if all_grounded {
("Unfix", "Remove the ground constraint")
} else {
("Fix", "Ground (fix) the selected points")
};
items.push(ActionItem::new("fix", label, tip));
}
if let Some(all_construction) = construction {
let tip = if all_construction {
"Convert to regular geometry"
} else {
"Convert to construction geometry"
};
items.push(ActionItem::new("construction", "◐ Construction", tip));
}
if !state.sketch_selected_point_ids().is_empty() {
let radius = state.sketch_corner_options().map_or(1.0, |o| o.radius);
items.push(ActionItem::new(
"fillet",
"Fillet",
format!(
"Round every selected corner (a point where two lines meet) at once with a radius {radius} tangent arc; \
the first corner you selected carries the one radius dimension and the others are held equal to it"
),
));
}
if state.sketch_selected_angle_constraint().is_some() {
items.push(ActionItem::new(
"angle",
"∠ Angle measure",
"Measure the angle the other way: step to the next sector between \
the two lines (167° becomes its 13° supplement) without moving \
the geometry",
));
}
items.push(ActionItem::new(
"cleanup",
"🧹 Clean",
"Remove unused points",
));
items.push(ActionItem::new(
"delete",
"🗑 Delete",
"Delete the selected entities (Del / Backspace)",
));
let subtitle = format!("{} selected", state.sketch_selection_count());
let clicked = if crate::viewport::touch::compact(ui.ctx()) {
action_rail(ui, Some("Sketch actions"), Some(&subtitle), &items, &mut self.ctx_hits)
} else {
egui::Frame::popup(ui.style())
.show(ui, |ui| {
action_rail(
ui,
Some("Sketch actions"),
Some(&subtitle),
&items,
&mut self.ctx_hits,
)
})
.inner
};
match clicked.as_deref() {
Some("text") => {
self.text_dialog = state.sketch_selected_text();
self.text_error = None;
}
Some(key) if key.starts_with("constraint:") => {
state.sketch_add_constraint(&key["constraint:".len()..]);
}
Some("fix") => {
state.sketch_toggle_ground();
}
Some("construction") => {
state.sketch_toggle_construction();
}
Some("angle") => {
state.sketch_cycle_angle_measure();
}
Some("fillet") => {
// Every selected corner at once; a refused point (all, or some of
// several) arms the fillet tool so its options card shows why (and
// the radius to change) in place of failing silently.
state.sketch_fillet_command();
}
Some("cleanup") => {
state.sketch_cleanup_unused_points();
}
Some("delete") => {
state.sketch_delete_selection();
}
_ => {}
}
}
pub fn show_text_dialog(&mut self, ctx: &egui::Context, state: &mut EngineState) {
self.text_hits.clear();
if !state.sketch_mode() { self.text_dialog = None; }
let Some((id, text, font)) = &mut self.text_dialog else { return; };
let mut open = true;
let mut apply = false;
let mut cancel = false;
let modal = egui::Modal::new(egui::Id::new("sketch-text-dialog")).show(ctx, |ui| {
ui.heading("Sketch text");
ui.label("Text");
self.text_hits.insert("text:contents".into(), ui.text_edit_singleline(text).rect);
ui.label("Font");
let fonts: Vec<(String, &str, &str)> = brep_render::sketch::text::FONTS.iter().map(|name| (name.to_string(), *name, *name)).collect();
crate::form::enum_dropdown(ui, "text:font", &fonts, font, None, Some(&mut self.text_hits));
if let Some(error) = &self.text_error { ui.colored_label(egui::Color32::RED, error); }
ui.horizontal(|ui| {
let response = ui.button("Apply");
apply = response.clicked();
self.text_hits.insert("text:apply".into(), response.rect);
let response = ui.button("Cancel");
cancel = response.clicked();
self.text_hits.insert("text:cancel".into(), response.rect);
});
});
if modal.should_close() { open = false; }
if apply {
match state.sketch_edit_text(id, text, font) {
Ok(()) => open = false,
Err(error) => self.text_error = Some(error),
}
}
if !open || cancel { self.text_dialog = None; self.text_error = None; }
}
/// The sketch-mode LEFT panel: Curves / Points / Constraints as selectable,
/// deletable, hover-synced rows (the port of the previous app's list sidebar).
/// Drawn only while editing a sketch; a click selects (Ctrl/Cmd adds), a row
/// hover highlights the entity on the canvas, and the ✕ deletes it.
pub fn show_entity_lists(&mut self, ui: &mut egui::Ui, state: &mut EngineState) {
self.list_hits.clear();
let hits = &mut self.list_hits;
egui::ScrollArea::vertical().show(ui, |ui| {
// The pane's VISIBLE region — the scroll viewport, not the layout
// extent. A long entity list runs past the bottom, where egui clips it
// and it stops being clickable even though its rect is still published;
// an automation host intersects against this to know when it must
// scroll a row into view first.
hits.insert("panel:clip".into(), ui.clip_rect());
ui.add_space(4.0);
// Snapshot the rows first (immutable borrow), then render with `&mut
// state` so per-row select/hover can call back into the engine.
// ISSUES first: the conflicting, then redundant, constraints, each row
// selecting / deleting its constraint like a Constraints row. Shown only
// while there are any; its rows publish as `issue:<id>` (`del:issue:<id>`)
// so they are told apart from the same constraint's Constraints row.
let issues = state.sketch_issue_rows();
if !issues.is_empty() {
let mut issue_hits: HashMap<String, egui::Rect> = HashMap::new();
entity_section(ui, &mut self.issues_collapsed, state, "Issues", "constraint", issues, &mut issue_hits);
for (key, rect) in issue_hits {
let key = if let Some(rest) = key.strip_prefix("del:constraint:") {
format!("del:issue:{rest}")
} else if let Some(rest) = key.strip_prefix("constraint:") {
format!("issue:{rest}")
} else {
key
};
if self.issues_reveal && key == "section:Issues" {
ui.scroll_to_rect(rect, Some(egui::Align::TOP));
}
hits.insert(key, rect);
}
}
self.issues_reveal = false;
let curves = state.sketch_geometry_rows();
let points = state.sketch_point_rows();
let constraints = state.sketch_constraint_rows();
entity_section(ui, &mut self.curves_collapsed, state, "Curves", "geometry", curves, hits);
entity_section(ui, &mut self.points_collapsed, state, "Points", "point", points, hits);
entity_section(
ui,
&mut self.constraints_collapsed,
state,
"Constraints",
"constraint",
constraints,
hits,
);
ui.add_space(6.0);
solver_settings_section(ui, &mut self.solver_collapsed, state);
});
}
/// The sketch-mode OVERLAY widget rects (egui points), published as
/// `__brepSketchHit`: the SKETCH ACTIONS card's constraint buttons plus its
/// Fix / Construction / Clean / Delete actions, each under the key
/// [`context_card`] returns when it is clicked.
///
/// The DRAW TOOLS are no longer here. They are workbench buttons now
/// ([`crate::workbench::sketch`]), so their rects are the toolbar's
/// `workbench:btn:sketch.tool.*` — one row, one hit-key family, and the
/// `workbench_button` command reaches them by id as well as by click.
///
/// The card floats in the top-right overlay and does not scroll, so it needs
/// no `panel:clip` — which is exactly why the entity list is [its own blob].
///
/// Empty out of sketch mode: the shell stops calling the card there, so last
/// frame's rects would otherwise be published forever as live widgets.
///
/// [`context_card`]: Self::context_card
/// [its own blob]: Self::list_hits_json
pub fn hits_json(&self, state: &EngineState) -> String {
if !state.sketch_mode() {
return "{}".to_string();
}
let mut hits = self.ctx_hits.clone();
hits.extend(self.text_hits.clone());
hits.extend(self.tool_hits.clone());
hits.extend(self.status_hits.clone());
crate::automation::hit_rects::hits_json(&hits)
}
/// The ENTITY LIST's widget rects (egui points), published as
/// `__brepSketchListHit`: one key per row (`geometry:` / `point:` /
/// `constraint:`, by entity id), its ✕ (`del:kind:id`), each section header, and
/// the pane's `panel:clip`. Empty out of sketch mode, for the same reason as
/// [`hits_json`].
///
/// [`hits_json`]: Self::hits_json
pub fn list_hits_json(&self, state: &EngineState) -> String {
if !state.sketch_mode() {
return "{}".to_string();
}
crate::automation::hit_rects::hits_json(&self.list_hits)
}
/// Verification mirror (wasm): the live sketch-mode state + the active session's
/// solve summary, so the headed verifier can assert enter/exit (screenshots read
/// black headless).
pub fn published_json(&self, state: &EngineState) -> String {
let session = state.sketch_edit_session();
// S5 editable dimensions: the per-constraint labels (id/value/valueExpr/mode)
// + a count, so the headless verifier can assert dims render + edit.
let dim_labels: Vec<serde_json::Value> =
serde_json::from_str(&state.sketch_dimension_labels_json()).unwrap_or_default();
let dimensions: Vec<serde_json::Value> = dim_labels
.iter()
.map(|l| {
serde_json::json!({
"id": l["id"],
"text": l["text"],
"value": l["value"],
"valueExpr": l["valueExpr"],
"mode": l["mode"],
})
})
.collect();
serde_json::json!({
"sketchMode": state.sketch_mode(),
"featureId": state.sketch_edit_feature_id(),
"dof": session.map(|s| s.diagnostics.dof),
"status": session.map(|s| s.diagnostics.status.clone()),
"conflicting": session.map(|s| s.diagnostics.conflicting),
// WHICH constraints conflict (the headless verifier asserts the exact
// set, not just the flag).
"conflictingConstraints": session
.map(|s| s.diagnostics.conflicting_constraints.clone())
.unwrap_or_default(),
"points": session.map(|s| s.doc.points.len()),
"geometries": session.map(|s| s.doc.geometries.len()),
"constraints": session.map(|s| s.doc.constraints.len()),
// S2 picking state (the headless verifier asserts hover/selection).
"hovered": session.and_then(|s| s.selection.hovered.clone()),
"selectionCount": state.sketch_selection_count(),
// The selected refs themselves ({kind, id}, selection order).
"selection": session.map(|s| s.selection.items.clone()).unwrap_or_default(),
// Constraint selection (select + delete): how many selected refs are
// constraints, so the verifier can assert a constraint pick + delete.
"selectedConstraintCount": state.sketch_selected_constraint_count(),
// S3a draw-tool state (the verifier asserts tool selection + that draws
// landed): the active tool + the doc's point/geometry counts + the
// in-progress click buffer length.
"tool": state.sketch_active_tool(),
"cameraLocked": state.sketch_camera_locked(),
"pointCount": session.map(|s| s.doc.points.len()),
"geometryCount": session.map(|s| s.doc.geometries.len()),
"pendingLen": state.sketch_pending_len(),
// S4 constraint palette: the active doc's constraint count + the ordered
// list of applicable-constraint symbols for the live selection (the
// headless verifier asserts the palette + that additions landed).
"constraintCount": state.sketch_constraint_count(),
"applicableConstraints": state
.sketch_applicable_constraints()
.iter()
.map(|a| a.symbol.clone())
.collect::<Vec<_>>(),
// Precise freedom: the redundant constraints (the conflicting ones are
// above), the Issues list rows in order, each movable point's free
// directions, and the hovered entity's readout.
"redundantConstraints": session
.map(|s| s.diagnostics.redundant_constraints.clone())
.unwrap_or_default(),
"issues": state
.sketch_issue_rows()
.iter()
.map(|r| serde_json::json!({ "id": r.id, "label": r.label }))
.collect::<Vec<_>>(),
"pointFreedom": session.map(|s| serde_json::to_value(&s.diagnostics.point_freedom).unwrap_or_default()),
"hoverFreedom": state.sketch_hover_freedom_label(),
// The geometric-constraint glyphs as drawn (id, pixel centre and size,
// saved stand-off), so the verifier can drag one and check its size.
"glyphs": serde_json::from_str::<serde_json::Value>(&state.sketch_glyphs_json())
.unwrap_or_default(),
// S5 editable dimensions.
"dimensionCount": dimensions.len(),
"dimensions": dimensions,
// S6a per-session sketch undo/redo (the verifier asserts a draw is
// undoable and that redo is available after an undo).
"canUndo": state.sketch_can_undo(),
"canRedo": state.sketch_can_redo(),
// S6b-2 pickEdges: the number of linked external-reference edges (the
// verifier asserts a link landed and round-trips a commit + re-enter).
"externalRefCount": state.sketch_external_ref_count(),
// S6b-3 handdraw: the live freehand stroke sample count (the verifier
// asserts a stroke captures while dragging, then clears + emits on end).
"handdrawPoints": state.sketch_handdraw_len(),
// Fillet / chamfer: the tools' options and why the last corner click
// changed nothing (null after one that did).
"cornerOptions": state.sketch_corner_options().map(|o| serde_json::json!({
"radius": o.radius,
"chamferMode": if o.chamfer_by_angle { "Distance + angle" } else { "Equal distance" },
"chamferDistance": o.chamfer_distance,
"chamferAngle": o.chamfer_angle_degrees,
})),
"cornerMessage": state.sketch_corner_message(),
})
.to_string()
}
}
/// The one conflict red every sketch surface uses: the editable
/// `sketchConflictColor` display setting, the same entry the engine paints the
/// glyphs, leaders and dimension text with.
fn conflict_color(state: &EngineState) -> egui::Color32 {
let c = state.settings.sketch_colors().conflict;
egui::Color32::from_rgb((c >> 16) as u8, (c >> 8) as u8, c as u8)
}
/// The readout's state (`conflicting` / `over` / `under` / `full`) and wording, as
/// the status bar shows them; the automation `sketch.freedom` answers the same pair.
pub(crate) fn readout(diag: &brep_render::sketch::SketchDiagnostics) -> (&'static str, String) {
if diag.conflicting {
// Name HOW MANY constraints the solver implicated, so the readout and the
// red rows/glyphs are visibly the same statement. The solver never raises
// the flag without naming something, so the bare label is only a fallback
// for a diagnostics blob that predates that guarantee.
let n = diag.conflicting_constraints.len();
let label = if n > 0 { format!("Conflicting constraints ({n})") } else { "Conflicting constraints".to_string() };
("conflicting", label)
} else if diag.status == "over" || diag.redundant > 0 {
let label = if diag.dof > 0 {
format!("Over-constrained ({} redundant, {} DOF)", diag.redundant, diag.dof)
} else {
format!("Over-constrained ({} redundant)", diag.redundant)
};
("over", label)
} else if diag.status == "under" || diag.dof > 0 {
("under", format!("Under-constrained — {} DOF", diag.dof))
} else {
("full", "Fully constrained".to_string())
}
}
/// The display-setting colours the status readout shares with the canvas, so the
/// dot says "fully constrained" in the colour fully constrained geometry is drawn in
/// (and "under-constrained" in the movable colour), whatever the user sets them to.
#[derive(Clone, Copy)]
pub(crate) struct StatusColors {
pub conflict: egui::Color32,
pub movable: egui::Color32,
pub locked: egui::Color32,
}
pub(crate) fn status_colors(state: &EngineState) -> StatusColors {
let c = state.settings.sketch_colors();
let rgb = |v: u32| egui::Color32::from_rgb((v >> 16) as u8, (v >> 8) as u8, v as u8);
StatusColors { conflict: rgb(c.conflict), movable: rgb(c.movable), locked: rgb(c.locked) }
}
/// The DOF status readout — a colored dot + label, ported from the previous
/// sketcher's DOF readout. Conflict red = conflicting, yellow = over-constrained,
/// the movable colour = under-constrained (`N` DOF), the locked colour = fully
/// constrained: each the colour the canvas draws that state's entities in.
fn dof_readout(
ui: &mut egui::Ui,
diag: &brep_render::sketch::SketchDiagnostics,
colors: StatusColors,
) -> egui::Response {
let (state, label) = readout(diag);
let color = match state {
"conflicting" => colors.conflict,
"over" => egui::Color32::from_rgb(0xff, 0xcf, 0x5c),
"under" => colors.movable,
_ => colors.locked,
};
let row = ui.horizontal(|ui| {
let (rect, _) = ui.allocate_exact_size(egui::vec2(12.0, 12.0), egui::Sense::hover());
ui.painter().circle_filled(rect.center(), 5.0, color);
ui.label(egui::RichText::new(label).strong());
});
// The dot and its label are one button: a click opens the Issues list (which
// names the conflicting and redundant constraints), a hover says so.
ui.interact(row.response.rect, ui.id().with("sketch-dof-readout"), egui::Sense::click())
.on_hover_cursor(egui::CursorIcon::PointingHand)
.on_hover_text("Show which constraints conflict or repeat (Issues list)")
}
/// One collapsible entity-list section, rendered with the shared `tree` widget so
/// it matches the Scene tree. A branch header (title + count) over leaf rows; each
/// leaf is a selectable label (Ctrl/Cmd adds), a row hover highlights the entity on
/// the canvas, and a trailing ✕ deletes it via the existing selection-delete path.
fn entity_section(
ui: &mut egui::Ui,
collapsed: &mut bool,
state: &mut EngineState,
title: &str,
kind: &'static str,
rows: Vec<SketchEntityRow>,
hits: &mut HashMap<String, egui::Rect>,
) {
let open = !*collapsed;
let resp = tree::node(ui, TreeRow::branch(&[], true, open, title), |ui| {
ui.add_space(6.0);
ui.label(egui::RichText::new(format!("{}", rows.len())).weak());
});
hits.insert(format!("section:{title}"), resp.label.rect);
if resp.toggled || resp.clicked() {
*collapsed = !*collapsed;
}
if !open {
return;
}
let base = tree::child_guides(&[], true);
if rows.is_empty() {
tree::node(ui, TreeRow::leaf(&base, true, "—"), |_| {});
return;
}
let n = rows.len();
// Read the palette ONCE, before the loop borrows `state` mutably per row.
let conflict = conflict_color(state);
let mut to_delete: Option<serde_json::Value> = None;
for (i, row) in rows.iter().enumerate() {
let last = i + 1 == n;
let mut delete_clicked = false;
let mut del_rect = egui::Rect::NOTHING;
// A CONFLICTING constraint's row is painted in the same red as the status
// dot and its canvas glyph, so the list answers "which ones?" directly.
let tint = row.conflicting.then(|| conflict);
let resp = tree::node(
ui,
TreeRow::leaf(&base, last, row.label.as_str())
.selected(row.selected)
.tint(tint),
|ui| {
let del = crate::icon_text::icon_button(ui, "✕").small()
.min_size(crate::viewport::touch::target_size(ui.ctx(), egui::Vec2::ZERO));
let resp = ui.add(del).on_hover_text("Delete");
del_rect = resp.rect;
if resp.clicked() {
delete_clicked = true;
}
},
);
// Keyed by the entity's own id, not its position or its label: a row's
// index moves when a sibling is deleted and its label is display text, but
// the id is what select/hover/delete are addressed by.
let key = id_key(&row.id);
let hit = if crate::viewport::touch::enabled(ui.ctx()) {
egui::Rect::from_min_max(
egui::pos2(resp.label.rect.left(), resp.row_rect.top()),
egui::pos2(del_rect.left() - 4.0, resp.row_rect.bottom()),
)
} else { resp.label.rect };
hits.insert(format!("{kind}:{key}"), hit);
hits.insert(format!("del:{kind}:{key}"), del_rect);
if delete_clicked {
to_delete = Some(row.id.clone());
} else if resp.clicked() {
let additive = crate::select_mods::primary_in(ui.ctx());
state.sketch_select_entity(kind, row.id.clone(), additive);
}
if resp.label.hovered() {
state.sketch_hover_entity(kind, row.id.clone());
}
// A copied edge's note ("copied from <part>, not linked") in full.
if let Some((_, note)) = row.label.split_once(" \u{2014} ") {
resp.label.clone().on_hover_text(note);
}
}
// Delete last so it can't invalidate the rows we are still iterating this frame.
if let Some(id) = to_delete {
// Only the clicked row — never the rest of a multi-selection.
state.sketch_delete_entity(kind, id);
}
}
/// The Solver Settings section (the port of the previous app's "Solver Settings" sidebar): a
/// couple of the `SolveSketchRequest` knobs (iteration cap + optional tolerance
/// override), plus Reset. Any change re-solves the sketch immediately. Defaults
/// reproduce the historical solve, so an untouched sketch is unaffected.
fn solver_settings_section(ui: &mut egui::Ui, collapsed: &mut bool, state: &mut EngineState) {
let Some(mut settings) = state.sketch_solver_settings() else {
return;
};
let open = !*collapsed;
let resp = tree::node(ui, TreeRow::branch(&[], true, open, "Solver Settings"), |_| {});
if resp.toggled || resp.clicked() {
*collapsed = !*collapsed;
}
if !open {
return;
}
let before = settings.clone();
egui::Frame::group(ui.style()).show(ui, |ui| {
// Iteration cap (always set; default 1000).
let mut iters = settings.iterations.unwrap_or(1000);
ui.horizontal(|ui| {
ui.label("Max iterations");
if ui
.add(egui::DragValue::new(&mut iters).range(50..=20_000).speed(10.0))
.changed()
{
settings.iterations = Some(iters);
}
});
// Optional convergence tolerance override.
let mut tol_on = settings.tolerance.is_some();
ui.horizontal(|ui| {
if ui.checkbox(&mut tol_on, "Override tolerance").changed() {
settings.tolerance = tol_on.then_some(1e-6);
}
if let Some(mut tol) = settings.tolerance {
if ui
.add(
egui::DragValue::new(&mut tol)
.range(1e-9..=1e-1)
.speed(1e-6)
.custom_formatter(|v, _| format!("{v:.1e}")),
)
.changed()
{
settings.tolerance = Some(tol);
}
}
});
if ui.button("Reset to defaults").clicked() {
settings = brep_render::sketch::SketchSolverSettings::default();
}
});
if settings != before {
state.sketch_set_solver_settings(settings);
}
}
/// The hit keys these two surfaces publish (see `automation::hit_keys`). They are
/// separate PANELS because they are separate blobs: `sketch` is the floating
/// actions card, `sketchlist` the scrolling entity list that owns a `panel:clip`.
pub static HIT_KEYS: &[HitKeyDoc] = &[
HitKeyDoc { panel: "sketch", prefix: "tool:", meaning: "the armed fillet or chamfer tool's options form (tool:field:radius, tool:field:mode with entries tool:field:mode#Equal distance / tool:field:mode#Distance + angle, tool:field:distance, tool:field:angle, tool:form:return puts the tool down, tool:form:error while the last click was refused)", command: None },
HitKeyDoc { panel: "sketch", prefix: "text", meaning: "edit selected text; text:contents, text:font (its entries text:font#<name> while open), text:apply and text:cancel address the dialog", command: None },
HitKeyDoc { panel: "sketch", prefix: "constraint:", meaning: "apply the offered sketch constraint to the selection (constraint:glyph, e.g. constraint:⌒)", command: None },
HitKeyDoc { panel: "sketch", prefix: "fix", meaning: "ground the selected points, or unground them when all are grounded", command: None },
HitKeyDoc { panel: "sketch", prefix: "construction", meaning: "flip the selection between construction and regular geometry", command: None },
HitKeyDoc { panel: "sketch", prefix: "angle", meaning: "with one ∠ constraint selected, measure the angle the next way round (its supplement in the adjacent sector; the value flips to 180 − value, the geometry stays put)", command: None },
HitKeyDoc { panel: "sketch", prefix: "fillet", meaning: "with points selected, round every selected corner (two lines meeting) at once with the fillet tool's radius in one undo step: one radius dimension on the first selected corner's arc, the others equal to it (⊜); a refusal arms the fillet tool showing why. The toolbar's sketch.tool.fillet does the same while points are selected", command: None },
HitKeyDoc { panel: "sketch", prefix: "cleanup", meaning: "remove points no geometry or constraint uses", command: None },
HitKeyDoc { panel: "sketch", prefix: "delete", meaning: "delete the selected sketch entities", command: None },
HitKeyDoc { panel: "sketch", prefix: "issues", meaning: "the constraint-status readout (DOF / fully constrained / redundant / conflicting): opens the entity list's Issues section and scrolls it into view", command: None },
HitKeyDoc { panel: "sketchlist", prefix: "section:", meaning: "collapse or expand an entity-list section (section:Issues while a constraint is redundant or conflicting / section:Curves / section:Points / section:Constraints)", command: None },
HitKeyDoc { panel: "sketchlist", prefix: "issue:", meaning: "select the redundant or conflicting constraint an Issues row names (issue:<constraint id>; its delete is del:issue:<id>)", command: None },
HitKeyDoc { panel: "sketchlist", prefix: "geometry:", meaning: "select a curve row by entity id; hold ctrl (modifiers_set) to add to the selection", command: None },
HitKeyDoc { panel: "sketchlist", prefix: "point:", meaning: "select a point row by entity id; hold ctrl to add to the selection", command: None },
HitKeyDoc { panel: "sketchlist", prefix: "constraint:", meaning: "select a constraint row by entity id; hold ctrl to add to the selection", command: None },
HitKeyDoc { panel: "sketchlist", prefix: "del:", meaning: "delete one entity-list row (del:kind:id)", command: None },
HitKeyDoc { panel: "sketchlist", prefix: "panel:clip", meaning: "the visible region of the pane", command: None },
];