BREP_app 0.35.0

The next.BREP.io CAD application on the Rust B-rep kernel: an eframe (egui + wgpu) host that draws the brep-render 3D engine into an egui frame, native + wasm from one codebase.
Documentation
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
//! Text and number inputs: a `bg.input` field with a 1 px border that turns
//! accent on focus, an error state that keeps the user's text, a search
//! variant, and numbers with the unit inside the field.
use super::{paint, Show};
use crate::theme::{radius, space, Text, Theme, BORDER};
use eframe::egui::{self, Rect, Stroke, Vec2};

/// What an input drew.
pub struct InputOutput {
    /// The text edit's own response (focus, changed, lost_focus).
    pub response: egui::Response,
    /// The whole framed field: the rect a hit key publishes.
    pub rect: Rect,
    /// The clear × was pressed (search fields).
    pub cleared: bool,
}

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Lead {
    None,
    Search,
}

/// A single-line text field.
#[must_use = "an input does nothing until `show` is called"]
pub struct TextInput<'a> {
    text: &'a mut String,
    placeholder: &'a str,
    error: Option<&'a str>,
    width: Option<f32>,
    enabled: bool,
    lead: Lead,
    suffix: Option<&'a str>,
    right_aligned: bool,
    id: Option<egui::Id>,
    show: Show,
}

/// A text field. `text_input(&mut name).placeholder("Name").show(ui)`.
pub fn text_input(text: &mut String) -> TextInput<'_> {
    TextInput { text, placeholder: "", error: None, width: None, enabled: true, lead: Lead::None, suffix: None, right_aligned: false, id: None, show: Show::Live }
}

/// A search field: a leading magnifier, and a clear × when not empty.
pub fn search_input(text: &mut String) -> TextInput<'_> {
    let mut input = text_input(text);
    input.lead = Lead::Search;
    input.placeholder = "Search";
    input
}

impl<'a> TextInput<'a> {
    pub fn placeholder(mut self, text: &'a str) -> Self {
        self.placeholder = text;
        self
    }
    /// A `danger` border and the message below in caption size.
    pub fn error(mut self, message: Option<&'a str>) -> Self {
        self.error = message;
        self
    }
    pub fn width(mut self, width: f32) -> Self {
        self.width = Some(width);
        self
    }
    pub fn enabled(mut self, enabled: bool) -> Self {
        self.enabled = enabled;
        self
    }
    /// Muted text INSIDE the field after the value (a unit).
    pub fn suffix(mut self, suffix: &'a str) -> Self {
        self.suffix = Some(suffix);
        self
    }
    pub fn right_aligned(mut self, right: bool) -> Self {
        self.right_aligned = right;
        self
    }
    pub fn id(mut self, id: egui::Id) -> Self {
        self.id = Some(id);
        self
    }
    pub fn show_state(mut self, show: Show) -> Self {
        self.show = show;
        self
    }

