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
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
//! File dialog — a **reusable modal** for model-document management: **New /
//! Open / Save / Save As** of the MODEL, driven from the toolbar. Mirrors the
//! shape of [`crate::palette::Palette`]: the caller owns ONE [`FileDialog`],
//! calls [`FileDialog::dispatch`] when a toolbar file button is clicked (which
//! either acts immediately or opens the modal in a mode), and calls
//! [`FileDialog::show`] every frame to draw the (possibly open) modal.
//!
//! The model document IS the engine-owned history: `EngineState` serializes it
//! with `history_request_json()` (the `.BREP.json` recipe) and loads it with
//! `set_history_json` / `load_model_and_fit`. This dialog keeps NO model state —
//! it only holds transient UI buffers (the name field, a status line, the
//! last-saved signature used to derive the dirty flag, and the current document
//! name) and drives the engine + the [`ModelStore`] seam.
//!
//! Persistence crosses the storage seam's model half ([`ModelStore`]) — the ONE
//! platform exception. On the **web** the modal itself is the file browser: the
//! Open modal lists the saved models (localStorage) with an Upload button, and
//! Save As is a name prompt. On the **desktop** (default-on `native-dialog`
//! feature, rfd) Open + Save As go straight to the platform's NATIVE file
//! dialog and plain Save writes back to the opened/chosen path; built with
//! `--no-default-features` (or on a test store), native falls back to the same
//! egui modal over the models directory.
use crate::store::{model_display_name, ModelStore};
use brep_render::engine_state::EngineState;
use eframe::egui;
#[cfg(target_arch = "wasm32")]
use serde_json::Value;
#[cfg(target_arch = "wasm32")]
use std::collections::HashMap;
/// The file operation a toolbar button requests. The shell maps a clicked
/// toolbar button to one of these and hands it to [`FileDialog::dispatch`].
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum FileAction {
New,
Open,
Save,
SaveAs,
/// Import a foreign format (STEP) FROM the user's filesystem, appending it to
/// the model rather than replacing it.
Import,
/// Export the model TO the user's filesystem in a chosen format (STEP / STL).
Export,
}
/// Which modal (if any) the dialog is currently showing.
#[derive(Clone, Copy, PartialEq, Eq)]
enum Mode {
/// Open a saved model (list + Upload on web / native-fallback).
Open,
/// Prompt for a name and save under it.
SaveAs,
/// Confirm discarding unsaved changes before New.
ConfirmNew,
/// Choose an export format (STEP / STL) for the current model.
Export,
}
/// Whether Open / Save As should drive the platform's NATIVE file dialog (rfd)
/// instead of the in-app egui modal: a desktop build compiled with the
/// (default-on) `native-dialog` feature AND a store whose file interchange is
/// dialog-backed (the real models store — test stores opt out, keeping the
/// suite headless on the modal path). The web build and the lean
/// (`--no-default-features`) native build both use the egui modal.
fn use_native_dialog(store: &dyn ModelStore) -> bool {
cfg!(all(not(target_arch = "wasm32"), feature = "native-dialog"))
&& store.supports_file_interchange()
}
/// Whether an imported file name is a STEP file (`.step` / `.stp`, any case) —
/// the routing key in [`FileDialog::show`]. Model documents arrive
/// extension-stripped (web) or as a full `*.json` path (native dialog), so this
/// never mis-routes a `.BREP.json` file.
fn is_step_name(name: &str) -> bool {
let lower = name.to_ascii_lowercase();
lower.ends_with(".step") || lower.ends_with(".stp")
}
/// The reusable file dialog — transient UI buffers + the current document
/// identity; the model itself lives in `EngineState`'s history.
pub struct FileDialog {
/// The current document's name (`None` = a never-saved "untitled" model).
current_name: Option<String>,
/// The name field buffer, used by the Save As modal.
name_buf: String,
/// The model request JSON as of the last New/Open/Save — the baseline the
/// dirty flag compares the live history against. `None` until first seeded.
saved_signature: Option<String>,
/// Last-action status line, surfaced inside the modal.
status: String,
/// Whether a modal is currently open.
open: bool,
/// The open modal's mode (only meaningful while `open`).
mode: Mode,
/// Set on open so the Save As text input grabs focus on the next frame.
want_focus: bool,
/// Per-frame widget hit-rects for the headed verifier (wasm only).
#[cfg(target_arch = "wasm32")]
hits: HashMap<String, egui::Rect>,
}
impl FileDialog {
/// Seed from the engine's current model so a freshly-booted document counts
/// as clean (the seed history is the baseline; the first edit marks it dirty).
pub fn new(state: &EngineState) -> Self {
Self {
current_name: None,
name_buf: String::new(),
saved_signature: Some(state.history_request_json()),
status: String::new(),
open: false,
mode: Mode::Open,
want_focus: false,
#[cfg(target_arch = "wasm32")]
hits: HashMap::new(),
}
}
// --- dirty tracking -------------------------------------------------------
/// Snapshot the current model as the clean baseline (after New/Open/Save).
fn mark_clean(&mut self, state: &EngineState) {
self.saved_signature = Some(state.history_request_json());
}
/// Dirty = the live model differs from the last saved/opened baseline.
/// (Rolling the history does NOT change the request document, so navigating
/// steps never marks dirty — only real edits/add/delete/reorder do.)
pub fn is_dirty(&self, state: &EngineState) -> bool {
match &self.saved_signature {
Some(saved) => *saved != state.history_request_json(),
None => true,
}
}
// --- dispatch: a toolbar button was clicked -------------------------------
/// Act on a toolbar file button. Some actions run immediately (New on a clean
/// doc; Save on a named doc; Open/Save As on native w/ rfd); the rest open the
/// modal in the matching [`Mode`].
pub fn dispatch(
&mut self,
action: FileAction,
state: &mut EngineState,
store: &dyn ModelStore,
) {
match action {
FileAction::New => {
if self.is_dirty(state) {
self.open_modal(Mode::ConfirmNew);
} else {
self.new_document(state);
}
}
FileAction::Open => {
if use_native_dialog(store) {
// Native picker; the chosen file arrives via take_import().
match store.begin_import() {
Ok(()) => self.status = "choose a file…".into(),
Err(e) => self.status = format!("open failed: {e}"),
}
} else {
self.open_modal(Mode::Open);
}
}
FileAction::Save => match self.current_name.clone() {
// A named document saves straight to its name.
Some(name) => {
let _ = self.save_to(state, store, name);
}
// An unnamed document falls through to Save As.
None => self.dispatch(FileAction::SaveAs, state, store),
},
FileAction::SaveAs => {
if use_native_dialog(store) {
// Native save dialog writes to a user-chosen path; that path
// becomes the document identity so a later plain Save writes
// straight back to it.
let name = self.effective_name();
match store.export_file(&name, &state.history_request_json()) {
Ok(Some(saved)) => {
self.name_buf = model_display_name(&saved);
self.current_name = Some(saved.clone());
self.mark_clean(state);
self.status = format!("saved {saved}");
}
Ok(None) => self.status = "save cancelled".into(),
Err(e) => self.status = format!("save failed: {e}"),
}
} else {
// Seed the name field with the current/effective name.
self.name_buf = self.effective_name();
self.open_modal(Mode::SaveAs);
}
}
FileAction::Import => {
// Fire the platform STEP picker; the chosen file arrives via
// take_import() and is routed by extension in show() (a `.step`/
// `.stp` name → import_step_feature, appended to the model).
match store.begin_import_filtered(("STEP", &["step", "stp", "STEP", "STP"])) {
Ok(()) => self.status = "choose a STEP file\u{2026}".into(),
Err(e) => self.status = format!("import failed: {e}"),
}
}
FileAction::Export => {
self.name_buf = self.effective_name();
self.open_modal(Mode::Export);
}
}
}
/// Open the modal in `mode` (and focus its input next frame).
fn open_modal(&mut self, mode: Mode) {
self.mode = mode;
self.open = true;
self.want_focus = true;
}
// --- per-frame draw -------------------------------------------------------
/// Draw the modal (if open) and pick up any completed async import. Called
/// every frame by the shell with a ctx-level handle (the modal is ctx-level,
/// like the command palette).
pub fn show(&mut self, ctx: &egui::Context, state: &mut EngineState, store: &dyn ModelStore) {
#[cfg(target_arch = "wasm32")]
self.hits.clear();
// A completed async import (web upload / native rfd pick) is picked up
// here, before drawing, so the model is live for this frame. Routed by
// extension: a STEP file (`.step`/`.stp`) is APPENDED to the model as an
// IMPORT3D feature; anything else is a `.BREP.json` model document loaded
// (replacing the model). The model lanes deliver an extension-less name
// (web, stripped by `model_display_name`) or a full `*.json` path
// (native dialog), so only real STEP files route here.
if let Some((name, contents)) = store.take_import() {
if is_step_name(&name) {
self.import_step(state, &name, &contents);
} else {
self.load_document(state, &name, &contents);
}
self.open = false;
}
if !self.open {
return;
}
match self.mode {
Mode::ConfirmNew => self.show_confirm_new(ctx, state),
Mode::SaveAs => self.show_save_as(ctx, state, store),
Mode::Open => self.show_open(ctx, state, store),
Mode::Export => self.show_export(ctx, state, store),
}
}
/// The **Discard unsaved changes?** confirmation shown before New on a dirty
/// document.
fn show_confirm_new(&mut self, ctx: &egui::Context, state: &mut EngineState) {
let title = self.current_name.clone().unwrap_or_else(|| "untitled".into());
let mut discard = false;
let mut cancel = false;
let modal = egui::Modal::new(egui::Id::new("brep-file-confirm-new")).show(ctx, |ui| {
ui.set_width(320.0);
ui.heading("Discard unsaved changes?");
ui.add_space(4.0);
ui.label(format!("\"{title}\" has unsaved changes."));
ui.add_space(6.0);
ui.horizontal(|ui| {
let d = ui.button("Discard");
self.hit("confirm:discard", &d);
if d.clicked() {
discard = true;
}
let c = ui.button("Cancel");
self.hit("confirm:cancel", &c);
if c.clicked() {
cancel = true;
}
});
});
if discard {
self.new_document(state);
self.open = false;
} else if cancel || modal.should_close() {
self.open = false;
}
}
/// The **Save As** name prompt.
fn show_save_as(
&mut self,
ctx: &egui::Context,
state: &mut EngineState,
store: &dyn ModelStore,
) {
let mut do_save = false;
let mut cancel = false;
let modal = egui::Modal::new(egui::Id::new("brep-file-saveas")).show(ctx, |ui| {
ui.set_width(320.0);
ui.heading("Save model as");
ui.add_space(4.0);
let field = ui.add(
egui::TextEdit::singleline(&mut self.name_buf)
.hint_text("model name")
.desired_width(f32::INFINITY),
);
self.hit("field:name", &field);
if self.want_focus {
field.request_focus();
self.want_focus = false;
}
let enter = field.lost_focus() && ui.input(|i| i.key_pressed(egui::Key::Enter));
ui.add_space(6.0);
ui.horizontal(|ui| {
let save = ui.button("Save");
self.hit("save", &save);
if save.clicked() || enter {
do_save = true;
}
let c = ui.button("Cancel");
self.hit("cancel", &c);
if c.clicked() {
cancel = true;
}
});
if !self.status.is_empty() {
ui.add_space(4.0);
ui.weak(&self.status);
}
});
if do_save {
let name = self.name_buf.clone();
if self.save_to(state, store, name) {
self.open = false;
}
} else if cancel || modal.should_close() {
self.open = false;
}
}
/// The **Export** chooser: pick a format (STEP / STL) and write the current
/// model to the user's filesystem under `<name>.<ext>` through the store's
/// format-typed interchange. STEP serializes the exact NURBS topology; STL is
/// the ASCII display mesh. No solids → a clear status line, nothing written.
fn show_export(&mut self, ctx: &egui::Context, state: &mut EngineState, store: &dyn ModelStore) {
let mut chosen: Option<&'static str> = None;
let mut cancel = false;
let modal = egui::Modal::new(egui::Id::new("brep-file-export")).show(ctx, |ui| {
ui.set_width(320.0);
ui.heading("Export model");
ui.add_space(4.0);
let field = ui.add(
egui::TextEdit::singleline(&mut self.name_buf)
.hint_text("file name")
.desired_width(f32::INFINITY),
);
self.hit("field:name", &field);
if self.want_focus {
field.request_focus();
self.want_focus = false;
}
ui.add_space(6.0);
ui.horizontal(|ui| {
let step = ui.button("STEP (.step)");
self.hit("export:step", &step);
if step.clicked() {
chosen = Some("step");
}
let stl = ui.button("STL (.stl)");
self.hit("export:stl", &stl);
if stl.clicked() {
chosen = Some("stl");
}
// The full model RECIPE (`.BREP.json`) — for saving a document to
// disk / sharing a failing model for a bug report. Re-openable via
// Open / Import.
let json = ui.button("JSON (.BREP.json)");
self.hit("export:json", &json);
if json.clicked() {
chosen = Some("json");
}
let c = ui.button("Cancel");
self.hit("cancel", &c);
if c.clicked() {
cancel = true;
}
});
if !self.status.is_empty() {
ui.add_space(4.0);
ui.weak(&self.status);
}
});
if let Some(format) = chosen {
if self.export_as(state, store, format) {
self.open = false;
}
} else if cancel || modal.should_close() {
self.open = false;
}
}
/// The **Open** browser: the saved-model list (+ Upload where the platform
/// supports real-file interchange).
fn show_open(&mut self, ctx: &egui::Context, state: &mut EngineState, store: &dyn ModelStore) {
let names = store.list();
let backend = store.backend_label();
let interchange = store.supports_file_interchange();
let mut chosen: Option<String> = None;
let mut to_delete: Option<String> = None;
let mut do_upload = false;
let mut cancel = false;
let modal = egui::Modal::new(egui::Id::new("brep-file-open")).show(ctx, |ui| {
ui.set_width(360.0);
ui.heading("Open model");
ui.weak(&backend);
ui.add_space(4.0);
ui.separator();
egui::ScrollArea::vertical()
.max_height(320.0)
.auto_shrink([false, false])
.show(ui, |ui| {
if names.is_empty() {
ui.weak("(no saved models)");
}
for name in &names {
ui.horizontal(|ui| {
let is_current = self.current_name.as_deref() == Some(name.as_str());
let row = ui.selectable_label(is_current, format!("\u{1F5CE} {name}"));
self.hit(&format!("open:{name}"), &row);
if row.clicked() {
chosen = Some(name.clone());
}
let del = ui.small_button("\u{2715}");
self.hit(&format!("del:{name}"), &del);
if del.clicked() {
to_delete = Some(name.clone());
}
});
}
});
ui.separator();
ui.horizontal(|ui| {
if interchange {
let up = ui.button("\u{2B06} Upload\u{2026}");
self.hit("upload", &up);
if up.clicked() {
do_upload = true;
}
}
let c = ui.button("Cancel");
self.hit("cancel", &c);
if c.clicked() {
cancel = true;
}
});
if !self.status.is_empty() {
ui.add_space(4.0);
ui.weak(&self.status);
}
});
if let Some(name) = chosen {
self.open_document(state, store, &name);
self.open = false;
} else if let Some(name) = to_delete {
let _ = store.remove(&name);
self.status = format!("removed {name}");
if self.current_name.as_deref() == Some(name.as_str()) {
self.current_name = None;
}
} else if do_upload {
// Fire the platform picker; the file arrives via take_import() and is
// loaded on a later frame (the modal closes now).
match store.begin_import() {
Ok(()) => {
self.status = "choose a file…".into();
self.open = false;
}
Err(e) => self.status = format!("import failed: {e}"),
}
} else if cancel || modal.should_close() {
self.open = false;
}
}
// --- model operations -----------------------------------------------------
/// The name to save under: the field if non-empty, else the current document
/// name, else `"untitled"`.
fn effective_name(&self) -> String {
let field = self.name_buf.trim();
if !field.is_empty() {
field.to_string()
} else {
self.current_name.clone().unwrap_or_else(|| "untitled".into())
}
}
/// **New** — reset the engine to an empty history; clean untitled document.
fn new_document(&mut self, state: &mut EngineState) {
let _ = state.set_history_json(r#"{"expressions":"","configurator":{},"features":[]}"#);
self.current_name = None;
self.name_buf.clear();
self.mark_clean(state);
self.status = "new (empty) model".into();
}
/// Write the current model request JSON through the store under `name`.
/// Returns `true` on success (so the caller can close the modal).
fn save_to(&mut self, state: &mut EngineState, store: &dyn ModelStore, name: String) -> bool {
let name = name.trim().to_string();
if name.is_empty() {
self.status = "enter a name to save".into();
return false;
}
match store.write(&name, &state.history_request_json()) {
Ok(()) => {
// `current_name` keeps the raw identity (a full path when a
// native dialog chose it); the name field shows the bare name.
self.name_buf = model_display_name(&name);
self.current_name = Some(name.clone());
self.mark_clean(state);
self.status = format!("saved {name}");
true
}
Err(e) => {
self.status = format!("save failed: {e}");
false
}
}
}
/// **Open** — read a stored document and load+frame it.
fn open_document(&mut self, state: &mut EngineState, store: &dyn ModelStore, name: &str) {
match store.read(name) {
Some(contents) => self.load_document(state, name, &contents),
None => self.status = format!("open failed: '{name}' not found"),
}
}
/// Serialize the current model in `format` (`"step"` | `"stl"` | `"json"`) and
/// write it through the store's format-typed interchange under `<name>.<ext>`.
/// `"json"` is the full model RECIPE (`.BREP.json`, `history_request_json`) —
/// the exact document Open/Import consume, for sharing a failing model. Returns
/// `true` on success (so the caller can close the modal); a guard message and
/// `false` when there is nothing to export or the engine/store errs.
fn export_as(&mut self, state: &EngineState, store: &dyn ModelStore, format: &str) -> bool {
let name = self.effective_name();
let (text, ext) = match format {
"stl" => (state.export_stl_text(), "stl"),
"json" => (Ok(state.history_request_json()), "BREP.json"),
_ => (state.export_step_text(), "step"),
};
match text {
Ok(contents) => match store.export_file_named(&format!("{name}.{ext}"), &contents) {
Ok(()) => {
self.status = format!("exported {name}.{ext}");
true
}
Err(e) => {
self.status = format!("export failed: {e}");
false
}
},
Err(e) => {
self.status = format!("export failed: {e}");
false
}
}
}
/// Append an imported STEP file to the model (an IMPORT3D feature), then treat
/// the enlarged model as dirty (an import is an edit, not an Open — the model
/// keeps its current name / save baseline).
fn import_step(&mut self, state: &mut EngineState, name: &str, contents: &str) {
match state.import_step_feature(contents) {
Ok(_) => {
state.zoom_to_fit(); // frame the newly imported body
self.status = format!("imported {name}");
}
Err(e) => self.status = format!("import failed: {e}"),
}
}
/// Load a model document's contents into the engine (roll to the last
/// feature + zoom-to-fit) and record it as the clean baseline.
fn load_document(&mut self, state: &mut EngineState, name: &str, contents: &str) {
match state.load_model_and_fit(contents) {
Ok(_) => {
// `current_name` keeps the raw identity — the full path when a
// native dialog picked the file, so plain Save writes back to
// it; the name field shows only the bare display name.
self.current_name = Some(name.to_string());
self.name_buf = model_display_name(name);
self.mark_clean(state);
self.status = format!("opened {name}");
}
Err(e) => self.status = format!("open failed: {e}"),
}
}
// --- verifier hooks (wasm only) -------------------------------------------
/// The published state for the headed verifier: current name, dirty flag,
/// backend label, the stored-document list, and the modal's open/mode.
#[cfg(target_arch = "wasm32")]
pub fn file_state_json(&self, state: &EngineState, store: &dyn ModelStore) -> String {
serde_json::json!({
"name": self.current_name,
"nameBuf": self.name_buf,
"dirty": self.is_dirty(state),
"backend": store.backend_label(),
"interchange": store.supports_file_interchange(),
"list": store.list(),
"status": self.status,
"open": self.open,
"mode": match self.mode {
Mode::Open => "open",
Mode::SaveAs => "saveas",
Mode::ConfirmNew => "confirmnew",
Mode::Export => "export",
},
})
.to_string()
}
/// The published widget hit-rects (egui points) for the headed verifier.
#[cfg(target_arch = "wasm32")]
pub fn hits_json(&self) -> String {
let map: serde_json::Map<String, Value> = self
.hits
.iter()
.map(|(k, r)| {
(
k.clone(),
serde_json::json!([r.min.x, r.min.y, r.width(), r.height()]),
)
})
.collect();
Value::Object(map).to_string()
}
/// Record a widget's screen rect for the headed verifier (wasm only; a no-op
/// elsewhere so the dialog code reads the same on both targets).
#[cfg(target_arch = "wasm32")]
fn hit(&mut self, key: &str, resp: &egui::Response) {
self.hits.insert(key.to_string(), resp.rect);
}
#[cfg(not(target_arch = "wasm32"))]
#[inline]
fn hit(&mut self, _key: &str, _resp: &egui::Response) {}
}
#[cfg(all(test, not(target_arch = "wasm32")))]
mod tests {
use super::*;
use crate::store::native_test_store;
/// The engine's `history_request_json()` is a stable model document: writing
/// it through the store and loading it back reproduces the same request —
/// the native save/open round-trip the brief asks for.
#[test]
fn model_document_round_trips_through_store_and_engine() {
// A temp-dir store (never touches the real config dir).
let dir = std::env::temp_dir().join(format!("brep-app-file-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let store = native_test_store(dir.clone());
// Build a model in the engine, serialize it, save it through the store.
let mut engine = EngineState::new();
let seed = r#"{"expressions":"","configurator":{},"features":[
{"type":"P.CU","inputParams":{"id":"Box","sizeX":8.0,"sizeY":8.0,"sizeZ":8.0,
"transform":{"position":[0,0,0],"rotationEuler":[0,0,0],"scale":[1,1,1]},
"boolean":{"targets":[],"operation":"NONE"}},"persistentData":{}}
]}"#;
engine.set_history_json(seed).unwrap();
let before = engine.history_request_json();
store.write("roundtrip", &before).unwrap();
// A fresh engine loads the stored document + frames it, reproducing it.
let mut reopened = EngineState::new();
let contents = store.read("roundtrip").unwrap();
reopened.load_model_and_fit(&contents).unwrap();
let after = reopened.history_request_json();
assert_eq!(before, after, "request JSON round-trips through the store");
assert_eq!(reopened.history_len(), 1);
assert_eq!(reopened.scene.solids().len(), 1);
let _ = std::fs::remove_dir_all(&dir);
}
/// New empties the model + marks it clean; an edit marks it dirty; saving
/// clears the dirty flag again and records the name.
#[test]
fn dirty_flag_flips_on_edit_and_clears_on_save() {
let dir = std::env::temp_dir().join(format!("brep-app-dirty-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let store = native_test_store(dir.clone());
let mut engine = EngineState::new();
engine
.set_history_json(
r#"{"features":[{"type":"P.CU","inputParams":{"id":"Box","sizeX":4.0,"sizeY":4.0,"sizeZ":4.0,"transform":{"position":[0,0,0],"rotationEuler":[0,0,0],"scale":[1,1,1]},"boolean":{"targets":[],"operation":"NONE"}}}]}"#,
)
.unwrap();
let mut dialog = FileDialog::new(&engine);
assert!(!dialog.is_dirty(&engine), "seeded model is clean");
// Edit a parameter → dirty.
engine
.update_feature_params(
"Box",
r#"{"id":"Box","sizeX":9.0,"sizeY":4.0,"sizeZ":4.0,"transform":{"position":[0,0,0],"rotationEuler":[0,0,0],"scale":[1,1,1]},"boolean":{"targets":[],"operation":"NONE"}}"#,
)
.unwrap();
assert!(dialog.is_dirty(&engine), "edit marks dirty");
// Save under a name (the Save As path) → clean, name recorded.
assert!(
dialog.save_to(&mut engine, &*store, "m".into()),
"save succeeds"
);
assert!(!dialog.is_dirty(&engine), "save clears dirty");
assert_eq!(dialog.current_name.as_deref(), Some("m"));
let _ = std::fs::remove_dir_all(&dir);
}
/// New on a DIRTY document opens the confirm modal (nothing cleared yet);
/// New on a CLEAN document clears immediately with no modal.
#[test]
fn new_confirms_only_when_dirty() {
let dir = std::env::temp_dir().join(format!("brep-app-newcfm-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let store = native_test_store(dir.clone());
let mut engine = EngineState::new();
engine
.set_history_json(
r#"{"features":[{"type":"P.CU","inputParams":{"id":"Box","sizeX":4.0,"sizeY":4.0,"sizeZ":4.0,"transform":{"position":[0,0,0],"rotationEuler":[0,0,0],"scale":[1,1,1]},"boolean":{"targets":[],"operation":"NONE"}}}]}"#,
)
.unwrap();
let mut dialog = FileDialog::new(&engine);
// Clean doc: New clears immediately, no modal.
dialog.dispatch(FileAction::New, &mut engine, &*store);
assert!(!dialog.open, "New on clean doc opens no modal");
assert_eq!(engine.history_len(), 0, "clean New cleared the history");
// Make it dirty, then New opens the confirm modal without clearing.
engine
.set_history_json(
r#"{"features":[{"type":"P.CU","inputParams":{"id":"Box","sizeX":4.0,"sizeY":4.0,"sizeZ":4.0,"transform":{"position":[0,0,0],"rotationEuler":[0,0,0],"scale":[1,1,1]},"boolean":{"targets":[],"operation":"NONE"}}}]}"#,
)
.unwrap();
assert!(dialog.is_dirty(&engine), "reseeded model is dirty vs empty baseline");
dialog.dispatch(FileAction::New, &mut engine, &*store);
assert!(dialog.open, "New on dirty doc opens the confirm modal");
assert_eq!(engine.history_len(), 1, "dirty New did NOT clear yet");
let _ = std::fs::remove_dir_all(&dir);
}
/// A plain Save on a never-named document routes through Save As: with no
/// name it opens the modal (nothing written); after a name is set + saved it
/// records the name and clears dirty.
#[test]
fn save_on_unnamed_falls_through_to_save_as_modal() {
let dir = std::env::temp_dir().join(format!("brep-app-unnamed-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let store = native_test_store(dir.clone());
let mut engine = EngineState::new();
engine
.set_history_json(
r#"{"features":[{"type":"P.CU","inputParams":{"id":"Box","sizeX":4.0,"sizeY":4.0,"sizeZ":4.0,"transform":{"position":[0,0,0],"rotationEuler":[0,0,0],"scale":[1,1,1]},"boolean":{"targets":[],"operation":"NONE"}}}]}"#,
)
.unwrap();
let mut dialog = FileDialog::new(&engine);
// Unnamed Save → Save As modal opens (feature-off native build).
dialog.dispatch(FileAction::Save, &mut engine, &*store);
assert!(dialog.open, "unnamed Save opens the Save As modal");
assert!(store.list().is_empty(), "nothing written yet");
// Provide a name + save.
assert!(dialog.save_to(&mut engine, &*store, "part".into()));
assert_eq!(dialog.current_name.as_deref(), Some("part"));
assert_eq!(store.list(), vec!["part".to_string()]);
let _ = std::fs::remove_dir_all(&dir);
}
/// A single-box model document, for the import/export lane tests.
const BOX_SEED: &str = r#"{"expressions":"","configurator":{},"features":[
{"type":"P.CU","inputParams":{"id":"Box","sizeX":8.0,"sizeY":8.0,"sizeZ":8.0,
"transform":{"position":[0,0,0],"rotationEuler":[0,0,0],"scale":[1,1,1]},
"boolean":{"targets":[],"operation":"NONE"}},"persistentData":{}}
]}"#;
/// STEP file names route to the import lane; extension-less model names (and
/// `.json` documents) do not — so the take_import poll never mis-routes.
#[test]
fn step_names_route_to_the_import_lane() {
assert!(is_step_name("part.step"));
assert!(is_step_name("PART.STP"));
assert!(!is_step_name("model"), "model docs arrive extension-less");
assert!(!is_step_name("model.json"));
}
/// Export dispatch opens the format chooser; choosing STEP / STL on a box
/// model serializes without error (the feature-off store's no-op interchange
/// still exercises the engine's STEP/STL text generation + `.ext` naming). An
/// empty model reports a clear guard rather than exporting.
#[test]
fn export_dispatch_and_chooser_serialize_the_model() {
let dir = std::env::temp_dir().join(format!("brep-app-export-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let store = native_test_store(dir.clone());
let mut engine = EngineState::new();
engine.set_history_json(BOX_SEED).unwrap();
let mut dialog = FileDialog::new(&engine);
dialog.dispatch(FileAction::Export, &mut engine, &*store);
assert!(dialog.open && dialog.mode == Mode::Export, "Export opens the chooser");
assert!(dialog.export_as(&engine, &*store, "step"), "STEP export ok");
assert!(dialog.status.contains("exported"), "status: {}", dialog.status);
assert!(dialog.export_as(&engine, &*store, "stl"), "STL export ok");
assert!(dialog.export_as(&engine, &*store, "json"), "JSON recipe export ok");
assert!(dialog.status.contains(".BREP.json"), "json status: {}", dialog.status);
let empty = EngineState::new();
assert!(!dialog.export_as(&empty, &*store, "step"), "empty model does not export");
assert!(dialog.status.contains("nothing to export"), "status: {}", dialog.status);
let _ = std::fs::remove_dir_all(&dir);
}
/// A STEP file routed to import is APPENDED to the model (an edit → dirty),
/// unlike Open which replaces + cleans. Uses the engine's own STEP export to
/// produce a valid document without a direct kernel dependency.
#[test]
fn import_step_appends_and_marks_dirty() {
let dir = std::env::temp_dir().join(format!("brep-app-imp-{}", std::process::id()));
let _ = std::fs::remove_dir_all(&dir);
let store = native_test_store(dir.clone());
// A box model → STEP text via the engine.
let mut source = EngineState::new();
source.set_history_json(BOX_SEED).unwrap();
let step = source.export_step_text().unwrap();
// A fresh (empty, clean) dialog imports it: one body appended, dirty.
let mut engine = EngineState::new();
let mut dialog = FileDialog::new(&engine);
assert!(!dialog.is_dirty(&engine), "empty seed is clean");
dialog.import_step(&mut engine, "part.step", &step);
assert_eq!(engine.history_len(), 1, "IMPORT3D feature appended");
assert_eq!(engine.scene.solids().len(), 1, "the imported body is in the scene");
assert!(dialog.is_dirty(&engine), "an import is an edit");
assert!(dialog.status.contains("imported"), "status: {}", dialog.status);
let _ = store; // store unused beyond construction (test stores never drive dialogs)
let _ = std::fs::remove_dir_all(&dir);
}
}