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
use super::*;
/// The egui text color for CONSTRAINT annotations (the dimension VALUE labels), read
/// from the engine's single source of truth — the display-settings sketch palette
/// ([`brep_render::style::RenderSettings::sketch_colors`]) — so the label text follows
/// the same (editable) color as the engine-drawn leaders + geometric glyphs.
fn constraint_text_color(settings: &brep_render::style::RenderSettings) -> egui::Color32 {
let c = settings.sketch_colors().constraint;
egui::Color32::from_rgb((c >> 16) as u8, (c >> 8) as u8, c as u8)
}
/// The width (egui points) to give a dimension value-edit `TextEdit` so its current
/// `text` never wraps: the measured no-wrap width of the string in `style`'s font
/// (same `layout_no_wrap` path the action rail uses), plus a little padding for the
/// caret + inner margin, floored so an emptied box (select-all + delete) stays a
/// usable size. Sizing only — value / color / placement are unchanged.
fn text_edit_width(ui: &egui::Ui, text: &str, style: egui::TextStyle) -> f32 {
let font = style.resolve(ui.style());
let measured = ui.ctx().fonts_mut(|f| {
f.layout_no_wrap(text.to_owned(), font.clone(), egui::Color32::PLACEHOLDER)
.size()
.x
});
(measured + 12.0).max(24.0)
}
impl Viewport {
/// Draw the editable dimension labels (S5) over the viewport while in sketch
/// mode. For each dimensional constraint the engine reports a label anchor in
/// world space + its display text; we project it to screen and draw a small
/// clickable value. Clicking opens an inline single-line `TextEdit` (seeded from
/// the number, or the `valueExpr` when set); Enter applies via
/// [`EngineState::sketch_set_dimension_value`], Esc cancels. Dragging a label
/// repositions it via [`EngineState::sketch_dimension_drag_to`]. The labels ride
/// in `Order::Middle` areas so they float over the 3D and take pointer priority
/// over the viewport's own select/place handling.
pub(super) fn draw_dimension_labels(
&mut self,
ctx: &egui::Context,
rect: egui::Rect,
state: &mut EngineState,
) {
if !state.sketch_mode() {
self.editing_dim = None;
return;
}
// The dimension labels (id/text/world/value/valueExpr/mode) from the engine.
let labels: Vec<serde_json::Value> =
serde_json::from_str(&state.sketch_dimension_labels_json()).unwrap_or_default();
// Drop an open editor whose constraint no longer has a label (e.g. deleted).
if let Some((id, _)) = self.editing_dim.as_ref() {
let key = id.to_string();
if !labels.iter().any(|l| l["id"].to_string() == key) {
self.editing_dim = None;
}
}
if labels.is_empty() {
return;
}
// Project every label anchor world→screen in one shot.
let worlds: Vec<[f64; 3]> = labels
.iter()
.map(|l| {
let w = &l["world"];
[
w[0].as_f64().unwrap_or(0.0),
w[1].as_f64().unwrap_or(0.0),
w[2].as_f64().unwrap_or(0.0),
]
})
.collect();
let screens: Vec<[f64; 4]> = serde_json::to_string(&worlds)
.ok()
.and_then(|s| state.world_to_screen_json(&s).ok())
.and_then(|s| serde_json::from_str(&s).ok())
.unwrap_or_default();
if screens.len() != labels.len() {
return;
}
// Editing state pulled out so the draw closures can mutate the buffer without
// borrowing `self` twice; written back after the loop.
let fresh = self.dim_edit_fresh;
self.dim_edit_fresh = false;
let mut editing = self.editing_dim.take();
let editing_key = editing.as_ref().map(|(id, _)| id.to_string());
// The label text color from the live settings (read BEFORE the closures, which
// must never touch `state`) — follows the editable sketch constraint color.
let dim_text_color = constraint_text_color(&state.settings);
// Deferred engine mutations (never call `state` inside the area closures).
let mut start_edit: Option<serde_json::Value> = None;
let mut apply: bool = false;
let mut cancel: bool = false;
let mut drag_to: Option<(serde_json::Value, f64, f64)> = None;
// A label drag ended this frame → reset the sketch undo's per-drag guard (S6a)
// so the whole drag was one undo step and the next drag starts a fresh one.
let mut drag_ended = false;
for (i, label) in labels.iter().enumerate() {
let scr = screens[i];
if scr[3] < 0.5 {
continue; // behind the eye plane
}
let cid = label["id"].clone();
let cid_key = cid.to_string();
let pos = egui::pos2(rect.min.x + scr[0] as f32, rect.min.y + scr[1] as f32);
let is_editing = editing_key.as_deref() == Some(cid_key.as_str());
let area_id = egui::Id::new(("brep-dim-label", cid_key.clone()));
egui::Area::new(area_id)
.order(egui::Order::Middle)
.fixed_pos(pos)
.pivot(egui::Align2::CENTER_CENTER)
.show(ctx, |ui| {
egui::Frame::popup(ui.style())
.inner_margin(egui::Margin::symmetric(4, 2))
.show(ui, |ui| {
if is_editing {
let buf = &mut editing.as_mut().expect("editing buffer").1;
// Size the box to its text so the value never wraps.
let width =
text_edit_width(ui, buf.as_str(), egui::TextStyle::Monospace);
let resp = ui.add(
egui::TextEdit::singleline(buf)
.desired_width(width)
.font(egui::TextStyle::Monospace),
);
if fresh {
resp.request_focus();
}
let enter =
ui.input(|i| i.key_pressed(egui::Key::Enter));
if resp.lost_focus() {
if enter {
apply = true;
} else if !fresh {
cancel = true;
}
}
if ui.input(|i| i.key_pressed(egui::Key::Escape)) {
cancel = true;
}
} else {
let text = label["text"].as_str().unwrap_or("").to_string();
let resp = ui.add(
egui::Button::new(
egui::RichText::new(text)
.monospace()
.color(dim_text_color),
)
// Never wrap/clip the chip — extend to fit its text.
.wrap_mode(egui::TextWrapMode::Extend)
.sense(egui::Sense::click_and_drag()),
);
if resp.clicked() {
start_edit = Some(cid.clone());
}
if resp.dragged() {
if let Some(p) = resp.interact_pointer_pos() {
drag_to = Some((
cid.clone(),
(p.x - rect.min.x) as f64,
(p.y - rect.min.y) as f64,
));
}
}
if resp.drag_stopped() {
drag_ended = true;
}
}
});
});
}
// --- apply deferred actions (state is free to borrow again here) ---------
if apply {
if let Some((id, text)) = editing.take() {
state.sketch_set_dimension_value(&id, &text);
}
self.editing_dim = None;
} else if cancel {
self.editing_dim = None;
} else {
// Keep the (possibly edited) buffer for the next frame.
self.editing_dim = editing;
}
if let Some((id, lx, ly)) = drag_to {
state.sketch_dimension_drag_to(&id, lx, ly);
}
if drag_ended {
state.sketch_dimension_drag_end();
}
if let Some(id) = start_edit {
// Seed the field from the display value (diameter shows the diameter),
// preferring the expression when one is set.
let seed: serde_json::Value =
serde_json::from_str(&state.sketch_dimension_value_json(&id)).unwrap_or_default();
let text = seed
.get("valueExpr")
.and_then(|v| v.as_str())
.map(str::to_string)
.or_else(|| {
seed.get("value")
.and_then(|v| v.as_f64())
.map(|n| format!("{n}"))
})
.unwrap_or_default();
self.editing_dim = Some((id, text));
self.dim_edit_fresh = true;
}
// Keep animating while a field is open (focus / caret).
if self.editing_dim.is_some() {
ctx.request_repaint();
}
}
/// Draw the editable FEATURE-dimension labels (FD-1) over the viewport while
/// the ◎ is in DIMENSION mode. For each linear param dim the engine reports a
/// leader midpoint (world) + its value; we project it to screen and draw a
/// small `"{label} {value}"` chip. Clicking opens an inline `TextEdit` seeded
/// from the value; Enter applies via [`EngineState::feature_dimension_set_value`]
/// (numeric literal OR live expression), Esc cancels. Dragging the chip drives
/// [`EngineState::feature_dimension_drag`] (the dim resizes the param live).
/// The chips ride `Order::Middle`, taking pointer priority over the viewport's
/// select/orbit — so a drag that starts on a handle never orbits the camera.
pub(super) fn draw_feature_dimension_labels(
&mut self,
ctx: &egui::Context,
rect: egui::Rect,
state: &mut EngineState,
) {
if state.gizmo_mode() != "dimension" {
self.editing_feature_dim = None;
return;
}
let feature = state.dimension_armed_feature();
if feature.is_empty() {
self.editing_feature_dim = None;
return;
}
let annotations: Vec<serde_json::Value> =
serde_json::from_str(&state.feature_dimension_annotations_json(&feature))
.unwrap_or_default();
// Drop an open editor whose field no longer has an annotation.
if let Some((_, field, _)) = self.editing_feature_dim.as_ref() {
let key = field.clone();
if !annotations
.iter()
.any(|a| a["fieldKey"].as_str() == Some(key.as_str()))
{
self.editing_feature_dim = None;
}
}
if annotations.is_empty() {
return;
}
// Project every leader midpoint world→screen in one shot.
let worlds: Vec<[f64; 3]> = annotations
.iter()
.map(|a| {
let m = &a["mid"];
[
m[0].as_f64().unwrap_or(0.0),
m[1].as_f64().unwrap_or(0.0),
m[2].as_f64().unwrap_or(0.0),
]
})
.collect();
let screens: Vec<[f64; 4]> = serde_json::to_string(&worlds)
.ok()
.and_then(|s| state.world_to_screen_json(&s).ok())
.and_then(|s| serde_json::from_str(&s).ok())
.unwrap_or_default();
if screens.len() != annotations.len() {
return;
}
let fresh = self.feature_dim_edit_fresh;
self.feature_dim_edit_fresh = false;
let mut editing = self.editing_feature_dim.take();
let editing_key = editing.as_ref().map(|(_, field, _)| field.clone());
// Deferred engine mutations (never touch `state` inside the area closures).
let mut start_edit: Option<(String, String)> = None; // (field, seed)
let mut apply = false;
let mut cancel = false;
let mut drag_to: Option<(String, f64, f64)> = None;
for (i, annotation) in annotations.iter().enumerate() {
let scr = screens[i];
if scr[3] < 0.5 {
continue; // behind the eye plane
}
let Some(field) = annotation["fieldKey"].as_str() else {
continue;
};
let field = field.to_string();
let value = annotation["value"].as_f64().unwrap_or(0.0);
let prefix = annotation["label"].as_str().unwrap_or("").to_string();
// An angular dim (torus `arc`, revolve `angle`) shows its value in
// DEGREES with a trailing `°`; the edit seed stays the bare number.
let is_angular = annotation["kind"].as_str() == Some("angular");
let pos = egui::pos2(rect.min.x + scr[0] as f32, rect.min.y + scr[1] as f32);
let is_editing = editing_key.as_deref() == Some(field.as_str());
let area_id = egui::Id::new(("brep-feature-dim", feature.clone(), field.clone()));
egui::Area::new(area_id)
.order(egui::Order::Middle)
.fixed_pos(pos)
.pivot(egui::Align2::CENTER_CENTER)
.show(ctx, |ui| {
// Dark rounded chip with a thin orange border + orange
// monospace text (matches the reference dimension image).
let orange = egui::Color32::from_rgb(245, 166, 35);
let dark = egui::Color32::from_rgb(20, 20, 20);
egui::Frame::new()
.fill(dark)
.stroke(egui::Stroke::new(1.0, orange))
.corner_radius(egui::CornerRadius::same(6))
.inner_margin(egui::Margin::symmetric(6, 3))
.show(ui, |ui| {
if is_editing {
let buf = &mut editing.as_mut().expect("editing buffer").2;
// Size the box to its text so the value never wraps.
let width =
text_edit_width(ui, buf.as_str(), egui::TextStyle::Monospace);
let resp = ui.add(
egui::TextEdit::singleline(buf)
.desired_width(width)
.font(egui::TextStyle::Monospace)
.text_color(orange)
.frame(egui::Frame::NONE),
);
if fresh {
resp.request_focus();
}
let enter = ui.input(|i| i.key_pressed(egui::Key::Enter));
if resp.lost_focus() {
if enter {
apply = true;
} else if !fresh {
cancel = true;
}
}
if ui.input(|i| i.key_pressed(egui::Key::Escape)) {
cancel = true;
}
} else {
let text = if is_angular {
format!("{prefix} {}\u{00b0}", fmt_dim_value(value))
} else {
format!("{prefix} {}", fmt_dim_value(value))
};
let resp = ui.add(
egui::Button::new(
egui::RichText::new(text).monospace().color(orange),
)
.frame(false)
// Never wrap/clip the chip — extend to fit its text.
.wrap_mode(egui::TextWrapMode::Extend)
.sense(egui::Sense::click_and_drag()),
);
if resp.clicked() {
start_edit = Some((field.clone(), fmt_dim_value(value)));
}
if resp.dragged() {
if let Some(p) = resp.interact_pointer_pos() {
drag_to = Some((
field.clone(),
(p.x - rect.min.x) as f64,
(p.y - rect.min.y) as f64,
));
}
}
}
});
});
}
// --- apply deferred actions (state free to borrow again) -----------------
if apply {
if let Some((feat, field, text)) = editing.take() {
state.feature_dimension_set_value(&feat, &field, &text);
}
self.editing_feature_dim = None;
} else if cancel {
self.editing_feature_dim = None;
} else {
self.editing_feature_dim = editing;
}
if let Some((field, lx, ly)) = drag_to {
state.feature_dimension_drag(&feature, &field, lx, ly);
}
if let Some((field, seed)) = start_edit {
self.editing_feature_dim = Some((feature.clone(), field, seed));
self.feature_dim_edit_fresh = true;
}
if self.editing_feature_dim.is_some() {
ctx.request_repaint();
}
}
/// Draw the transform gizmo's axis-end labels (`XC` red, `YC` green, `ZC`
/// blue) at each cone tip while the ◎ is in TRANSFORM mode. These are pure
/// display text (non-interactable, so they never intercept a gizmo drag).
pub(super) fn draw_transform_axis_labels(
&mut self,
ctx: &egui::Context,
rect: egui::Rect,
state: &mut EngineState,
) {
if state.gizmo_mode() != "transform" {
return;
}
let labels: Vec<serde_json::Value> =
serde_json::from_str(&state.transform_axis_labels_json()).unwrap_or_default();
if labels.is_empty() {
return;
}
// Project every label anchor world→screen in one shot.
let worlds: Vec<[f64; 3]> = labels
.iter()
.map(|l| {
let w = &l["world"];
[
w[0].as_f64().unwrap_or(0.0),
w[1].as_f64().unwrap_or(0.0),
w[2].as_f64().unwrap_or(0.0),
]
})
.collect();
let screens: Vec<[f64; 4]> = serde_json::to_string(&worlds)
.ok()
.and_then(|s| state.world_to_screen_json(&s).ok())
.and_then(|s| serde_json::from_str(&s).ok())
.unwrap_or_default();
if screens.len() != labels.len() {
return;
}
for (i, label) in labels.iter().enumerate() {
let scr = screens[i];
if scr[3] < 0.5 {
continue; // behind the eye plane
}
let text = label["text"].as_str().unwrap_or("").to_string();
let rgb = &label["rgb"];
let color = egui::Color32::from_rgb(
(rgb[0].as_f64().unwrap_or(1.0) * 255.0).round() as u8,
(rgb[1].as_f64().unwrap_or(1.0) * 255.0).round() as u8,
(rgb[2].as_f64().unwrap_or(1.0) * 255.0).round() as u8,
);
let pos = egui::pos2(rect.min.x + scr[0] as f32, rect.min.y + scr[1] as f32);
let area_id = egui::Id::new(("brep-transform-axis", i));
egui::Area::new(area_id)
.order(egui::Order::Middle)
.interactable(false)
.fixed_pos(pos)
.pivot(egui::Align2::CENTER_CENTER)
.show(ctx, |ui| {
ui.label(egui::RichText::new(text).monospace().strong().color(color));
});
}
}
}
/// A compact display string for a dimension value: up to 4 decimals, trailing
/// zeros (and a bare trailing dot) trimmed — so `10.0` shows as `10`, `12.5` as
/// `12.5`, `14.0000` as `14`.
fn fmt_dim_value(value: f64) -> String {
let s = format!("{value:.4}");
let trimmed = s.trim_end_matches('0').trim_end_matches('.');
if trimmed.is_empty() || trimmed == "-" {
"0".to_string()
} else {
trimmed.to_string()
}
}
#[cfg(test)]
mod tests {
use super::*;
/// The dimension value-edit box is sized to its text: a longer value string yields
/// a wider box (so the text never wraps), and an emptied box stays a usable floor.
/// Exercised through a headless egui frame (font layout is CPU-only) — the same
/// `run_ui` harness the toolbar test uses.
#[test]
fn text_edit_width_grows_with_text_and_floors_when_empty() {
let ctx = egui::Context::default();
let (mut empty_w, mut short_w, mut long_w) = (0.0f32, 0.0f32, 0.0f32);
let _ = ctx.run_ui(egui::RawInput::default(), |ui| {
empty_w = text_edit_width(ui, "", egui::TextStyle::Monospace);
short_w = text_edit_width(ui, "20", egui::TextStyle::Monospace);
long_w = text_edit_width(ui, "1234.5678", egui::TextStyle::Monospace);
});
// A longer value needs a wider box so it never wraps.
assert!(long_w > short_w, "long {long_w} must exceed short {short_w}");
assert!(short_w >= empty_w, "text is at least as wide as the empty box");
// An emptied box (select-all + delete) keeps the ~24px usable floor.
assert!(empty_w >= 24.0, "empty box floored, got {empty_w}");
}
}