    pub fn show(self, ui: &mut egui::Ui) -> InputOutput {
        let theme = Theme::of(ui);
        let c = &theme.colors;
        let width = self.width.unwrap_or_else(|| ui.spacing().text_edit_width.min(ui.available_width()));
        let height = theme.control_height();
        let id = self.id.unwrap_or_else(|| ui.next_auto_id().with("ui-kit-input"));
        let (rect, hover) = ui.allocate_exact_size(Vec2::new(width, height), egui::Sense::hover());
        let focused = (self.enabled && ui.memory(|m| m.has_focus(id))) || self.show == Show::Focus;
        let hovered = self.enabled && (hover.hovered() || self.show == Show::Hover);
        let focus = ui.ctx().animate_bool_with_time(id.with("focus"), focused, theme.motion_base());
        let fill = if self.enabled { c.bg_input } else { crate::theme::over(c.bg_panel, c.hover) };
        let border = if self.error.is_some() {
            c.danger
        } else if !self.enabled {
            c.border_subtle
        } else {
            let rest = if hovered { crate::theme::mix(c.border_strong, c.text_secondary, 0.35) } else { c.border_strong };
            paint::lerp_color(rest, c.accent_ring, focus)
        };
        ui.painter().rect(rect, radius::INPUT, fill, Stroke::new(BORDER, border), egui::StrokeKind::Inside);
        if focused {
            paint::focus_ring(ui, rect, radius::INPUT, &theme);
        }

        let pad = space::MD;
        let mut inner = rect.shrink2(Vec2::new(pad, 0.0));
        if self.lead == Lead::Search {
            let slot = Rect::from_min_size(inner.min, Vec2::new(14.0, height));
            paint::magnifier(ui.painter(), slot.center(), 5.0, Stroke::new(1.4, c.text_secondary));
            inner.min.x += 14.0 + space::SM;
        }
        let mut cleared = false;
        if self.lead == Lead::Search && !self.text.is_empty() && self.enabled {
            let slot = Rect::from_center_size(egui::pos2(inner.right() - 7.0, rect.center().y), Vec2::splat(16.0));
            let clear = ui.interact(slot, id.with("clear"), egui::Sense::click());
            clear.widget_info(|| egui::WidgetInfo::labeled(egui::WidgetType::Button, true, "Clear"));
            if clear.hovered() {
                ui.painter().rect_filled(slot, radius::INPUT, c.hover);
            }
            paint::cross(ui.painter(), slot.center(), 3.5, Stroke::new(1.4, c.text_secondary));
            if clear.clicked() {
                self.text.clear();
                cleared = true;
            }
            inner.max.x -= 16.0 + space::XS;
        }
        if let Some(suffix) = self.suffix {
            let g = paint::galley(ui, suffix, theme.font(Text::Body));
            inner.max.x -= g.size().x;
            ui.painter().galley(egui::pos2(inner.right(), rect.center().y - g.size().y / 2.0), g, if self.enabled { c.text_secondary } else { c.text_disabled });
            inner.max.x -= space::XS;
        }
        let font = theme.font(Text::Body);
        let row = ui.fonts_mut(|f| f.row_height(&font));
        let text_rect = Rect::from_center_size(inner.center(), Vec2::new(inner.width(), row));
        let edit = egui::TextEdit::singleline(self.text)
            .id(id)
            .frame(egui::Frame::NONE)
            .margin(egui::Margin::ZERO)
            .font(font)
            .text_color(if self.enabled { c.text_primary } else { c.text_disabled })
            .hint_text(egui::RichText::new(self.placeholder).color(c.text_disabled))
            .horizontal_align(if self.right_aligned { egui::Align::RIGHT } else { egui::Align::LEFT })
            .desired_width(inner.width())
            .interactive(self.enabled);
        let response = ui.put(text_rect, edit);
        if let Some(message) = self.error {
            ui.label(egui::RichText::new(message).font(theme.font(Text::Caption)).color(c.danger));
        }
        InputOutput { response, rect, cleared }
    }
}

/// The millimetres in one of a length unit, or `None` for a unit that is not a length.
fn length_mm(unit: &str) -> Option<f64> {
    Some(match unit {
        "mm" => 1.0,
        "cm" => 10.0,
        "m" => 1000.0,
        "um" | "µm" => 0.001,
        "in" | "\"" => 25.4,
        "ft" | "'" => 304.8,
        "mil" | "thou" => 0.0254,
        _ => return None,
    })
}

/// The degrees in one of an angle unit.
fn angle_deg(unit: &str) -> Option<f64> {
    Some(match unit {
        "deg" | "°" => 1.0,
        "rad" => 180.0 / std::f64::consts::PI,
        _ => return None,
    })
}

/// The factor that turns a value written in `written` into the field's `unit`.
fn unit_factor(written: &str, unit: &str) -> Result<f64, String> {
    if written == unit {
        return Ok(1.0);
    }
    if let (Some(a), Some(b)) = (length_mm(written), length_mm(unit)) {
        return Ok(a / b);
    }
    if let (Some(a), Some(b)) = (angle_deg(written), angle_deg(unit)) {
        return Ok(a / b);
    }
    if unit.is_empty() {
        return Err(format!("this field has no unit; `{written}` cannot be used here"));
    }
    Err(format!("`{written}` cannot be converted to {unit}"))
}

