BREP_app 0.3.0

The BREP CAD application: 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
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
//! A generic, reusable searchable **command-palette** modal — engine-agnostic.
//!
//! The caller drives it with a flat list of [`PaletteItem`]s (each an opaque
//! `id`, a displayed `label`, and extra `keywords` to match on) and reads back
//! the chosen `id`. The dialog itself knows NOTHING about features, the engine,
//! or the scene — so every "pick one of N named things" call site (add-feature
//! here; later: insert-datum, apply-appearance, jump-to-solid, …) reuses it
//! verbatim.
//!
//! # Public API shape — `show(...) -> Option<String>`
//!
//! The user asked for "a callback executed upon selection". In egui's immediate
//! mode a stored `Box<dyn FnMut(&str)>` would have to be invoked from inside the
//! per-frame draw while the caller ALSO holds `&mut EngineState` (to act on the
//! pick) — the closure would need to capture that same `&mut`, which the borrow
//! checker rejects. So the idiomatic form is inverted: [`Palette::show`] RETURNS
//! `Some(id)` on the frame an item is chosen (and closes itself), and the caller
//! acts on the id with its own `&mut EngineState` right there. Same effect as a
//! callback, no borrow fight, and the palette stays free of caller state.
//!
//! # Behaviour
//!
//! * A centred modal [`egui::Modal`] (backdrop dims + blocks the rest of the UI).
//! * A single-line text input **focused by default**, then scrollable results.
//! * A display dropdown: large icons (default), medium icons, or compact lists
//!   in one or multiple columns. The caller persists the display preference.
//! * The list is **alphabetical by label** and **filtered live** (case-insensitive
//!   substring, with a light subsequence fuzzy fallback) against `label` +
//!   `keywords` — see [`filter_items`] (pure + unit-tested).
//! * **Click** an item → selects it. **Enter** → selects the current TOP of the
//!   filtered list. **Esc** / backdrop click → cancels.

use eframe::egui;
use std::collections::HashMap;

/// One selectable entry. `id` is the opaque token returned on selection; `label`
/// is shown (and is the alphabetical sort key); `keywords` are extra strings the
/// query also matches against (short codes / aliases) but which aren't displayed.
#[derive(Clone, Debug)]
pub struct PaletteItem {
    pub id: String,
    pub label: String,
    pub keywords: Vec<String>,
}

impl PaletteItem {
    pub fn new(id: impl Into<String>, label: impl Into<String>, keywords: Vec<String>) -> Self {
        Self {
            id: id.into(),
            label: label.into(),
            keywords,
        }
    }

    /// The row text as shown. For features the label already carries the leading
    /// glyph (prepended by `feature_long_name`); the palette sorts/searches on a
    /// glyph-stripped key ([`sort_key`]) so ordering stays alphabetical by name.
    fn display(&self) -> String {
        self.label.clone()
    }
}

/// Application-wide presentation preference; independent of model contents.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PaletteDisplay {
    CompactSingle,
    CompactMulti,
    #[default]
    LargeIcons,
    MediumIcons,
}

impl PaletteDisplay {
    const ALL: [Self; 4] = [
        Self::CompactSingle,
        Self::CompactMulti,
        Self::LargeIcons,
        Self::MediumIcons,
    ];

    fn label(self) -> &'static str {
        match self {
            Self::CompactSingle => "Compact list — 1 column",
            Self::CompactMulti => "Compact list — multi column",
            Self::LargeIcons => "Icons large",
            Self::MediumIcons => "Icons medium",
        }
    }

    fn columns(self, width: f32, gap: f32) -> usize {
        let minimum = match self {
            Self::CompactSingle => return 1,
            Self::CompactMulti => 230.0,
            Self::LargeIcons => 140.0,
            Self::MediumIcons => 110.0,
        };
        ((width + gap) / (minimum + gap)).floor().max(1.0) as usize
    }
}

