BREP_app 0.11.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
use super::*;
use crate::panels::plm_parts::{
    CreatedPart, NewPartRequest, PartCatalog, PartType, Pending, PlmPartCatalog,
};
use crate::plm::client::PlmClient;
use std::rc::Rc;

#[derive(Clone, Copy, Debug, Default, PartialEq)]
enum Destination {
    #[default]
    NewPart,
    NewRevision,
    Existing,
}

impl Destination {
    fn slug(self) -> &'static str {
        match self {
            Destination::NewPart => "new-part",
            Destination::NewRevision => "new-revision",
            Destination::Existing => "existing",
        }
    }
}

/// Where a Save As starts: on a PLM revision, a new revision of it; off one,
/// a new part; and from the family member hand-edit prompt's "Save as a new
/// part", a NEW PART whatever the document is named — never the generated
/// member's own revision (integrator ruling 2026-10-03). What the new part's
/// Name starts as. Not the tab's title: an untitled document's "untitled 2"
/// (or a revision's "CPART000000001/A") became the first part's name
/// whenever the user typed into the field rather than replacing it. Empty
/// for an untitled document (the field says what to type), the part's own
/// name for a PLM revision, the file's name otherwise.
fn new_part_name(doc: &crate::document::Document, store: &dyn ModelStore) -> String {
    let Some(name) = doc.name() else { return String::new() };
    match crate::panels::plm_host::revision_of(name) {
        Some((part, revision)) => store
            .plm_revision(&crate::plm::identity::document_key(&part, &revision))
            .map(|entry| entry.part_name)
            .unwrap_or_default(),
        None => doc.title(),
    }
}

fn initial_destination(member_new_part: bool, on_a_revision: bool) -> Destination {
    if member_new_part || !on_a_revision {
        Destination::NewPart
    } else {
        Destination::NewRevision
    }
}

/// The document a Save As writes. A copy that becomes a part of its own (a
/// new part, or another part's revision) carries no family stamp — the
/// generated member's `familySource` names the family that wrote the member,
/// and the copy is not it (what "Save as a new part" means, as the local Save
/// As has always done). The session document itself is not touched here: it
/// drops the stamp only once the copy has landed.
fn copy_document(document: &str, strip_family_stamp: bool) -> String {
    if !strip_family_stamp {
        return document.to_string();
    }
    match serde_json::from_str::<serde_json::Value>(document) {
        Ok(mut value) => {
            if let Some(object) = value.as_object_mut() {
                object.remove(family_table::FAMILY_SOURCE_KEY);
            }
            value.to_string()
        }
        Err(_) => document.to_string(),
    }
}

#[derive(Default)]
pub(super) struct SaveAs {
    document: u64,
    destination: Destination,
    part: String,
    revision: String,
    name: String,
    number: String,
    part_type: String,
    types: Vec<PartType>,
    loading: Option<Pending<Vec<PartType>>>,
    saving: Option<Pending<String>>,
    signature: Option<String>,
    snapshot: Option<String>,
    /// The copy being written carries no family stamp (see
    /// [`copy_document`]); once it lands, the session document drops its own.
    strip_stamp: bool,
    /// The tab's `derivedFrom` block before this Save As stamped it (`Some`
    /// only when it did): a failed save puts it back.
    prior_lineage: Option<Option<serde_json::Value>>,
}

impl SaveAs {
    /// What the automation state publishes about the open Save As.
    pub(super) fn state_json(&self) -> serde_json::Value {
        serde_json::json!({
            "destination": self.destination.slug(),
            "part": self.part,
            "revision": self.revision,
            "name": self.name,
            "number": self.number,
            "saving": self.saving.is_some(),
            "stripsFamilyStamp": self.strip_stamp,
        })
    }
}