/// Evaluate what a user typed into a number field whose unit is `unit` ("" for
/// none): `+ - * /`, parentheses, and unit names, which multiply the value
/// before them into the field's unit, so `1/2 in` in a millimetre field is
/// 12.7 and `2 in + 5` is 55.8. This is the gallery's stand-in: the form
/// wiring (rollout step 3) hands the text to the engine's expression evaluator.
pub fn evaluate(text: &str, unit: &str) -> Result<f64, String> {
    struct Parser<'a> {
        chars: std::iter::Peekable<std::str::Chars<'a>>,
        unit: &'a str,
    }
    impl Parser<'_> {
        fn skip(&mut self) {
            while self.chars.peek().is_some_and(|c| c.is_whitespace()) {
                self.chars.next();
            }
        }
        fn expr(&mut self) -> Result<f64, String> {
            let mut value = self.term()?;
            loop {
                self.skip();
                match self.chars.peek() {
                    Some('+') => {
                        self.chars.next();
                        value += self.term()?;
                    }
                    Some('-') => {
                        self.chars.next();
                        value -= self.term()?;
                    }
                    _ => return Ok(value),
                }
            }
        }
        fn term(&mut self) -> Result<f64, String> {
            let mut value = self.factor()?;
            loop {
                self.skip();
                match self.chars.peek().copied() {
                    Some('*') => {
                        self.chars.next();
                        value *= self.factor()?;
                    }
                    Some('/') => {
                        self.chars.next();
                        let d = self.factor()?;
                        if d == 0.0 {
                            return Err("division by zero".into());
                        }
                        value /= d;
                    }
                    // A unit name multiplies what is before it: `1/2 in`.
                    Some(ch) if ch.is_alphabetic() || matches!(ch, '"' | '\'' | '°') => {
                        let mut name = String::new();
                        while let Some(ch) = self.chars.peek().copied().filter(|ch| ch.is_alphabetic() || matches!(ch, '"' | '\'' | '°')) {
                            name.push(ch);
                            self.chars.next();
                        }
                        value *= unit_factor(&name, self.unit)?;
                    }
                    _ => return Ok(value),
                }
            }
        }
        fn factor(&mut self) -> Result<f64, String> {
            self.skip();
            match self.chars.peek().copied() {
                Some('-') => {
                    self.chars.next();
                    Ok(-self.factor()?)
                }
                Some('+') => {
                    self.chars.next();
                    self.factor()
                }
                Some('(') => {
                    self.chars.next();
                    let value = self.expr()?;
                    self.skip();
                    match self.chars.next() {
                        Some(')') => Ok(value),
                        _ => Err("a `(` is not closed".into()),
                    }
                }
                Some(ch) if ch.is_ascii_digit() || ch == '.' => {
                    let mut digits = String::new();
                    while let Some(ch) = self.chars.peek().copied().filter(|ch| ch.is_ascii_digit() || *ch == '.') {
                        digits.push(ch);
                        self.chars.next();
                    }
                    digits.parse().map_err(|_| format!("`{digits}` is not a number"))
                }
                Some(ch) => Err(format!("unexpected `{ch}`")),
                None => Err("a value is missing".into()),
            }
        }
    }
    let mut parser = Parser { chars: text.chars().peekable(), unit };
    let value = parser.expr()?;
    parser.skip();
    match parser.chars.peek() {
        Some(ch) => Err(format!("unexpected `{ch}`")),
        None if value.is_finite() => Ok(value),
        None => Err("the value is not finite".into()),
    }
}

/// A value as a field shows it: up to six decimals, no trailing zeros.
pub fn format_number(value: f64) -> String {
    let text = format!("{value:.6}");
    let text = text.trim_end_matches('0').trim_end_matches('.');
    if text == "-0" { "0".into() } else { text.into() }
}

/// A number field with its unit inside the field.
#[must_use = "an input does nothing until `show` is called"]
pub struct NumberInput<'a> {
    value: &'a mut f64,
    unit: &'a str,
    label: Option<&'a str>,
    width: Option<f32>,
    speed: f64,
    enabled: bool,
    id: Option<egui::Id>,
}

/// `number_input(&mut depth).unit("mm").label("Depth").show(ui)`.
pub fn number_input(value: &mut f64) -> NumberInput<'_> {
    NumberInput { value, unit: "", label: None, width: None, speed: 0.1, enabled: true, id: None }
}