/// Draw a fixed-size tile with catalogue artwork above its wrapping caption.
fn icon_tile(ui: &mut egui::Ui, label: &str, top: bool, width: f32, large: bool) -> egui::Response {
    let height = if large { 120.0 } else { 96.0 };
    let response = ui.add_sized([width, height], egui::Button::new("").selected(top));
    let (icon, caption) = crate::icon_text::split_caption(label);
    if ui.is_rect_visible(response.rect) {
        let color = ui.style().interact_selectable(&response, top).text_color();
        if let Some(icon) = icon {
            egui_extras::install_image_loaders(ui.ctx());
            let side: f32 = if large { 56.0 } else { 36.0 };
            let art_height = side.min((width - 16.0) / icon.artwork_aspect.max(1.0));
            let rect = egui::Rect::from_center_size(
                egui::pos2(
                    response.rect.center().x,
                    response.rect.top() + 10.0 + side / 2.0,
                ),
                egui::vec2(art_height * icon.artwork_aspect, art_height),
            );
            let mut art = egui::Image::new(egui::ImageSource::Bytes {
                uri: format!("{}-artwork.svg", icon.uri).into(),
                bytes: egui::load::Bytes::Static(icon.artwork_svg.as_bytes()),
            })
            .fit_to_exact_size(rect.size());
            if icon.mono {
                art = art.tint(color);
            }
            art.paint_at(ui, rect);
        }
        let font = egui::TextStyle::Button.resolve(ui.style());
        let mut job = egui::text::LayoutJob::simple(caption.to_owned(), font, color, width - 12.0);
        job.halign = egui::Align::Center;
        job.wrap.max_rows = 2;
        let galley = ui.fonts_mut(|fonts| fonts.layout_job(job));
        ui.painter().galley(
            egui::pos2(
                response.rect.center().x,
                response.rect.top() + if large { 76.0 } else { 54.0 },
            ),
            galley,
            color,
        );
    }
    response.widget_info(|| {
        egui::WidgetInfo::labeled(egui::WidgetType::Button, ui.is_enabled(), caption)
    });
    response.on_hover_text(caption)
}

/// The palette's transient state. The caller owns ONE, calls [`Palette::open`]
/// to populate + show it, and [`Palette::show`] every frame; the return of
/// `show` is the selection outcome.
#[derive(Default)]
pub struct Palette {
    open: bool,
    pub display: PaletteDisplay,
    display_changed: bool,
    /// The live query text (bound to the text input).
    query: String,
    /// Heading text (empty → no heading).
    title: String,
    /// Text-input hint.
    placeholder: String,
    /// The items, pre-sorted alphabetical by label at [`open`](Palette::open).
    items: Vec<PaletteItem>,
    /// Set on open (and after a no-op Enter) so the text input grabs focus.
    want_focus: bool,
    /// Per-frame widget rects (text input + visible rows) for the headed
    /// verifier. Keys include `"input"`, `"display"`, `"top"`, and `"item:<id>"`.
    /// Rebuilt each show; visible dropdown options use `"display:<mode>"`.
    hits: HashMap<String, egui::Rect>,
}

impl Palette {
    pub fn new() -> Self {
        Self::default()
    }

    /// Populate + open the palette. Items are sorted alphabetical by label; the
    /// query is reset and the text input will focus on the next frame.
    pub fn open(
        &mut self,
        mut items: Vec<PaletteItem>,
        title: impl Into<String>,
        placeholder: impl Into<String>,
    ) {
        sort_by_label(&mut items);
        self.items = items;
        self.title = title.into();
        self.placeholder = placeholder.into();
        self.query.clear();
        self.open = true;
        self.want_focus = true;
    }

    pub fn take_display_change(&mut self) -> bool {
        std::mem::take(&mut self.display_changed)
    }

    pub fn is_open(&self) -> bool {
        self.open
    }

    pub fn close(&mut self) {
        self.open = false;
        self.query.clear();
        self.items.clear();
        self.hits.clear();
    }

    /// The per-frame widget rects (text input + visible rows) for the headed
    /// verifier — empty when the palette is closed.
    pub fn hits(&self) -> &HashMap<String, egui::Rect> {
        &self.hits
    }

