Skip to main content

brep_app/
form_view.rs

1//! Schema-driven form layout built on [`form::field_input`].
2//!
3//! The view edits parameter data and returns [`FormViewOut`] actions for the caller
4//! to apply after drawing. It takes no engine or document, so the app and capture
5//! tools can use the same layout without overlapping mutable engine borrows.
6//!
7//! Sections run from references and parameters through schema-ordered groups,
8//! followed by Transform and read-only sections. Transform and Outputs start
9//! collapsed. Reference selections stay visible below their activation button.
10//!
11//! Accordion and arrival-scroll state lives in egui memory keyed by the form's
12//! hit prefix, title, and section.
13
14use crate::form;
15use brep_render::style::{FieldKind, FormField};
16use eframe::egui;
17use serde_json::Value;
18use std::collections::{HashMap, HashSet};
19
20/// Groups that are drawn as a COLLAPSED accordion by default. `Transform` is the
21/// owner's explicit call (R6); the read-only trailing sections join it because
22/// they report, they do not edit. Everything else opens by default — a section
23/// the user must click to see is a section they will miss.
24const COLLAPSED_BY_DEFAULT: &[&str] = &["Transform", "Outputs"];
25
26/// Everything ABOUT the form that the consumer supplies. Borrowed; the form view
27/// holds no state of its own beyond egui memory.
28pub struct FormViewSpec<'a> {
29    /// The form's heading — e.g. `"E3  ⟠ Extrude"`. Also the scope key for this
30    /// form's transient view state and per-field widget ids, so it must be
31    /// STABLE and UNIQUE per subject (a feature id / constraint id qualifies).
32    pub title: &'a str,
33    /// An optional second line under the title (a status, a type name…).
34    pub subtitle: Option<&'a str>,
35    /// The schema fields to render, in schema order.
36    pub fields: &'a [FormField],
37    /// Field keys ([`FormField::key`]) to HIDE this frame — the schema-driven
38    /// field-visibility hook. A field whose key is in this set is dropped BEFORE
39    /// the fields are partitioned into sections, so a group left with nothing
40    /// visible draws no header. `None` (the common case) hides nothing. A feature
41    /// consumer fills this from [`brep_render::features::feature_hidden_params`]
42    /// against the LIVE params each frame, so it reacts to both first display and
43    /// every field change with no extra plumbing.
44    pub hidden: Option<&'a HashSet<String>>,
45    /// A message banner drawn under the title — e.g. the feature's run error.
46    pub banner: Option<(&'a str, egui::Color32)>,
47    /// Read-only sections appended after the fields — e.g. `[("Outputs", …)]`.
48    pub trailing: Option<&'a [(&'a str, Vec<String>)]>,
49    /// ONE consumer-drawn section `(title, drawer)` placed after the schema
50    /// groups and before the trailing sections — for a subject whose editing
51    /// surface the schema cannot express (a spline's anchor list). The drawer
52    /// is `Fn`, so anything it decides goes through interior mutability the
53    /// consumer owns; the form view stays intent-out like everything else here.
54    pub extra: Option<(&'a str, &'a dyn Fn(&mut egui::Ui))>,
55    /// The exit button's label — the button at the RIGHT end of the title row.
56    /// Both of today's consumers say "Return to tree" — the history feature list
57    /// and the constraint list are BOTH drawn by `panels::tree`, so the word is
58    /// literal, not a metaphor (Q12). A consumer whose list is NOT a tree
59    /// supplies its own wording here.
60    pub exit_label: &'a str,
61    /// Whether this consumer's subject lives in a ROLLED history — i.e. whether
62    /// LEAVING the form also means "roll the model back to the tip".
63    ///
64    /// The form view holds no engine and therefore cannot roll anything itself
65    /// (that is [`FormViewOut::roll_to_tip`], which the caller acts on). What
66    /// this flag does is decide, in ONE place, whether an exit *carries* that
67    /// intent — so no consumer has to hard-code "am I the history panel?" at its
68    /// exit arm. The history panel passes `true`; assembly constraints have no
69    /// rollback at all (the owner's call) and pass `false`, which is why their
70    /// panel has no roll branch to get wrong.
71    pub rollback: bool,
72    /// Prefix for every published hit key. `""` for a consumer that shows ONE
73    /// form at a time (history); a consumer that can show several at once MUST
74    /// pass a prefix carrying the subject id or the rects collide silently.
75    pub hits_prefix: &'a str,
76    /// Why the subject may not change (a PLM revision not checked out, or
77    /// released), or `None`. The fields then draw DISABLED under a banner
78    /// saying why, so nothing is typed that the engine would refuse and the
79    /// field's buffer would keep; the exit button stays live.
80    pub read_only: Option<&'a str>,
81}
82
83/// A reference field's `Select` was pressed — the caller dispatches this to its
84/// own picker flavour (`begin_ref_select` / `begin_ref_select_for_constraint`).
85#[derive(Debug, Clone, PartialEq)]
86pub struct RefActivate {
87    /// The JSON key chain the picked selection writes back into.
88    pub path: Vec<String>,
89    /// The field's label, for the picker's prompt.
90    pub label: String,
91    /// The schema's entity-kind filter (`["solid"]`, `["face"]`…).
92    pub filter: Vec<String>,
93    /// Whether the field accepts more than one entity.
94    pub multiple: bool,
95    /// The names already chosen — the picker lights them up as the seed.
96    pub seed: Vec<String>,
97}
98
99/// What the user did in one drawn frame of the form.
100#[derive(Debug, Default, Clone, PartialEq)]
101pub struct FormViewOut {
102    /// A field wrote into `params` — the caller commits the whole buffer.
103    pub changed: bool,
104    /// A [`FieldKind::Button`] field was clicked, by its key (`"editSketch"`).
105    pub button_clicked: Option<String>,
106    /// A reference field's `Select` was pressed.
107    pub ref_activate: Option<RefActivate>,
108    /// The title row's exit button was pressed — the caller returns to its list.
109    pub exit_clicked: bool,
110    /// The exit ALSO means "roll the model to the tip" — set only when the exit
111    /// button was pressed AND the consumer declared [`FormViewSpec::rollback`].
112    /// Always `false` for a consumer with no rollback, so its panel never needs
113    /// the branch.
114    pub roll_to_tip: bool,
115    /// The pointer is over a line that NAMES a scene entity — a reference line or
116    /// a read-only trailing line (`Outputs`). The caller feeds it to
117    /// `EngineState::hover_entity_by_name` so the entity lights in the 3D view
118    /// exactly as mousing over it there would, and calls
119    /// `EngineState::dialog_hover_end` when it is `None`.
120    pub hovered_entity: Option<String>,
121}
122
123/// Draw ONE complete schema-driven form into `ui`, editing `params` live, and
124/// return what the user did. `hits`, when supplied, receives the widget screen
125/// rects the headed verifier drives:
126///
127/// | key | what |
128/// |---|---|
129/// | `form:feature` | the title label |
130/// | `form:section:{Group}` | an accordion header |
131/// | `form:return` | the exit button, right end of the title row |
132/// | `field:{path}` | a field's input widget |
133/// | `field:{path}#{variant}` | an OPEN enum's items |
134/// | `field:{path}#activate` / `#x{i}` | a reference's Select / remove buttons |
135/// | `field:{path}#line{i}` | a reference's i-th chosen-entity line |
136/// | `form:trailing:{Section}:{i}` | a read-only section's i-th line (`Outputs`) |
137///
138/// all with `spec.hits_prefix` prepended.
139/// Padding INSIDE the form's container — the gap between the frame edge and the
140/// first/last widget on every side.
141const FORM_MARGIN: i8 = 10;
142
143/// Gap OUTSIDE the container, between it and the pane edge, so the frame's own
144/// stroke is not flush against the dock border.
145const FORM_OUTER_MARGIN: i8 = 6;
146
147pub fn form_view(
148    ui: &mut egui::Ui,
149    spec: &FormViewSpec<'_>,
150    params: &mut Value,
151    mut hits: Option<&mut HashMap<String, egui::Rect>>,
152) -> FormViewOut {
153    let mut out = FormViewOut::default();
154
155    // A form ARRIVES IN VIEW. Every consumer's pane is wrapped in the dock's
156    // `ScrollArea`, whose offset egui remembers PER PANE — so a form opened from
157    // a tree the user had scrolled down inherits that offset and starts part-way
158    // in, with the title row (and the exit button on it) above the viewport. The
159    // enclosing scroll area is asked to bring the CURSOR — which is the form's
160    // TOP EDGE here, before the container's own margins push it down — into
161    // view, ONCE per arrival: keyed on the subject AND on having been drawn on
162    // the previous pass, so re-opening the same subject after a trip back to the
163    // tree resets too, while scrolling INSIDE an open form sticks.
164    //
165    // WHERE this sits matters: inside the container it would align the first
166    // WIDGET, not the form, and leave the pane a margin's worth (measured: 14
167    // pt) past the form's own top edge and border. Out here the cursor IS that
168    // edge. The align is `None` — "only if it is not already visible" — rather
169    // than `Align::TOP`, so a pane already at the top computes a zero delta and
170    // asks for nothing at all, rather than a target that only happens to clamp
171    // back to where it was.
172    //
173    // (`form_view` cannot reach the scroll area itself — it is the consumer's,
174    // two levels out — and asking through the cursor is what keeps the required
175    // inputs at `(ui, spec, &mut params)` for the headless caller.)
176    let arrival = egui::Id::new(("form-view-arrival", spec.hits_prefix));
177    let pass = ui.ctx().cumulative_pass_nr();
178    let arrived = ui.ctx().memory_mut(|m| {
179        let previous: Option<(String, u64)> = m.data.get_temp(arrival);
180        let continuing = previous
181            .is_some_and(|(title, drawn)| title == spec.title && pass.saturating_sub(drawn) <= 1);
182        m.data.insert_temp(arrival, (spec.title.to_string(), pass));
183        !continuing
184    });
185    if arrived {
186        // INSTANT, not animated: the reset must land before the frame the user
187        // sees, and a dialog gliding into place on every open is noise.
188        ui.scroll_to_cursor_animation(None, egui::style::ScrollAnimation::none());
189    }
190
191    // The whole form sits inside ONE padded container, so the fields never run
192    // flush against the pane edge the way the inline tree rendering did. The
193    // margin is the frame's, not per-widget spacing: a single container keeps
194    // the label-above-full-width rhythm intact when the pane is resized, and
195    // gives the scroll region a consistent inset on every side.
196    egui::Frame::group(ui.style())
197        .inner_margin(egui::Margin::same(FORM_MARGIN))
198        .outer_margin(egui::Margin::same(FORM_OUTER_MARGIN))
199        .show(ui, |ui| {
200            form_body(ui, spec, params, &mut hits, &mut out);
201        });
202
203    out
204}
205
206/// The form's contents, drawn INSIDE the padded container opened by
207/// [`form_view`]. Split out so the container owns the margin in one place
208/// rather than every section adding its own edge spacing.
209fn form_body(
210    ui: &mut egui::Ui,
211    spec: &FormViewSpec<'_>,
212    params: &mut Value,
213    hits: &mut Option<&mut HashMap<String, egui::Rect>>,
214    out: &mut FormViewOut,
215) {
216    // Fill the container's width so full-width inputs stay full width.
217    ui.set_width(ui.available_width());
218
219    // --- heading + the ONE exit button, on one row -------------------------
220    // No OK/Cancel pair and no buffer: editing is LIVE (every change commits and
221    // re-runs) and UNDO is the revert mechanism, so there is nothing for a
222    // Cancel to roll back that undo does not already cover.
223    //
224    // The exit is allocated FIRST, from the RIGHT edge, and the title takes what
225    // is left over: a right-to-left row measures the button before the heading
226    // exists, so no title — however long — can push the button off the pane, and
227    // the heading truncates into the remainder instead of running under it. (The
228    // reverse order, title-then-button, is exactly the layout that loses the
229    // button on a long feature name.)
230    ui.horizontal(|ui| {
231        ui.with_layout(egui::Layout::right_to_left(egui::Align::Center), |ui| {
232            let exit = ui.button(spec.exit_label);
233            publish(spec, hits, "form:return", exit.rect);
234            out.exit_clicked = exit.clicked();
235            // The exit's rollback half, gated by the consumer's declaration —
236            // see [`FormViewSpec::rollback`].
237            out.roll_to_tip = out.exit_clicked && spec.rollback;
238            // Back to reading order for the title, inside whatever width the
239            // button left behind.
240            ui.with_layout(egui::Layout::left_to_right(egui::Align::Center), |ui| {
241                let head = ui.add(
242                    egui::Label::new(egui::RichText::new(spec.title).heading()).truncate(),
243                );
244                publish(spec, hits, "form:feature", head.rect);
245            });
246        });
247    });
248    if let Some(subtitle) = spec.subtitle {
249        ui.label(egui::RichText::new(subtitle).weak());
250    }
251    ui.separator();
252
253    // --- banner: the subject's error, ABOVE the fields ---------------------
254    // (The history tree ALSO keeps this on the feature's row, so a failure is
255    // still visible while scanning the tree — see the panel.)
256    if let Some((text, color)) = spec.banner {
257        egui::Frame::group(ui.style())
258            .stroke(egui::Stroke::new(1.0, color))
259            .fill(color.gamma_multiply(0.12))
260            .show(ui, |ui| {
261                ui.set_width(ui.available_width());
262                ui.add(
263                    egui::Label::new(egui::RichText::new(text).color(color))
264                        .wrap_mode(egui::TextWrapMode::Wrap),
265                );
266            });
267        ui.add_space(4.0);
268    }
269
270    // --- read-only: say why, and take no edit below this line ------------
271    if let Some(reason) = spec.read_only {
272        egui::Frame::group(ui.style())
273            .stroke(egui::Stroke::new(1.0, ui.visuals().weak_text_color()))
274            .show(ui, |ui| {
275                ui.set_width(ui.available_width());
276                let said = ui.add(egui::Label::new(format!("Read-only: {reason}")).wrap_mode(egui::TextWrapMode::Wrap));
277                publish(spec, hits, "form:read-only", said.rect);
278            });
279        ui.add_space(4.0);
280        ui.disable();
281    }
282
283    // --- partition the schema into direct params + grouped sections --------
284    let mut references: Vec<&FormField> = Vec::new();
285    let mut param_leaves: Vec<&FormField> = Vec::new();
286    let mut groups: Vec<(&str, Vec<&FormField>)> = Vec::new();
287    for f in spec.fields {
288        // The field-visibility hook: a hidden field is dropped here, before the
289        // partition, so it never reaches a section — and an emptied group never
290        // draws a bare header. Evaluated fresh each frame against the live params
291        // by the consumer, this is what makes fields show/hide as the field that
292        // governs them (e.g. a hole's type) changes.
293        if spec.hidden.is_some_and(|h| h.contains(f.key())) {
294            continue;
295        }
296        match f.group.as_str() {
297            "References" => references.push(f),
298            "Parameters" => {
299                if matches!(f.kind, FieldKind::Text { read_only: true }) {
300                    continue; // the subject id — already the form's title
301                }
302                param_leaves.push(f);
303            }
304            group => match groups.iter_mut().find(|(name, _)| *name == group) {
305                Some(existing) => existing.1.push(f),
306                None => groups.push((group, vec![f])),
307            },
308        }
309    }
310    // Transform trails the other groups: it is the one the owner named as the
311    // collapsed accordion, so it belongs at the bottom, not between two open
312    // sections.
313    groups.sort_by_key(|(name, _)| usize::from(*name == "Transform"));
314
315    // (1) references, then (2) plain parameters — both un-sectioned, because a
316    // section over the fields the user came here to edit is a click in the way.
317    for f in references.iter().chain(param_leaves.iter()) {
318        draw_field(ui, spec, f, params, hits, out);
319    }
320
321    // (3) the remaining groups, each an accordion.
322    for (name, fields) in &groups {
323        section(ui, spec, name, hits, |ui, hits| {
324            for f in fields {
325                draw_field(ui, spec, f, params, hits, out);
326            }
327        });
328    }
329
330    // (4) the consumer's own section, when it has one.
331    if let Some((name, draw)) = spec.extra {
332        section(ui, spec, name, hits, |ui, _hits| draw(ui));
333    }
334
335    // (5) read-only trailing sections (Outputs…).
336    //
337    // These lines NAME scene entities too (a feature's output solids), so they
338    // report a hover exactly as a reference line does — the section is read-only
339    // in the sense that it edits nothing, not that it is inert.
340    let mut trailing_hover: Option<String> = None;
341    for (name, values) in spec.trailing.unwrap_or(&[]) {
342        section(ui, spec, name, hits, |ui, hits| {
343            if values.is_empty() {
344                ui.label(egui::RichText::new("(none)").weak());
345            }
346            for (i, value) in values.iter().enumerate() {
347                let line = ui.label(format!("• {value}"));
348                if line.hovered() {
349                    trailing_hover = Some(value.clone());
350                }
351                publish(spec, hits, &format!("form:trailing:{name}:{i}"), line.rect);
352            }
353        });
354    }
355    if trailing_hover.is_some() {
356        out.hovered_entity = trailing_hover;
357    }
358
359    // Breathing room UNDER the last thing in the form, so the final section's
360    // widgets are not flush against (and, once egui rounds their rects to
361    // physical pixels, a hair past) the pane's clip edge — which is exactly
362    // where a click stops landing.
363    ui.add_space(8.0);
364}
365
366/// Record one widget rect under `spec.hits_prefix`.
367fn publish(
368    spec: &FormViewSpec<'_>,
369    hits: &mut Option<&mut HashMap<String, egui::Rect>>,
370    key: &str,
371    rect: egui::Rect,
372) {
373    if let Some(map) = hits.as_deref_mut() {
374        map.insert(format!("{}{key}", spec.hits_prefix), rect);
375    }
376}
377
378/// One collapsible section: a header row that publishes `form:section:{name}`
379/// and, when open, `body`. Open/collapsed lives in egui memory, keyed to this
380/// form's subject, so two features' Transform sections remember separately and
381/// the caller carries no state.
382fn section(
383    ui: &mut egui::Ui,
384    spec: &FormViewSpec<'_>,
385    name: &str,
386    hits: &mut Option<&mut HashMap<String, egui::Rect>>,
387    body: impl FnOnce(&mut egui::Ui, &mut Option<&mut HashMap<String, egui::Rect>>),
388) {
389    ui.add_space(6.0);
390    let open = !COLLAPSED_BY_DEFAULT.contains(&name);
391    let response = egui::CollapsingHeader::new(egui::RichText::new(name).strong())
392        .id_salt(("form-view-section", spec.hits_prefix, spec.title, name))
393        .default_open(open)
394        .show(ui, |ui| body(ui, hits));
395    publish(
396        spec,
397        hits,
398        &format!("form:section:{name}"),
399        response.header_response.rect,
400    );
401}
402
403/// Draw ONE schema field: its label, then the input at FULL WIDTH beneath it.
404/// A `Reference` is the same shape — [`form::field_input`] draws its activation
405/// button and the chosen entities under this same label.
406fn draw_field(
407    ui: &mut egui::Ui,
408    spec: &FormViewSpec<'_>,
409    field: &FormField,
410    params: &mut Value,
411    hits: &mut Option<&mut HashMap<String, egui::Rect>>,
412    out: &mut FormViewOut,
413) {
414    let mut probe: HashMap<String, egui::Rect> = HashMap::new();
415    let mut rect = egui::Rect::NOTHING;
416    let mut actions = form::FieldActions::default();
417    ui.add_space(4.0);
418    // A `Button` field IS its own label (the schema gives it one), so a label
419    // above it would say the same thing twice.
420    if !matches!(field.kind, FieldKind::Button { .. }) {
421        ui.label(&field.label);
422    }
423    // Scope the widget id-stack to THIS (subject, field) so a Scalar's
424    // per-location egui-memory edit buffer (and its TextEdit focus id) can't
425    // collide when two subjects share a param name — switching between two
426    // extrudes mid-edit must not hand one's half-typed `distance` to the other.
427    // `make_persistent_id` folds in the ui id-stack only.
428    ui.push_id((spec.title, field.key()), |ui| {
429        let (changed, r) = form::field_input(ui, field, params, Some(&mut probe), &mut actions);
430        out.changed |= changed;
431        rect = r;
432    });
433    if let Some(map) = hits.as_deref_mut() {
434        let prefix = spec.hits_prefix;
435        map.insert(format!("{prefix}field:{}", field.path.join(".")), rect);
436        for (key, r) in probe {
437            map.insert(format!("{prefix}field:{key}"), r);
438        }
439    }
440    // A hovered reference LINE names an entity; the form's consumer owns lighting
441    // it (that needs the engine). One line is under the pointer at a time, so the
442    // last field to report wins — and only one ever reports.
443    if actions.hovered_entity.is_some() {
444        out.hovered_entity = actions.hovered_entity.take();
445    }
446    // `field_input` reports the two ACTION kinds through the same out-param, by
447    // field key; which intent it is comes from the field's own kind.
448    if actions.clicked.is_some() {
449        match &field.kind {
450            FieldKind::Reference { filter, multiple } => {
451                out.ref_activate = Some(RefActivate {
452                    path: field.path.clone(),
453                    label: field.label.clone(),
454                    filter: filter.clone(),
455                    multiple: *multiple,
456                    seed: form::reference_names(form::value_at(params, &field.path)),
457                });
458            }
459            _ => out.button_clicked = actions.clicked.take(),
460        }
461    }
462}
463