pub struct NumberOutput {
    pub input: InputOutput,
    /// The value changed this frame (a commit, or a drag on the label).
    pub changed: bool,
    /// What was typed could not be read; the field keeps it and shows this.
    pub error: Option<String>,
}

impl<'a> NumberInput<'a> {
    pub fn unit(mut self, unit: &'a str) -> Self {
        self.unit = unit;
        self
    }
    /// A label before the field that is also the DRAG HANDLE: dragging it
    /// sideways changes the value (the field itself is for typing only).
    pub fn label(mut self, label: &'a str) -> Self {
        self.label = Some(label);
        self
    }
    pub fn width(mut self, width: f32) -> Self {
        self.width = Some(width);
        self
    }
    /// Value change per point dragged on the label.
    pub fn speed(mut self, speed: f64) -> Self {
        self.speed = speed;
        self
    }
    pub fn enabled(mut self, enabled: bool) -> Self {
        self.enabled = enabled;
        self
    }
    pub fn id(mut self, id: egui::Id) -> Self {
        self.id = Some(id);
        self
    }

    pub fn show(self, ui: &mut egui::Ui) -> NumberOutput {
        let theme = Theme::of(ui);
        let id = self.id.unwrap_or_else(|| ui.next_auto_id().with("ui-kit-number"));
        let buffer_id = id.with("buffer");
        let error_id = id.with("error");
        let mut changed = false;
        ui.horizontal(|ui| {
            if let Some(label) = self.label {
                let g = paint::galley(ui, label, theme.font(Text::Label));
                let sense = if self.enabled { egui::Sense::drag() } else { egui::Sense::hover() };
                let (rect, drag) = ui.allocate_exact_size(Vec2::new(g.size().x, theme.control_height()), sense);
                let ink = if !self.enabled {
                    theme.colors.text_disabled
                } else if drag.hovered() || drag.dragged() {
                    theme.colors.text_primary
                } else {
                    theme.colors.text_secondary
                };
                ui.painter().galley(egui::pos2(rect.left(), rect.center().y - g.size().y / 2.0), g, ink);
                if self.enabled {
                    let drag = drag.on_hover_cursor(egui::CursorIcon::ResizeHorizontal);
                    if drag.dragged() {
                        let delta = f64::from(drag.drag_delta().x) * self.speed;
                        if delta != 0.0 {
                            *self.value += delta;
                            changed = true;
                            ui.data_mut(|d| {
                                d.remove::<String>(buffer_id);
                                d.remove::<String>(error_id);
                            });
                        }
                    }
                }
            }
            ui.vertical(|ui| {
                // The buffer is the user's text while they edit and while it is
                // in error; otherwise the field shows the value.
                let stored = ui.data(|d| d.get_temp::<String>(buffer_id));
                let mut text = stored.clone().unwrap_or_else(|| format_number(*self.value));
                let error = ui.data(|d| d.get_temp::<String>(error_id));
                let mut input = text_input(&mut text).id(id).right_aligned(true).enabled(self.enabled).error(error.as_deref());
                if !self.unit.is_empty() {
                    input = input.suffix(self.unit);
                }
                if let Some(width) = self.width {
                    input = input.width(width);
                }
                let out = input.show(ui);
                let mut error = error;
                if out.response.changed() || (out.response.has_focus() && stored.is_none()) {
                    ui.data_mut(|d| d.insert_temp(buffer_id, text.clone()));
                }
                if out.response.lost_focus() {
                    match evaluate(&text, self.unit) {
                        Ok(value) => {
                            if value != *self.value {
                                *self.value = value;
                                changed = true;
                            }
                            error = None;
                            ui.data_mut(|d| {
                                d.remove::<String>(buffer_id);
                                d.remove::<String>(error_id);
                            });
                        }
                        Err(message) => {
                            ui.data_mut(|d| {
                                d.insert_temp(buffer_id, text.clone());
                                d.insert_temp(error_id, message.clone());
                            });
                            error = Some(message);
                        }
                    }
                }
                NumberOutput { input: out, changed, error }
            })
            .inner
        })
        .inner
    }
}