    /// Draw the palette (if open) and return the chosen item id on the frame a
    /// selection is made (the palette closes itself). `None` while it stays open,
    /// while nothing is chosen, and on cancel (Esc / backdrop click, which also
    /// close it). Idempotent when closed.
    pub fn show(&mut self, ctx: &egui::Context) -> Option<String> {
        if !self.open {
            return None;
        }
        self.hits.clear();

        let mut selected: Option<String> = None;
        let mut enter_no_match = false;

        let modal = egui::Modal::new(egui::Id::new("brep-command-palette")).show(ctx, |ui| {
            let desired_width: f32 = if self.display == PaletteDisplay::CompactSingle {
                360.0
            } else {
                620.0
            };
            ui.set_width(desired_width.min((ctx.content_rect().width() - 40.0).max(160.0)));

            if !self.title.is_empty() {
                ui.heading(&self.title);
                ui.add_space(4.0);
            }

            ui.horizontal(|ui| {
                ui.label("Display");
                let combo = egui::ComboBox::from_id_salt("palette-display")
                    .selected_text(self.display.label())
                    .show_ui(ui, |ui| {
                        for mode in PaletteDisplay::ALL {
                            let option = ui.selectable_value(&mut self.display, mode, mode.label());
                            self.hits.insert(format!("display:{mode:?}"), option.rect);
                            if option.changed() {
                                self.display_changed = true;
                                self.want_focus = true;
                            }
                        }
                    });
                self.hits.insert("display".into(), combo.response.rect);
            });
            ui.add_space(4.0);

            // --- search input (focused by default) ----------------------------
            let input = ui.add(
                egui::TextEdit::singleline(&mut self.query)
                    .hint_text(&self.placeholder)
                    .desired_width(f32::INFINITY),
            );
            self.hits.insert("input".into(), input.rect);
            if self.want_focus {
                input.request_focus();
                self.want_focus = false;
            }
            // While focused, keep Esc for the modal (its `should_close` consumes
            // it to cancel) instead of letting egui surrender focus — which would
            // otherwise let the app's global Esc handler eat it a frame early.
            if input.has_focus() {
                ui.memory_mut(|m| {
                    m.set_focus_lock_filter(
                        input.id,
                        egui::EventFilter {
                            escape: true,
                            horizontal_arrows: true,
                            ..Default::default()
                        },
                    )
                });
            }
            // Enter commits the current TOP of the filtered list.
            let enter = input.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));

            ui.add_space(4.0);
            ui.separator();

            // --- filtered, ranked list ---------------------------------------
            let filtered = filter_items(&self.items, &self.query);
            if enter {
                match filtered.first() {
                    Some(top) => selected = Some(top.id.clone()),
                    None => enter_no_match = true,
                }
            }

            egui::ScrollArea::vertical()
                .max_height((ctx.content_rect().height() - 200.0).clamp(100.0, 480.0))
                .auto_shrink([false, false])
                .show(ui, |ui| {
                    if filtered.is_empty() {
                        ui.weak("No matches");
                    }
                    let gap = ui.spacing().item_spacing.x;
                    let columns = self.display.columns(ui.available_width(), gap);
                    let width = ((ui.available_width() - gap * (columns - 1) as f32)
                        / columns as f32)
                        .max(1.0);
                    for (row_index, items) in filtered.chunks(columns).enumerate() {
                        ui.horizontal(|ui| {
                            for (column, item) in items.iter().enumerate() {
                                let is_top = row_index == 0 && column == 0;
                                let row = ui
                                    .push_id(&item.id, |ui| match self.display {
                                        PaletteDisplay::LargeIcons
                                        | PaletteDisplay::MediumIcons => icon_tile(
                                            ui,
                                            &item.label,
                                            is_top,
                                            width,
                                            self.display == PaletteDisplay::LargeIcons,
                                        ),
                                        PaletteDisplay::CompactSingle => {
                                            crate::icon_text::selectable_icon_label(
                                                ui,
                                                is_top,
                                                &item.display(),
                                            )
                                        }
                                        PaletteDisplay::CompactMulti => {
                                            let (icon, caption) =
                                                crate::icon_text::split_caption(&item.label);
                                            let button = if let Some(icon) = icon {
                                                egui_extras::install_image_loaders(ui.ctx());
                                                egui::Button::selectable(
                                                    is_top,
                                                    (
                                                        crate::icon_text::image(
                                                            icon,
                                                            ui.text_style_height(
                                                                &egui::TextStyle::Body,
                                                            ),
                                                        ),
                                                        caption,
                                                    ),
                                                )
                                                .image_tint_follows_text_color(icon.mono)
                                            } else {
                                                egui::Button::selectable(is_top, caption)
                                            };
                                            ui.add_sized([width, 24.0], button.truncate())
                                                .on_hover_text(caption)
                                        }
                                    })
                                    .inner;
                                if ui.is_rect_visible(row.rect) {
                                    let visible = row.rect.intersect(ui.clip_rect());
                                    self.hits.insert(format!("item:{}", item.id), visible);
                                    if is_top {
                                        self.hits.insert("top".into(), visible);
                                    }
                                }
                                if row.clicked() {
                                    selected = Some(item.id.clone());
                                }
                            }
                        });
                    }
                });
        });

        // A pick closes + reports; a cancel (Esc / backdrop) just closes.
        if let Some(id) = selected {
            self.close();
            return Some(id);
        }
        if modal.should_close() {
            self.close();
        } else if enter_no_match {
            // Enter with an empty result surrendered the input's focus; grab it
            // back so the user can keep typing.
            self.want_focus = true;
        }
        None
    }
}