/// Save the captured session copy, retaining checkout for subsequent Save.
/// A refusal leaves the caller's document and identity untouched.
async fn write_copy(client: &PlmClient, key: &str, document: &str) -> Result<(), String> {
    let (part, revision) =
        crate::panels::plm_host::revision_of(key).ok_or("choose a PLM revision")?;
    let base = crate::plm::identity::revision_path(&part, &revision);
    client
        .call(
            "POST",
            &format!("{base}/checkout"),
            Some(br#"{"client_id":"brep-app"}"#.to_vec()),
        )
        .await
        .map_err(|e| e.to_string())?;
    client
        .call(
            "PUT",
            &crate::plm::identity::doc_path(key),
            Some(document.as_bytes().to_vec()),
        )
        .await
        .map_err(|e| format!("{key} is checked out, but saving failed: {e}"))?;
    Ok(())
}

async fn save_copy(
    client: &PlmClient,
    destination: Destination,
    part: &str,
    revision: &str,
    request: NewPartRequest,
    document: &str,
    other_open: &[String],
) -> Result<String, String> {
    match destination {
        Destination::NewRevision => {
            crate::panels::plm_parts::save_as_new_revision(client, part, revision, document).await
        }
        Destination::NewPart => {
            let response = client
                .call(
                    "POST",
                    "/api/parts",
                    Some(serde_json::to_vec(&request).map_err(|e| e.to_string())?),
                )
                .await
                .map_err(|e| e.to_string())?;
            let created: CreatedPart =
                serde_json::from_slice(&response.body).map_err(|e| e.to_string())?;
            let key = created
                .first_revision_key()
                .ok_or("the new part has no revision")?;
            write_copy(client, &key, document).await?;
            Ok(key)
        }
        Destination::Existing => {
            let path = format!("/api/parts/{}", crate::plm::identity::segment(part));
            let response = client
                .call("GET", &path, None)
                .await
                .map_err(|e| e.to_string())?;
            let detail: serde_json::Value =
                serde_json::from_slice(&response.body).map_err(|e| e.to_string())?;
            let id = detail["id"]
                .as_str()
                .ok_or("the target part was not found")?;
            let revisions = detail["revisions"]
                .as_array()
                .ok_or("the target has no revisions")?;
            let target = if revision.is_empty() {
                revisions.last()
            } else {
                revisions.iter().find(|r| {
                    r["id"].as_str() == Some(revision) || r["label"].as_str() == Some(revision)
                })
            }
            .ok_or("the target revision was not found")?;
            let key = crate::plm::identity::document_key(
                id,
                target["id"]
                    .as_str()
                    .ok_or("the target revision has no id")?,
            );
            if other_open.contains(&key) {
                return Err("That revision is already open in another tab; save from that tab or choose another destination".into());
            }
            write_copy(client, &key, document).await?;
            Ok(key)
        }
    }
}

impl FileDialog {
    pub(super) fn poll_plm_save_as(
        &mut self,
        ctx: &egui::Context,
        docs: &mut Documents,
        store: &dyn ModelStore,
    ) {
        let Some(state) = self.plm_save_as.as_mut() else {
            return;
        };
        if state.saving.is_some() {
            ctx.request_repaint_after(std::time::Duration::from_millis(30));
        }
        if let Some(result) = state
            .saving
            .as_mut()
            .and_then(|p| p.poll(std::task::Waker::noop()))
        {
            state.saving = None;
            match result {
                Ok(key) => {
                    let name = store.canonical_identity(&key);
                    if let Some(snapshot) = state.snapshot.take() {
                        store.remember_saved_document(&name, &snapshot);
                    }
                    if let Some(doc) = docs.iter_mut().find(|d| d.id() == state.document) {
                        doc.set_name(Some(name.clone()));
                        doc.set_plm_save_access(crate::document::Access::Editable);
                        if state.strip_stamp {
                            // The tab is now the copy: a part of its own, no
                            // family stamp. Its clean baseline is the copy as
                            // saved — captured WITHOUT the stamp below — so an
                            // edit made while the save was in flight reads
                            // dirty, and undoing it back to the saved content
                            // reads clean.
                            doc.engine
                                .history
                                .set_document_block_no_undo(family_table::FAMILY_SOURCE_KEY, None);
                        }
                        if let Some(signature) = state.signature.take() {
                            doc.mark_saved_signature(signature);
                        }
                    }
                    store.refresh_plm_index(&[key], false);
                    self.save_generation += 1;
                    self.status = format!("saved {name}");
                    if self.mode == Mode::SaveAs {
                        self.open = false;
                    }
                    let document = state.document;
                    self.plm_save_as = None;
                    // The copy is a revision of its own now: parts it places
                    // that have no document of their own become PLM items in
                    // the same Save (never kept only inside the assembly), and
                    // parts it changed are written to their own items (checked
                    // out, or a new revision, through the one Save dialog):
                    // Save As writes only the assembly, and a changed copy left
                    // unwritten and unmarked is refreshed away at the next open.
                    let plan = (docs.active_id() == document).then(|| docs.plan_owned_save(store, &name));
                    if plan.is_some_and(|plan| !plan.promotions.is_empty() || !plan.rows.is_empty()) {
                        self.save_to(docs, store, name);
                    }
                    return;
                }
                Err(problem) => {
                    if let Some(prior) = state.prior_lineage.take() {
                        if let Some(doc) = docs.iter_mut().find(|d| d.id() == state.document) {
                            doc.engine.history.set_document_block_no_undo(
                                brep_render::engine_state::replace_component::DERIVED_FROM_KEY,
                                prior,
                            );
                        }
                    }
                    self.status =
                        format!("Save failed: {problem}. Your session edits are unchanged.")
                }
            }
        }
    }

    pub(super) fn show_save_as_plm(
        &mut self,
        ctx: &egui::Context,
        docs: &mut Documents,
        store: &dyn ModelStore,
        client: Rc<PlmClient>,
    ) {
        let id = docs.active_id();
        if self
            .plm_save_as
            .as_ref()
            .is_none_or(|s| s.document != id && s.saving.is_none())
        {
            let source = docs
                .active()
                .name()
                .and_then(crate::panels::plm_host::revision_of);
            let catalog = PlmPartCatalog::new(client.clone());
            let member_new_part = std::mem::take(&mut self.member_new_part);
            self.plm_save_as = Some(SaveAs {
                document: id,
                destination: initial_destination(member_new_part, source.is_some()),
                part: source.map(|(p, _)| p).unwrap_or_default(),
                name: new_part_name(docs.active(), store),
                loading: Some(Pending::new(catalog.part_types())),
                ..Default::default()
            });
        }
        self.member_new_part = false;
        let state = self.plm_save_as.as_mut().unwrap();
        if let Some(result) = state
            .loading
            .as_mut()
            .and_then(|p| p.poll(std::task::Waker::noop()))
        {
            state.loading = None;
            match result {
                Ok(types) => {
                    state.part_type = types
                        .iter()
                        .find(|t| t.id == "component")
                        .or(types.first())
                        .map(|t| t.id.clone())
                        .unwrap_or_default();
                    state.types = types;
                }
                Err(problem) => self.status = problem,
            }
        }
        let busy = state.saving.is_some();
        if busy || state.loading.is_some() {
            ctx.request_repaint_after(std::time::Duration::from_millis(30));
        }
        let mut save = false;
        // Every destination here writes to the PLM: an account that may not
        // is told before it fills anything in, and nothing is offered.
        let viewer = client.can_author() == Some(false);
        let modal = egui::Modal::new(egui::Id::new("brep-file-saveas")).show(ctx, |ui| {
            ui.heading("Save as");
            if viewer {
                let note = ui.colored_label(
                    ui.visuals().warn_fg_color,
                    format!("Not available: {}. Export keeps a copy as a file.", crate::document::owned_save::VIEW_ONLY),
                );
                self.hits.insert("saveas:view-only".into(), note.rect);
            }
            ui.add_enabled_ui(!busy && !viewer, |ui| {
                // The destination as one dropdown (the form's enum field):
                // saveas:destination, its open entries saveas:destination#new-revision,
                // #new-part and #existing.
                ui.horizontal(|ui| {
                    ui.label("Destination");
                    let choices = [
                        (Destination::NewRevision, "new-revision", "A new revision"),
                        (Destination::NewPart, "new-part", "A new part"),
                        (Destination::Existing, "existing", "An existing revision"),
                    ];
                    crate::form::enum_dropdown(ui, "saveas:destination", &choices, &mut state.destination, None, Some(&mut self.hits));
                });
                if state.destination == Destination::NewPart {
                    ui.label("Part type");
                    egui::ComboBox::from_id_salt("saveas:type")
                        .selected_text(&state.part_type)
                        .show_ui(ui, |ui| {
                            for t in &state.types {
                                ui.selectable_value(&mut state.part_type, t.id.clone(), &t.name);
                            }
                        });
                    for (label, field, key) in [
                        ("Name", &mut state.name, "saveas:name"),
                        (
                            "Number (blank for automatic numbering)",
                            &mut state.number,
                            "saveas:number",
                        ),
                    ] {
                        ui.label(label);
                        let hint = if key == "saveas:name" { "the new part's name" } else { "" };
                        let r = ui.add(egui::TextEdit::singleline(field).hint_text(hint));
                        self.hits.insert(key.into(), r.rect);
                    }
                } else {
                    ui.label("Part number");
                    let r = ui.text_edit_singleline(&mut state.part);
                    self.hits.insert("saveas:part".into(), r.rect);
                }
                ui.label(if state.destination == Destination::Existing {
                    "Revision (blank for newest)"
                } else {
                    "Revision label (blank for automatic)"
                });
                let r = ui.text_edit_singleline(&mut state.revision);
                self.hits.insert("saveas:revision".into(), r.rect);
                if state.destination == Destination::Existing {
                    ui.label(
                        "Check out this revision and replace its model with your session copy.",
                    );
                }
                let ready = if state.destination == Destination::NewPart {
                    !state.part_type.is_empty() && !state.name.trim().is_empty()
                } else {
                    !state.part.trim().is_empty()
                };
                let button = ui.add_enabled(ready, egui::Button::new("Save"));
                self.hits.insert("saveas:save".into(), button.rect);
                save = button.clicked();
            });
            if busy {
                ui.label("Saving…");
            }
            if !self.status.is_empty() {
                ui.label(&self.status);
            }
            let cancel = ui.button(if busy { "Keep editing" } else { "Cancel" });
            self.hits.insert("saveas:cancel".into(), cancel.rect);
            cancel.clicked()
        });
        if modal.inner || modal.should_close() {
            self.open = false;
            if !busy {
                self.plm_save_as = None;
            }
            return;
        }
        if save {
            // A copy that keeps the part's identity (its own next revision,
            // or its own existing one) keeps a member's family stamp; a copy
            // that becomes another part drops it.
            let source_part = docs
                .active()
                .name()
                .and_then(crate::panels::plm_host::revision_of)
                .map(|(part, _)| part)
                .unwrap_or_default();
            let keeps_identity = match state.destination {
                Destination::NewRevision => true,
                Destination::Existing => state.part.trim() == source_part,
                Destination::NewPart => false,
            };
            let stamped = docs
                .engine()
                .history
                .document_block(family_table::FAMILY_SOURCE_KEY)
                .is_some();
            state.strip_stamp = stamped && !keeps_identity;
            // A copy that becomes another part records where it came from
            // (Replace component trusts face names across that lineage).
            // Stamped on the tab BEFORE the baseline and the copy are taken,
            // so both carry it; a failed save restores the tab.
            if !keeps_identity {
                let key = brep_render::engine_state::replace_component::DERIVED_FROM_KEY;
                state.prior_lineage = Some(docs.engine().history.document_block(key).cloned());
                super::stamp_save_as_lineage(docs, store, "");
            }
            // A Save As writes the assembly alone, not the parts it changed:
            // their copies are marked as holding a change not saved to them
            // yet, so the copy (and the new revision holding it) says so, no
            // open refreshes it away, and the Save that follows the Save As
            // writes them through the one Save dialog.
            if let Some(current) = docs.active().name().map(str::to_string) {
                let id = docs.active_id();
                let plan = docs.plan_owned_save(store, &current);
                for row in plan.rows.iter().filter(|row| row.write.key != current) {
                    docs.mark_unsaved_copies(id, &row.write.key, "Save As wrote only the assembly");
                }
            }
            // The baseline of what is being saved: without the stamp when the
            // copy is written without it.
            state.signature = Some(if state.strip_stamp {
                docs.active().save_signature_without(family_table::FAMILY_SOURCE_KEY)
            } else {
                docs.active().save_signature()
            });
            let document = copy_document(&docs.tab_engine().history_request_json(), state.strip_stamp);
            state.snapshot = Some(document.clone());
            let other_open = docs
                .iter()
                .filter(|d| d.id() != id)
                .filter_map(|d| {
                    d.name()
                        .and_then(crate::panels::plm_host::revision_of)
                        .map(|(p, r)| crate::plm::identity::document_key(&p, &r))
                })
                .collect::<Vec<_>>();
            let (destination, part, revision) = (
                state.destination,
                state.part.trim().to_string(),
                state.revision.trim().to_string(),
            );
            let request = NewPartRequest {
                part_type: state.part_type.clone(),
                name: state.name.trim().into(),
                number: state.number.trim().into(),
                label: revision.clone(),
                document_class: document_class::document_class(docs.engine()).slug().into(),
                ..Default::default()
            };
            state.saving = Some(Pending::new(Box::pin(async move {
                save_copy(
                    &client,
                    destination,
                    &part,
                    &revision,
                    request,
                    &document,
                    &other_open,
                )
                .await
            })));
            self.status = "Saving…".into();
            ctx.request_repaint();
        }
    }
}