/// Sort/tie-break key: the label lower-cased with any leading non-alphanumeric
/// glyph (a feature icon prepended by `feature_long_name`) and spaces stripped,
/// so the resting order stays alphabetical by NAME despite an icon prefix. A
/// glyph-free label is unaffected.
fn sort_key(label: &str) -> String {
    label
        .trim_start_matches(|c: char| !c.is_ascii_alphanumeric())
        .to_lowercase()
}

/// Sort items alphabetical (case-insensitive) by label — the resting list order.
pub(crate) fn sort_by_label(items: &mut [PaletteItem]) {
    items.sort_by(|a, b| sort_key(&a.label).cmp(&sort_key(&b.label)));
}

/// Filter + rank `items` against `query` (case-insensitive). Returns references
/// to the matching items, best match first, ties broken alphabetically by label.
/// An empty query returns ALL items in their existing (alphabetical) order.
///
/// Matching is substring-first (an earlier, longer hit ranks higher) with a
/// light subsequence fuzzy fallback, evaluated against the label (slightly
/// preferred) and every keyword.
pub fn filter_items<'a>(items: &'a [PaletteItem], query: &str) -> Vec<&'a PaletteItem> {
    let needle = query.trim().to_lowercase();
    if needle.is_empty() {
        return items.iter().collect();
    }
    let mut scored: Vec<(i32, &PaletteItem)> = items
        .iter()
        .filter_map(|item| item_score(item, &needle).map(|s| (s, item)))
        .collect();
    // Higher score first; alphabetical by label on ties (stable, predictable top).
    scored.sort_by(|a, b| {
        b.0.cmp(&a.0)
            .then_with(|| sort_key(&a.1.label).cmp(&sort_key(&b.1.label)))
    });
    scored.into_iter().map(|(_, item)| item).collect()
}

/// Best match score of an item against a (lowercased) needle, or `None` if it
/// matches neither the label nor any keyword. The label carries a small bonus so
/// a label hit outranks an equal keyword hit.
fn item_score(item: &PaletteItem, needle: &str) -> Option<i32> {
    const LABEL_BONUS: i32 = 10;
    let mut best: Option<i32> = None;
    let mut consider = |s: Option<i32>| {
        if let Some(s) = s {
            best = Some(best.map_or(s, |b| b.max(s)));
        }
    };
    consider(fuzzy_score(&item.label, needle).map(|s| s + LABEL_BONUS));
    for kw in &item.keywords {
        consider(fuzzy_score(kw, needle));
    }
    best
}

/// Score one `haystack` against a lowercased `needle`: a substring hit scores
/// `1000 - start` (earlier is better); otherwise a subsequence hit scores
/// `400 - last_index` (tighter is better); no match → `None`.
fn fuzzy_score(haystack: &str, needle: &str) -> Option<i32> {
    if needle.is_empty() {
        return Some(0);
    }
    let hay = haystack.to_lowercase();
    if let Some(pos) = hay.find(needle) {
        return Some(1000 - pos as i32);
    }
    // Subsequence fallback: every needle char appears in order.
    let mut chars = needle.chars().peekable();
    let mut last = 0i32;
    for (i, hc) in hay.chars().enumerate() {
        match chars.peek() {
            Some(&nc) if hc == nc => {
                chars.next();
                last = i as i32;
            }
            Some(_) => {}
            None => break,
        }
    }
    chars.peek().is_none().then_some(400 - last)
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn all_layouts_fit_and_keep_ranked_selection_at_desktop_and_phone_widths() {
        for mode in PaletteDisplay::ALL {
            for screen_width in [360.0, 1400.0] {
                let ctx = egui::Context::default();
                let mut palette = Palette::new();
                palette.display = mode;
                palette.open(items(), "Add feature", "Search features…");
                for frame in 0..4 {
                    let raw = egui::RawInput {
                        screen_rect: Some(egui::Rect::from_min_size(
                            egui::Pos2::ZERO,
                            egui::vec2(screen_width, 800.0),
                        )),
                        time: Some(frame as f64 / 60.0),
                        ..Default::default()
                    };
                    let _ = ctx.run_ui(raw, |_| {
                        assert_eq!(palette.show(&ctx), None);
                    });
                }
                let top = palette.hits()["top"];
                assert_eq!(top, palette.hits()["item:B"]);
                for rect in palette.hits().values() {
                    assert!(
                        rect.left() >= 0.0 && rect.right() <= screen_width,
                        "{mode:?}: {rect:?}"
                    );
                }
                let second = palette.hits()["item:P.CU"];
                if mode == PaletteDisplay::CompactSingle
                    || (screen_width == 360.0 && mode == PaletteDisplay::CompactMulti)
                {
                    assert!(second.top() > top.top());
                } else {
                    assert_eq!(second.top(), top.top());
                    assert!(second.left() > top.left());
                }
                palette.query = "sphere".into();
                let _ = ctx.run_ui(egui::RawInput::default(), |_| {
                    palette.show(&ctx);
                });
                assert_eq!(palette.hits()["top"], palette.hits()["item:P.S"]);
                assert!(!palette.hits().contains_key("item:B"));
            }
        }
    }

    fn items() -> Vec<PaletteItem> {
        // Deliberately unsorted on input; `open`/`sort_by_label` orders them.
        let mut v = vec![
            PaletteItem::new("P.CY", "Primitive Cylinder", vec!["P.CY".into()]),
            PaletteItem::new("P.CU", "Primitive Cube", vec!["P.CU".into()]),
            PaletteItem::new("B", "Boolean", vec!["B".into()]),
            PaletteItem::new("P.S", "Primitive Sphere", vec!["P.S".into()]),
        ];
        sort_by_label(&mut v);
        v
    }

    #[test]
    fn empty_query_is_alphabetical_by_label() {
        let v = items();
        let labels: Vec<&str> = filter_items(&v, "")
            .iter()
            .map(|i| i.label.as_str())
            .collect();
        assert_eq!(
            labels,
            [
                "Boolean",
                "Primitive Cube",
                "Primitive Cylinder",
                "Primitive Sphere"
            ]
        );
    }

    #[test]
    fn substring_query_ranks_the_match_first() {
        let v = items();
        let out = filter_items(&v, "cyl");
        assert_eq!(out.first().unwrap().id, "P.CY");
    }

    #[test]
    fn query_is_case_insensitive() {
        let v = items();
        assert_eq!(filter_items(&v, "CYL").first().unwrap().id, "P.CY");
        assert_eq!(filter_items(&v, "boolean").first().unwrap().id, "B");
    }

    #[test]
    fn keyword_matches_even_when_label_does_not() {
        let v = items();
        // "p.cy" appears only in the keyword, never in a label word.
        let out = filter_items(&v, "p.cy");
        assert_eq!(out.first().unwrap().id, "P.CY");
    }

    #[test]
    fn non_matching_query_yields_nothing() {
        let v = items();
        assert!(filter_items(&v, "zzz").is_empty());
    }

    #[test]
    fn light_fuzzy_subsequence_matches() {
        let v = items();
        // "cye" is not a substring of "Cylinder" but is a subsequence (Cy...e).
        let out = filter_items(&v, "cye");
        assert_eq!(out.first().unwrap().id, "P.CY");
    }

    #[test]
    fn prefix_substring_outranks_a_later_substring() {
        let v = vec![
            PaletteItem::new("a", "Rounded corner", vec![]),
            PaletteItem::new("b", "Corner treatment", vec![]),
        ];
        // Both contain "corner"; the one where it starts earlier ranks first.
        let out = filter_items(&v, "corner");
        assert_eq!(out.first().unwrap().id, "b");
    }
}