Skip to main content

brep_app/panels/
sheets.rs

1//! The Sheets panel — the drawing sheets of the document as a TREE on the
2//! shared [`crate::column_tree`] widget: one row per sheet, its placed views
3//! as children, and — when a sheet or a placement is open — that object's
4//! dialog through the SHARED [`crate::form_view`] (the same function the
5//! feature, constraint and PMI annotation dialogs use; the schema comes from
6//! `brep_render::sheets::schema_catalogue`, so neither form is hand-written).
7//!
8//! # Tree mode
9//!
10//! Header: **Add sheet** (a new sheet at the default paper size, opened in the
11//! sheet viewport), **+ Place view** (one entry per saved PMI view — placing
12//! is gated on having a sheet AND a view to place), and a summary.
13//!
14//! Rows: a SHEET row shows its name (editable — rename in place), its paper
15//! size in millimetres, how many views it places and an **open** toggle (the
16//! sheet viewport draws the open sheet; unticking returns to the 3D view); a
17//! click opens it in the sheet viewport — the open sheet is the selected one —
18//! and a double click opens the sheet's dialog; its menu offers Edit sheet and
19//! Delete. A PLACED VIEW row shows its id, the saved view it places with its
20//! scale, its position, whether its text is `flat` on the sheet or
21//! `projected`, and its status — ✓ with the count of drawn edges and
22//! annotations, or ✕ with the reason it did not project (a deleted view, a
23//! camera this slice cannot draw).
24//!
25//! Every row a sheet HOLDS — a placement, a dimension, an ordinate set — is
26//! picked the same way: a click SELECTS it (the row, and the object on the
27//! paper, carry the selection) and a double click opens its form.
28//!
29//! Every row's menu is ALSO the right-click menu of its object on the paper
30//! (`viewport/sheet.rs`), bare paper opening the sheet's: [`object_actions`]
31//! is the one list and [`run_row_action`] the one dispatch, so the two cannot
32//! drift. The Delete key removes the selected held object through its menu's
33//! destructive entry ([`delete_held_object`], driven by the app shell).
34//!
35//! A SHEET DIMENSION row sits under the placements of the same sheet — a
36//! dimension belongs to the PAPER, not to any one placement, so it is a child
37//! of the sheet — and shows its id, what it measures (its alignment or its
38//! kind), how many anchors it has and the VALUE it read, with ✓ or the reason
39//! it did not resolve. Its form carries the kind, the alignment, the anchors as
40//! reference rows, the offset and the precision; the rows' **Select** opens the
41//! reference picker — the modal every dialog's reference rows open — whose
42//! picks are anchors clicked on the paper, and **Finish** writes them here.
43//! Every reference row of every sheet object works that way: an ordinate
44//! set's datum and members, a section's cutting line, a detail's centre and
45//! rim. A SECTION and a DETAIL have forms of their own for that reason
46//! (`sectionView`, `detailView`): a plain placement has nothing to pick.
47//!
48//! The SHEET's dialog ends with a **Revisions** section: the sheet's revision
49//! rows, each a letter, a date and a description edited in place, with a ✕
50//! to remove a row and **+ Add revision** under them. A list of records is a
51//! surface the schema vocabulary cannot express, so it is the form's one
52//! consumer-drawn section (`FormViewSpec::extra`, the spline editor's anchor
53//! list is the other) — every edit still goes through the engine's revision
54//! doors, and the rows keep the order they were added in.
55//!
56//! **Flatten text** is a checkbox of the placement's own FORM
57//! (`sheets:field:flattenText`, from the schema like every other field)
58//! rather than a column of the tree: the shared column tree gates its editors
59//! on the whole ROW, and a placement row is not editable — its name is its
60//! id. The row says which way the toggle is set; the form is where it moves.
61//!
62//! # Form mode
63//!
64//! Which object is open is the ENGINE's `sheet_open_object` (a mode, not model
65//! state) — a click on an object on the sheet viewport's paper opens one without going
66//! through here, so the mode is read, never owned. Editing is LIVE and
67//! **Return to tree** closes the form.
68//!
69//! Everything the panel knows comes from the engine (`sheet_state`,
70//! `sheet_drawing`); this struct holds the widget's transient state only.
71
72use crate::automation::hit_keys::HitKeyDoc;
73use crate::column_tree::{self, CellKind, ColumnLayout, ColumnSpec, ColumnTreeSpec, RowAction, RowNode};
74use crate::form_view::{form_view, FormViewSpec};
75use brep_render::engine_state::EngineState;
76use brep_render::features::form_fields_from_schema;
77use brep_render::sheets::SheetState;
78use eframe::egui;
79use serde_json::Value;
80use std::collections::{HashMap, HashSet};
81
82const NAME: &str = "name";
83const KIND: &str = "kind";
84const VALUE: &str = "value";
85const STATUS: &str = "status";
86const ON: &str = "on";
87const ACTIONS: &str = "actions";
88
89const OK_COLOR: &str = "#3fb950";
90const ERROR_COLOR: &str = "#f85149";
91const ACTIVE_COLOR: &str = "#58a6ff";
92const MUTED_COLOR: &str = "#8b949e";
93
94/// Row-menu action ids.
95const ACT_OPEN: &str = "open";
96const ACT_CLOSE: &str = "close";
97const ACT_EDIT: &str = "edit";
98const ACT_DELETE_SHEET: &str = "delete-sheet";
99const ACT_DELETE_VIEW: &str = "delete-view";
100const ACT_DELETE_DIM: &str = "delete-dimension";
101const ACT_DELETE_ORD: &str = "delete-ordinate";
102
103/// A deferred engine mutation (one per frame).
104enum Action {
105    AddSheet,
106    PlaceView(String),
107    Rename(String, String),
108    Open(Option<String>),
109    Edit(Option<String>),
110    /// A single click on a placement, dimension or ordinate row.
111    Select(String),
112    DeleteSheet(String),
113    DeleteView(String),
114    DeleteDimension(String),
115    UpdateSheet(String, Value),
116    UpdateView(String, Value),
117    UpdateDimension(String, Value),
118    DeleteOrdinate(String),
119    UpdateOrdinate(String, Value),
120    /// A reference row's **Select** — a dimension's anchors, an ordinate set's
121    /// datum or members, a section's cutting line, a detail's centre or rim:
122    /// the reference picker, on the paper, the modal every dialog's reference
123    /// rows open.
124    BeginRefSelect {
125        id: String,
126        path: Vec<String>,
127        label: String,
128        filter: Vec<String>,
129        multiple: bool,
130        seed: Vec<String>,
131    },
132    /// The sheet dialog's Revisions section: append a row…
133    AddRevision(String),
134    /// …edit one field of row `n`…
135    UpdateRevision(String, usize, Value),
136    /// …or remove row `n`.
137    RemoveRevision(String, usize),
138}
139
140/// What the Revisions section asked for this frame. Recorded by the drawer
141/// (which runs inside the form view and holds no engine) and turned into an
142/// [`Action`] once the form has drawn.
143enum RevisionIntent {
144    Add,
145    Update(usize, &'static str, String),
146    Remove(usize),
147}
148
149/// Drive the engine for one deferred [`Action`]. A refusal comes back as the
150/// engine's own message, which the caller turns into a notice.
151fn apply(state: &mut EngineState, action: Action) -> Result<(), String> {
152    match action {
153        Action::AddSheet => {
154            state.sheet_add(None);
155            Ok(())
156        }
157        Action::PlaceView(view) => state.sheet_place_view(None, &view, None, None).map(|_| ()),
158        Action::Rename(id, name) => {
159            state.sheet_update(&id, &serde_json::json!({ "name": name }).to_string())
160        }
161        Action::Open(id) => state.sheet_set_open(id.as_deref()),
162        Action::Edit(id) => {
163            state.sheet_set_object_open(id.as_deref());
164            Ok(())
165        }
166        Action::Select(id) => {
167            state.sheet_select_object(Some(&id));
168            Ok(())
169        }
170        Action::DeleteSheet(id) => state.sheet_delete(&id),
171        Action::DeleteView(id) => state.sheet_remove_view(&id),
172        Action::DeleteDimension(id) => state.sheet_remove_dimension(&id),
173        Action::UpdateSheet(id, params) => state.sheet_update(&id, &params.to_string()),
174        Action::UpdateView(id, params) => state.sheet_update_view(&id, &params.to_string()),
175        Action::UpdateDimension(id, params) => {
176            state.sheet_update_dimension(&id, &params.to_string())
177        }
178        Action::DeleteOrdinate(id) => state.sheet_remove_ordinate(&id),
179        Action::UpdateOrdinate(id, params) => {
180            state.sheet_update_ordinate(&id, &params.to_string())
181        }
182        Action::BeginRefSelect { id, path, label, filter, multiple, seed } => {
183            state.begin_ref_select_for_sheet(&id, path, label, filter, multiple, seed)
184        }
185        Action::AddRevision(id) => state.sheet_add_revision(&id, None, None, None).map(|_| ()),
186        Action::UpdateRevision(id, index, params) => {
187            state.sheet_update_revision(&id, index, &params.to_string())
188        }
189        Action::RemoveRevision(id, index) => state.sheet_remove_revision(&id, index),
190    }
191}
192
193/// A SHEET row's menu. `is_open` flips the first entry between Open and
194/// Close.
195fn sheet_actions(is_open: bool) -> Vec<RowAction> {
196    vec![
197        if is_open {
198            RowAction::new(ACT_CLOSE, "Close sheet").tooltip("Return the viewport to the 3D model")
199        } else {
200            RowAction::new(ACT_OPEN, "Open sheet").tooltip("Draw this sheet in the viewport")
201        },
202        RowAction::new(ACT_EDIT, "Edit sheet").tooltip("Name and paper size"),
203        RowAction::new(ACT_DELETE_SHEET, "Delete sheet").separator_above().destructive(),
204    ]
205}
206
207/// A PLACED VIEW row's menu — a plain placement, a section or a detail alike.
208fn placement_actions() -> Vec<RowAction> {
209    vec![
210        RowAction::new(ACT_EDIT, "Edit placement").tooltip("Which view, where, at what scale, whether its text lies flat on the sheet, and — on a section or a detail — its letter"),
211        RowAction::new(ACT_DELETE_VIEW, "Remove from sheet").separator_above().destructive(),
212    ]
213}
214
215/// A SHEET DIMENSION row's menu.
216fn dimension_actions() -> Vec<RowAction> {
217    vec![
218        RowAction::new(ACT_EDIT, "Edit dimension").tooltip("Kind, anchors, offset, precision and tolerance"),
219        RowAction::new(ACT_DELETE_DIM, "Remove dimension").separator_above().destructive(),
220    ]
221}
222
223/// An ORDINATE SET row's menu.
224fn ordinate_actions() -> Vec<RowAction> {
225    vec![
226        RowAction::new(ACT_EDIT, "Edit ordinate set").tooltip("Axis, datum, members, baseline offset and precision"),
227        RowAction::new(ACT_DELETE_ORD, "Remove ordinate set").separator_above().destructive(),
228    ]
229}
230
231/// The menu of the tree row standing for `id` — a sheet, a placement, a
232/// dimension or an ordinate set — or nothing for an id that names none.
233///
234/// This is what the row's `⋯` opens, and what a right-click on the same
235/// object on the PAPER opens (`viewport/sheet.rs`): one list, so the two
236/// cannot offer different things.
237pub(crate) fn object_actions(sheets: &SheetState, open_sheet: Option<&str>, id: &str) -> Vec<RowAction> {
238    if sheets.find_sheet(id).is_some() {
239        sheet_actions(open_sheet == Some(id))
240    } else if sheets.locate_view(id).is_some() {
241        placement_actions()
242    } else if sheets.locate_dimension(id).is_some() {
243        dimension_actions()
244    } else if sheets.locate_ordinate(id).is_some() {
245        ordinate_actions()
246    } else {
247        Vec::new()
248    }
249}
250
251/// What a row-menu entry does: `action` is one of the ids [`object_actions`]
252/// declares, on the row `id`.
253fn menu_action(id: String, action: &str) -> Option<Action> {
254    match action {
255        ACT_OPEN => Some(Action::Open(Some(id))),
256        ACT_CLOSE => Some(Action::Open(None)),
257        ACT_EDIT => Some(Action::Edit(Some(id))),
258        ACT_DELETE_SHEET => Some(Action::DeleteSheet(id)),
259        ACT_DELETE_VIEW => Some(Action::DeleteView(id)),
260        ACT_DELETE_DIM => Some(Action::DeleteDimension(id)),
261        ACT_DELETE_ORD => Some(Action::DeleteOrdinate(id)),
262        _ => None,
263    }
264}
265
266/// Run the menu entry `action` of the row standing for `id` — the dispatch
267/// the tree's menu and the paper's right-click menu share. An unknown entry
268/// does nothing.
269pub(crate) fn run_row_action(state: &mut EngineState, id: &str, action: &str) -> Result<(), String> {
270    menu_action(id.to_string(), action).map_or(Ok(()), |action| apply(state, action))
271}
272
273/// Delete what a sheet HOLDS — a placement, a dimension or an ordinate set —
274/// through its own menu's destructive entry: the Delete key on a selected
275/// object. A SHEET is never deleted this way (it takes everything placed on it
276/// with it), and an id that names nothing a sheet holds refuses.
277pub(crate) fn delete_held_object(state: &mut EngineState, id: &str) -> Result<(), String> {
278    let sheets = state.sheet_state();
279    let entry = if sheets.locate_view(id).is_some() {
280        ACT_DELETE_VIEW
281    } else if sheets.locate_dimension(id).is_some() {
282        ACT_DELETE_DIM
283    } else if sheets.locate_ordinate(id).is_some() {
284        ACT_DELETE_ORD
285    } else {
286        return Err(format!("no placed view, dimension or ordinate set '{id}'"));
287    };
288    run_row_action(state, id, entry)
289}
290
291/// The panel's transient UI state.
292pub struct SheetsPanel {
293    hits: HashMap<String, egui::Rect>,
294    layout: ColumnLayout,
295    columns: Vec<ColumnSpec>,
296    /// Sheets collapsed in the tree (every sheet starts expanded).
297    collapsed: HashSet<String>,
298}
299
300impl Default for SheetsPanel {
301    fn default() -> Self {
302        Self::new()
303    }
304}
305
306impl SheetsPanel {
307    pub fn new() -> Self {
308        Self {
309            hits: HashMap::new(),
310            layout: ColumnLayout::default(),
311            columns: vec![
312                ColumnSpec::new(NAME, "Sheet / view", CellKind::Text).width(140.0),
313                ColumnSpec::new(KIND, "", CellKind::Badges).width(28.0),
314                ColumnSpec::new(VALUE, "Paper / placement", CellKind::ReadOnly).width(170.0),
315                ColumnSpec::new(STATUS, "", CellKind::Badges).width(28.0),
316                ColumnSpec::new(ON, "Open", CellKind::Toggle).width(36.0),
317                ColumnSpec::new(ACTIONS, "", CellKind::Actions { label: "\u{22EF}".into() }).width(30.0),
318            ],
319            collapsed: HashSet::new(),
320        }
321    }
322
323    /// Draw the panel: the open object's form, else the sheet tree.
324    pub fn show(&mut self, ui: &mut egui::Ui, state: &mut EngineState) {
325        self.hits.clear();
326        self.hits.insert("sheets:panel:clip".into(), ui.clip_rect());
327        let sheets = state.sheet_state();
328        let open_sheet = state.sheet_open().map(String::from);
329        let open_object = state.sheet_open_object().map(String::from);
330        let selected = state.sheet_selected_object().map(String::from);
331        let view_ids = state.sheet_pmi_view_ids();
332
333        let mut action: Option<Action> = None;
334        let mut close = false;
335        match open_object.as_deref() {
336            Some(id) if sheets.find_sheet(id).is_some() => {
337                let sheet = sheets.find_sheet(id).expect("just matched").clone();
338                self.show_form(ui, state, &sheet.id, "Sheet", &sheet.params(), 0, None, &mut action, &mut close);
339            }
340            Some(id) if sheets.locate_view(id).is_some() => {
341                let placed = sheets
342                    .sheets
343                    .iter()
344                    .find_map(|sheet| sheet.find_view(id))
345                    .expect("just located")
346                    .clone();
347                // A section and a detail are placements with forms of their
348                // own: their picked references are rows there, and a plain
349                // placement has none.
350                let (label, index) = match placed.schema_type() {
351                    "sectionView" => ("Section view", 4),
352                    "detailView" => ("Detail view", 5),
353                    _ => ("Placed view", 1),
354                };
355                self.show_form(ui, state, &placed.id, label, &placed.params(), index, None, &mut action, &mut close);
356            }
357            Some(id) if sheets.locate_dimension(id).is_some() => {
358                let dimension = sheets.find_dimension(id).expect("just located").clone();
359                // A dimension that writes a PMI dimension's tolerance block says
360                // so at the top of its form: its own four fields read `none`,
361                // and the value on the paper does not.
362                let inherited = sheets
363                    .locate_dimension(id)
364                    .and_then(|(sheet, _)| state.sheet_drawing_cached(&sheet))
365                    .and_then(|drawing| drawing.dimensions.iter().find(|drawn| drawn.id == dimension.id))
366                    .filter(|drawn| !drawn.tolerance_from.is_empty())
367                    .map(|drawn| {
368                        format!(
369                            "Tolerance from PMI dimension {}: {} \u{2014} set one here to override it",
370                            drawn.tolerance_from, drawn.text
371                        )
372                    });
373                self.show_form(ui, state, &dimension.id, "Sheet dimension", &dimension.params(), 2, inherited.as_deref(), &mut action, &mut close);
374            }
375            Some(id) if sheets.locate_ordinate(id).is_some() => {
376                let set = sheets.find_ordinate(id).expect("just located").clone();
377                self.show_form(ui, state, &set.id, "Ordinate set", &set.params(), 3, None, &mut action, &mut close);
378            }
379            // A stale mode (the object was deleted elsewhere) falls back to
380            // the tree rather than an empty pane.
381            _ => self.show_tree(ui, state, &sheets, open_sheet.as_deref(), selected.as_deref(), &view_ids, &mut action),
382        }
383
384        let result = action.map_or(Ok(()), |action| apply(state, action));
385        if let Err(error) = result {
386            state.push_notice(format!("Sheets: {error}"));
387        }
388        if close {
389            state.sheet_set_object_open(None);
390        }
391    }
392
393    #[allow(clippy::too_many_arguments)]
394    fn show_tree(
395        &mut self,
396        ui: &mut egui::Ui,
397        state: &mut EngineState,
398        sheets: &SheetState,
399        open_sheet: Option<&str>,
400        selected: Option<&str>,
401        view_ids: &[String],
402        action: &mut Option<Action>,
403    ) {
404        // --- header -------------------------------------------------------------
405        ui.horizontal_wrapped(|ui| {
406            let add = ui
407                .add(crate::icon_text::icon_button(ui, "\u{1F5CB} Add sheet"))
408                .on_hover_text("Add an A3 sheet and open it in the sheet viewport");
409            self.hits.insert("sheets:add".into(), add.rect);
410            if add.clicked() {
411                *action = Some(Action::AddSheet);
412            }
413            let can_place = !sheets.sheets.is_empty() && !view_ids.is_empty();
414            let mut place: Option<String> = None;
415            ui.add_enabled_ui(can_place, |ui| {
416                let combo = egui::ComboBox::from_id_salt("sheets-place")
417                    .selected_text("+ Place view")
418                    .show_ui(ui, |ui| {
419                        for id in view_ids {
420                            let item = crate::icon_text::selectable_icon_label(ui, false, id);
421                            self.hits.insert(format!("sheets:place:{id}"), item.rect);
422                            if item.clicked() {
423                                place = Some(id.clone());
424                            }
425                        }
426                    });
427                let response = if can_place {
428                    combo.response
429                } else if sheets.sheets.is_empty() {
430                    combo.response.on_disabled_hover_text("Add a sheet first")
431                } else {
432                    combo.response.on_disabled_hover_text("Capture a PMI view first")
433                };
434                self.hits.insert("sheets:place".into(), response.rect);
435            });
436            if let Some(view) = place {
437                *action = Some(Action::PlaceView(view));
438            }
439        });
440        let placed: usize = sheets.sheets.iter().map(|sheet| sheet.views.len()).sum();
441        let dimensions: usize = sheets.sheets.iter().map(|sheet| sheet.dimensions.len()).sum();
442        ui.label(
443            egui::RichText::new(format!(
444                "{} sheet{} | {placed} placed view{} | {dimensions} dimension{} | {}",
445                sheets.sheets.len(),
446                if sheets.sheets.len() == 1 { "" } else { "s" },
447                if placed == 1 { "" } else { "s" },
448                if dimensions == 1 { "" } else { "s" },
449                match open_sheet.and_then(|id| sheets.find_sheet(id)) {
450                    Some(sheet) => format!("open: {}", sheet.name),
451                    None => "no sheet open".to_string(),
452                }
453            ))
454            .weak(),
455        );
456        if sheets.sheets.is_empty() {
457            ui.label(egui::RichText::new("Add a sheet to place PMI views on paper").weak().italics());
458        }
459        ui.add_space(2.0);
460
461        // --- the tree ---------------------------------------------------------------
462        // The OPEN sheet's projection is already computed for the viewport;
463        // the rows read it for their per-placement status, and nothing else is
464        // projected — a sheet is a hidden-line pass and the tree must not
465        // trigger one per row.
466        let drawing = open_sheet.and_then(|id| state.sheet_drawing(id));
467        let rows: Vec<RowNode> = sheets
468            .sheets
469            .iter()
470            .map(|sheet| {
471                let is_open = open_sheet == Some(sheet.id.as_str());
472                let (w, h) = sheet.millimetres();
473                let count = sheet.views.len();
474                let mut row = RowNode::new(&sheet.id)
475                    .cell(NAME, Value::String(sheet.name.clone()))
476                    .cell(KIND, serde_json::json!([{ "glyph": "\u{1F5CB}", "color": if is_open { ACTIVE_COLOR } else { MUTED_COLOR }, "tooltip": "drawing sheet" }]))
477                    .cell(
478                        VALUE,
479                        Value::String(format!(
480                            "{} · {w:.0} × {h:.0} mm · {count} view{}",
481                            sheet.size,
482                            if count == 1 { "" } else { "s" }
483                        )),
484                    )
485                    .cell(
486                        STATUS,
487                        if is_open {
488                            serde_json::json!([{ "glyph": "\u{25CF}", "color": ACTIVE_COLOR, "tooltip": "shown in the sheet viewport" }])
489                        } else {
490                            serde_json::json!([])
491                        },
492                    )
493                    .cell(ON, Value::Bool(is_open))
494                    .actions(sheet_actions(is_open));
495                row.expanded = !self.collapsed.contains(&sheet.id);
496                row.selected = is_open;
497                row.children = sheet
498                    .views
499                    .iter()
500                    .map(|placed| {
501                        let projected = drawing.and_then(|d| d.views.iter().find(|v| v.id == placed.id));
502                        let is_section = placed.section.as_ref();
503                        let is_detail = placed.detail.as_ref();
504                        let (glyph, color, tooltip, status) = match projected {
505                            Some(view) if view.error.is_empty() => (
506                                "\u{2713}",
507                                OK_COLOR,
508                                format!("{} edges, {} annotations", view.edges.len(), view.annotations.len()),
509                                format!("{} edges", view.edges.len()),
510                            ),
511                            Some(view) => ("\u{2715}", ERROR_COLOR, view.error.clone(), view.error.clone()),
512                            None => ("\u{2013}", MUTED_COLOR, "open the sheet to draw it".into(), String::new()),
513                        };
514                        let _ = status;
515                        // A placement row carries no editable cell: its name
516                        // IS its id, and the Open toggle belongs to the sheet.
517                        let mut child = RowNode::new(&placed.id)
518                            .cell(NAME, Value::String(placed.id.clone()))
519                            .cell(KIND, match (is_section, is_detail) {
520                                (Some(cut), _) => serde_json::json!([{ "glyph": "\u{25E7}", "color": ACTIVE_COLOR, "tooltip": format!("section {}—{} of {}", cut.label, cut.label, cut.source) }]),
521                                (_, Some(circle)) => serde_json::json!([{ "glyph": "\u{25CE}", "color": ACTIVE_COLOR, "tooltip": format!("detail {} of {}", circle.label, circle.source) }]),
522                                _ => serde_json::json!([{ "glyph": "\u{1F5CE}", "color": ACTIVE_COLOR, "tooltip": "placed PMI view" }]),
523                            })
524                            .cell(
525                                VALUE,
526                                Value::String(match (is_section, is_detail) {
527                                    // A section's row says what it IS a section
528                                    // of; its saved view is its source's, and
529                                    // saying so twice tells a reader nothing.
530                                    (Some(cut), _) => format!(
531                                        "SECTION {}—{} of {} · {}:1 · ({:.0}, {:.0}) mm",
532                                        cut.label,
533                                        cut.label,
534                                        cut.source,
535                                        trim(placed.scale),
536                                        placed.position[0],
537                                        placed.position[1]
538                                    ),
539                                    // …and a detail's what it is a detail of,
540                                    // at the scale that is the whole point of it.
541                                    (_, Some(circle)) => format!(
542                                        "DETAIL {} of {} · {}:1 · ({:.0}, {:.0}) mm",
543                                        circle.label,
544                                        circle.source,
545                                        trim(placed.scale),
546                                        placed.position[0],
547                                        placed.position[1]
548                                    ),
549                                    _ => format!(
550                                        "{} · {}:1 · ({:.0}, {:.0}) mm · {}",
551                                        placed.view,
552                                        trim(placed.scale),
553                                        placed.position[0],
554                                        placed.position[1],
555                                        if placed.flatten_text { "flat" } else { "projected" }
556                                    ),
557                                }),
558                            )
559                            .cell(STATUS, serde_json::json!([{ "glyph": glyph, "color": color, "tooltip": tooltip }]))
560                            .cell(ON, Value::Null)
561                            .actions(placement_actions());
562                        child.editable = false;
563                        child.selected = selected == Some(placed.id.as_str());
564                        child
565                    })
566                    .collect();
567                // …then the sheet's OWN dimensions, under the placements they
568                // anchor to. A dimension belongs to the PAPER, so it is a
569                // child of the sheet and not of any one placement — including
570                // the unresolved ones, which is where their reason is read.
571                row.children.extend(sheet.dimensions.iter().map(|dimension| {
572                    let drawn = drawing.and_then(|d| d.dimensions.iter().find(|x| x.id == dimension.id));
573                    let (glyph, color, tooltip) = match drawn {
574                        Some(d) if d.error.is_empty() => (
575                            "\u{2713}",
576                            OK_COLOR,
577                            if d.tolerance_from.is_empty() {
578                                format!("{} \u{2014} {} mm off its anchors", d.text, trim(d.offset_mm))
579                            } else {
580                                format!(
581                                    "{} \u{2014} {} mm off its anchors; the tolerance is PMI dimension {}'s",
582                                    d.text,
583                                    trim(d.offset_mm),
584                                    d.tolerance_from
585                                )
586                            },
587                        ),
588                        Some(d) => ("\u{2715}", ERROR_COLOR, d.error.clone()),
589                        None => ("\u{2013}", MUTED_COLOR, "open the sheet to draw it".into()),
590                    };
591                    let measured = drawn
592                        .filter(|d| d.error.is_empty())
593                        .map(|d| match d.tolerance_from.as_str() {
594                            "" => d.text.clone(),
595                            from => format!("{} (from {from})", d.text),
596                        })
597                        .unwrap_or_else(|| "\u{2014}".into());
598                    let mut child = RowNode::new(&dimension.id)
599                        .cell(NAME, Value::String(dimension.id.clone()))
600                        .cell(KIND, serde_json::json!([{ "glyph": "\u{2194}", "color": ACTIVE_COLOR, "tooltip": "sheet dimension" }]))
601                        .cell(
602                            VALUE,
603                            Value::String(format!(
604                                "{} \u{00B7} {} \u{00B7} {measured}",
605                                if dimension.kind == "linear" {
606                                    dimension.alignment.clone()
607                                } else {
608                                    dimension.kind.clone()
609                                },
610                                match dimension.anchors.len() {
611                                    1 => "1 anchor".to_string(),
612                                    n => format!("{n} anchors"),
613                                }
614                            )),
615                        )
616                        .cell(STATUS, serde_json::json!([{ "glyph": glyph, "color": color, "tooltip": tooltip }]))
617                        .cell(ON, Value::Null)
618                        .actions(dimension_actions());
619                    child.editable = false;
620                    child.selected = selected == Some(dimension.id.as_str());
621                    child
622                }));
623                // …and one row per ORDINATE SET, beside the dimensions: a set
624                // belongs to the paper too, and its row reads how many members
625                // it draws and how many it has lost.
626                row.children.extend(sheet.ordinates.iter().map(|set| {
627                    let drawn = drawing.and_then(|d| d.ordinates.iter().find(|x| x.id == set.id));
628                    let (glyph, color, tooltip) = match drawn {
629                        Some(d) if !d.error.is_empty() => ("\u{2715}", ERROR_COLOR, d.error.clone()),
630                        Some(d) if d.lost() > 0 => (
631                            "\u{2715}",
632                            ERROR_COLOR,
633                            d.stations
634                                .iter()
635                                .filter(|station| !station.error.is_empty())
636                                .map(|station| station.error.clone())
637                                .collect::<Vec<_>>()
638                                .join("; "),
639                        ),
640                        Some(d) => (
641                            "\u{2713}",
642                            OK_COLOR,
643                            format!(
644                                "{} stations \u{2014} baseline {} mm from the datum",
645                                d.stations.len(),
646                                trim(d.offset_mm)
647                            ),
648                        ),
649                        None => ("\u{2013}", MUTED_COLOR, "open the sheet to draw it".into()),
650                    };
651                    let mut child = RowNode::new(&set.id)
652                        .cell(NAME, Value::String(set.id.clone()))
653                        .cell(KIND, serde_json::json!([{ "glyph": "\u{22EE}", "color": ACTIVE_COLOR, "tooltip": "ordinate set" }]))
654                        .cell(
655                            VALUE,
656                            Value::String(format!(
657                                "{} \u{00B7} {}",
658                                set.axis,
659                                match set.members.len() {
660                                    1 => "1 member".to_string(),
661                                    n => format!("{n} members"),
662                                }
663                            )),
664                        )
665                        .cell(STATUS, serde_json::json!([{ "glyph": glyph, "color": color, "tooltip": tooltip }]))
666                        .cell(ON, Value::Null)
667                        .actions(ordinate_actions());
668                    child.editable = false;
669                    child.selected = selected == Some(set.id.as_str());
670                    child
671                }));
672                row
673            })
674            .collect();
675        let spec = ColumnTreeSpec {
676            id: "sheets",
677            columns: &self.columns,
678            root_label: Some("Sheets"),
679            root_cells: None,
680            empty_hint: Some("(no sheets — Add sheet to start a drawing)"),
681            hits_prefix: "sheets:",
682        };
683        let out = column_tree::column_tree(ui, &spec, &mut self.layout, &rows, Some(&mut self.hits));
684
685        // --- act on what the widget reported (at most one mutation) ------------------
686        if let Some(id) = &out.toggled {
687            if sheets.find_sheet(id).is_some() && !self.collapsed.remove(id) {
688                self.collapsed.insert(id.clone());
689            }
690        }
691        if let Some(click) = out.actions.first() {
692            *action = menu_action(click.row_id.clone(), &click.action);
693            return;
694        }
695        if let Some(edit) = out.edits.first() {
696            let id = edit.row_id.clone();
697            match edit.column.as_str() {
698                NAME if sheets.find_sheet(&id).is_some() => {
699                    *action = Some(Action::Rename(id, edit.value.as_str().unwrap_or("").to_string()));
700                }
701                ON if sheets.find_sheet(&id).is_some() => {
702                    *action = Some(Action::Open(edit.value.as_bool().unwrap_or(false).then_some(id)));
703                }
704                _ => {}
705            }
706            return;
707        }
708        let held_by_a_sheet = |id: &str| {
709            sheets.locate_view(id).is_some()
710                || sheets.locate_dimension(id).is_some()
711                || sheets.locate_ordinate(id).is_some()
712        };
713        // A DOUBLE click opens the row's dialog — a sheet's own included. Read
714        // first: egui reports the second press of a double click as a click too.
715        if let Some(id) = &out.double_clicked {
716            if held_by_a_sheet(id) || sheets.find_sheet(id).is_some() {
717                *action = Some(Action::Edit(Some(id.clone())));
718            }
719            return;
720        }
721        // A single click SELECTS: what a sheet holds becomes the selected
722        // object, and a sheet becomes the open one — which is what selecting a
723        // sheet means.
724        if let Some(id) = &out.clicked {
725            if held_by_a_sheet(id) {
726                *action = Some(Action::Select(id.clone()));
727            } else if sheets.find_sheet(id).is_some() && open_sheet != Some(id.as_str()) {
728                *action = Some(Action::Open(Some(id.clone())));
729            }
730        }
731    }
732
733    /// Draw ONE sheet object's dialog through the shared form view.
734    /// `catalogue_index` picks the schema: 0 = the sheet, 1 = a placement,
735    /// 2 = a dimension, 3 = an ordinate set, 4 = a section, 5 = a detail.
736    #[allow(clippy::too_many_arguments)]
737    fn show_form(
738        &mut self,
739        ui: &mut egui::Ui,
740        state: &EngineState,
741        id: &str,
742        label: &str,
743        seed: &Value,
744        catalogue_index: usize,
745        note: Option<&str>,
746        action: &mut Option<Action>,
747        close: &mut bool,
748    ) {
749        let catalogue = state.sheet_catalogue();
750        let Some(schema) = catalogue
751            .get("objects")
752            .and_then(Value::as_array)
753            .and_then(|objects| objects.get(catalogue_index))
754            .cloned()
755        else {
756            *close = true;
757            return;
758        };
759        let fields = form_fields_from_schema(&schema);
760        let mut params = seed.clone();
761        let title = format!("{label} {id}");
762        // The SHEET's revision rows: a list of records, drawn as the form's
763        // own section. Intent-out like the rest of the form — the drawer edits
764        // a copy and records what changed; the engine is driven below.
765        let is_sheet = catalogue_index == 0;
766        let revisions: Vec<brep_render::sheets::Revision> = if is_sheet {
767            serde_json::from_value(seed.get("revisions").cloned().unwrap_or(Value::Null)).unwrap_or_default()
768        } else {
769            Vec::new()
770        };
771        let revision_rows = std::cell::RefCell::new(revisions);
772        let revision_intents: std::cell::RefCell<Vec<RevisionIntent>> = std::cell::RefCell::new(Vec::new());
773        let revision_hits: std::cell::RefCell<Vec<(String, egui::Rect)>> = std::cell::RefCell::new(Vec::new());
774        let bom = std::cell::RefCell::new(serde_json::from_value::<Option<brep_render::sheets::BomTable>>(seed.get("bomTable").cloned().unwrap_or(Value::Null)).unwrap_or_default());
775        let bom_changed = std::cell::Cell::new(false);
776        let mut columns = if is_sheet { state.sheet_bom_columns() } else { Vec::new() };
777        let config = if state.settings.bom_columns.is_empty() { crate::panels::bom_columns::default_text() } else { state.settings.bom_columns.clone() };
778        for column in crate::panels::bom_columns::parse(&config).columns { let key = column.key(); if !columns.contains(&key) { columns.push(key); } }
779        if let Some(table) = bom.borrow().as_ref() { for column in &table.columns { if !columns.contains(column) { columns.push(column.clone()); } } }
780        columns.sort_by_key(|column| !bom.borrow().as_ref().is_some_and(|table| table.columns.contains(column)));
781        let draw_revisions = |ui: &mut egui::Ui| {
782            ui.label("BOM table");
783            let mut table = bom.borrow_mut();
784            let mut enabled = table.is_some();
785            let response = ui.checkbox(&mut enabled, "Show BOM table");
786            revision_hits.borrow_mut().push(("sheets:bom:enabled".into(), response.rect));
787            if response.changed() {
788                *table = enabled.then(brep_render::sheets::BomTable::default); bom_changed.set(true);
789            }
790            if let Some(table) = table.as_mut() {
791                ui.horizontal(|ui| {
792                    ui.label("Position (mm)");
793                    for coordinate in &mut table.position { if ui.add(egui::DragValue::new(coordinate).speed(1.)).changed() { bom_changed.set(true); } }
794                });
795                ui.horizontal(|ui| { ui.label("Column width (mm)"); if ui.add(egui::DragValue::new(&mut table.column_width_mm).range(8.0..=200.0)).changed() { bom_changed.set(true); } });
796                ui.label("Columns");
797                egui::ScrollArea::vertical().id_salt(("bom-columns", id)).max_height(180.0).show(ui, |ui| {
798                for column in &columns {
799                    let mut selected = table.columns.contains(column);
800                    let response = ui.checkbox(&mut selected, column.replace('_', " "));
801                    revision_hits.borrow_mut().push((format!("sheets:bom:column:{column}"), response.rect));
802                    if response.changed() {
803                        if selected { table.columns.push(column.clone()); } else { table.columns.retain(|c| c != column); }
804                        bom_changed.set(true);
805                    }
806                }
807                });
808            }
809            ui.separator();
810            ui.label("Revisions");
811            draw_revision_rows(ui, id, &revision_rows, &revision_intents, &revision_hits);
812        };
813        let spec = FormViewSpec {
814            title: &title,
815            subtitle: None,
816            fields: &fields,
817            banner: note.map(|note| (note, egui::Color32::from_rgb(0x58, 0xa6, 0xff))),
818            trailing: None,
819            exit_label: "Return to tree",
820            extra: is_sheet.then_some(("Tables", &draw_revisions as &dyn Fn(&mut egui::Ui))),
821            rollback: false,
822            hidden: None,
823            hits_prefix: "sheets:",
824            read_only: state.history.locked(),
825        };
826        let mut out = form_view(ui, &spec, &mut params, Some(&mut self.hits));
827        if is_sheet && bom_changed.get() { params["bomTable"] = serde_json::to_value(bom.into_inner()).unwrap_or(Value::Null); out.changed = true; }
828        for (key, rect) in revision_hits.into_inner() {
829            self.hits.insert(key, rect);
830        }
831        // ONE revision edit per frame, and only when the schema fields did not
832        // change on the same frame (each is a document write).
833        if !out.changed {
834            if let Some(intent) = revision_intents.into_inner().into_iter().next() {
835                *action = Some(match intent {
836                    RevisionIntent::Add => Action::AddRevision(id.to_string()),
837                    RevisionIntent::Update(index, field, value) => {
838                        Action::UpdateRevision(id.to_string(), index, serde_json::json!({ field: value }))
839                    }
840                    RevisionIntent::Remove(index) => Action::RemoveRevision(id.to_string(), index),
841                });
842            }
843        }
844        let anchor = self.hits.get("sheets:form:feature").map(|rect| rect.min).unwrap_or(egui::Pos2::ZERO);
845        self.hits.insert(format!("sheets:form:object:{id}"), egui::Rect::from_min_size(anchor, egui::Vec2::ZERO));
846        if out.changed {
847            *action = Some(match catalogue_index {
848                0 => Action::UpdateSheet(id.to_string(), params),
849                2 => Action::UpdateDimension(id.to_string(), params),
850                3 => Action::UpdateOrdinate(id.to_string(), params),
851                // A placement, a section or a detail: one update door.
852                _ => Action::UpdateView(id.to_string(), params),
853            });
854        }
855        // Every reference row's **Select** is the same gesture a feature's
856        // is: the reference picker. On a sheet the picks are anchors clicked
857        // on the paper, and Finish writes them into this object's field.
858        if let Some(activate) = out.ref_activate {
859            *action = Some(Action::BeginRefSelect {
860                id: id.to_string(),
861                path: activate.path,
862                label: activate.label,
863                filter: activate.filter,
864                multiple: activate.multiple,
865                seed: activate.seed,
866            });
867        }
868        if out.exit_clicked {
869            *close = true;
870        }
871    }
872
873    /// The per-frame widget rects for the automation layer.
874    pub fn hits_json(&self) -> String {
875        crate::automation::hit_rects::hits_json(&self.hits)
876    }
877
878    /// Drop the published rects: the dock calls this for a pane it did not
879    /// draw this frame (`DockState::ui`), whose widgets are not on screen.
880    pub fn clear_hits(&mut self) {
881        self.hits.clear();
882    }
883}
884
885/// The sheet dialog's **Revisions** section: one row per revision — its
886/// letter, date and description as text edits and a ✕ that removes it — then
887/// **+ Add revision**. Every control publishes a keyed rect
888/// (`sheets:rev:<n>:rev|date|description|remove`, `sheets:rev:add`).
889fn draw_revision_rows(
890    ui: &mut egui::Ui,
891    sheet_id: &str,
892    rows: &std::cell::RefCell<Vec<brep_render::sheets::Revision>>,
893    intents: &std::cell::RefCell<Vec<RevisionIntent>>,
894    hits: &std::cell::RefCell<Vec<(String, egui::Rect)>>,
895) {
896    let mut rows = rows.borrow_mut();
897    if rows.is_empty() {
898        ui.label(egui::RichText::new("No revisions \u{2014} the sheet draws no revision table").weak().italics());
899    }
900    // Two lines per revision, because the pane is a narrow column: the letter,
901    // the date and the ✕ on the first, the description the whole width of the
902    // second.
903    for (index, row) in rows.iter_mut().enumerate() {
904        let mut edit = |ui: &mut egui::Ui, field: &'static str, value: &mut String, width: f32, hint: &str| {
905            let response = ui.add(
906                egui::TextEdit::singleline(value)
907                    .id(egui::Id::new(("sheet-revision", sheet_id, index, field)))
908                    .hint_text(hint)
909                    .desired_width(width),
910            );
911            hits.borrow_mut().push((format!("sheets:rev:{index}:{field}"), response.rect));
912            if response.changed() {
913                intents.borrow_mut().push(RevisionIntent::Update(index, field, value.clone()));
914            }
915        };
916        ui.horizontal(|ui| {
917            ui.label(egui::RichText::new("Rev").weak());
918            edit(ui, "rev", &mut row.rev, 36.0, "A");
919            ui.label(egui::RichText::new("Date").weak());
920            edit(ui, "date", &mut row.date, 88.0, "YYYY-MM-DD");
921            let remove = ui
922                .add(crate::icon_text::icon_button(ui, "\u{2715}"))
923                .on_hover_text("Remove this revision row");
924            hits.borrow_mut().push((format!("sheets:rev:{index}:remove"), remove.rect));
925            if remove.clicked() {
926                intents.borrow_mut().push(RevisionIntent::Remove(index));
927            }
928        });
929        // Capped, not the whole available width: in a scrolling pane that can
930        // run past the clip rect, and a rect egui will not click is a lie.
931        let width = ui.available_width().min(240.0);
932        edit(ui, "description", &mut row.description, width, "Description");
933        ui.add_space(4.0);
934    }
935    let add = ui
936        .add(crate::icon_text::icon_button(ui, "+ Add revision"))
937        .on_hover_text("Append a revision row: the next letter, today's date, no description");
938    hits.borrow_mut().push(("sheets:rev:add".into(), add.rect));
939    if add.clicked() {
940        intents.borrow_mut().push(RevisionIntent::Add);
941    }
942}
943
944/// `4` rather than `4.0`, `2.5` as `2.5` — a scale reads as a ratio.
945fn trim(value: f64) -> String {
946    let text = format!("{value:.3}");
947    let text = text.trim_end_matches('0').trim_end_matches('.');
948    if text.is_empty() { "0".into() } else { text.to_string() }
949}
950
951/// The hit keys this panel publishes (see `automation::hit_keys`).
952pub static HIT_KEYS: &[HitKeyDoc] = &[
953    HitKeyDoc { panel: "sheets", prefix: "sheets:panel:clip", meaning: "the pane's clip rect \u{2014} a row scrolled outside it publishes a rect egui will not accept a click on", command: None },
954    HitKeyDoc { panel: "sheets", prefix: "sheets:add", meaning: "add a sheet at the default paper size and open it", command: Some("sheet_add") },
955    HitKeyDoc { panel: "sheets", prefix: "sheets:place", meaning: "open the place-view menu", command: None },
956    HitKeyDoc { panel: "sheets", prefix: "sheets:place:", meaning: "place that saved PMI view on the open sheet (sheets:place:<view id>)", command: Some("sheet_place_view") },
957    HitKeyDoc { panel: "sheets", prefix: "sheets:row:", meaning: "a sheet, placement, dimension or ordinate-set row (sheets:row:<id>) \u{2014} a click opens a sheet in the sheet viewport or SELECTS what it holds, a double click opens that row's dialog", command: None },
958    HitKeyDoc { panel: "sheets", prefix: "sheets:cell:", meaning: "a row cell (sheets:cell:<id>:<column>) \u{2014} `sheets:cell:<sheet id>:on` is the toggle that OPENS a sheet in the sheet viewport", command: Some("sheet_open") },
959    HitKeyDoc { panel: "sheets", prefix: "sheets:box:", meaning: "a row's collapse box (sheets:box:<row id>) \u{2014} a sheet's box folds its placed views away", command: None },
960    HitKeyDoc { panel: "sheets", prefix: "sheets:col:", meaning: "a table column header (sheets:col:<field>) \u{2014} click to sort", command: None },
961    HitKeyDoc { panel: "sheets", prefix: "sheets:grip:", meaning: "a column's resize grip (sheets:grip:<field>)", command: None },
962    HitKeyDoc { panel: "sheets", prefix: "sheets:menu:", meaning: "a row's action-menu trigger cell (sheets:menu:<row id>); a right-click on the row opens the same menu", command: None },
963    HitKeyDoc { panel: "sheets", prefix: "sheets:menuitem:", meaning: "one entry of the OPEN row action menu (sheets:menuitem:<row id>:<action>) \u{2014} published only while the menu is up", command: None },
964    HitKeyDoc { panel: "sheets", prefix: "sheets:form:", meaning: "the open sheet / placement form (sheets:form:object:<id>, sheets:form:feature, sheets:form:return)", command: Some("sheet_update") },
965    HitKeyDoc { panel: "sheets", prefix: "sheets:field:", meaning: "one schema field of the open form (sheets:field:<path>) \u{2014} the paper size, the placed view, its position and scale, `sheets:field:flattenText`, the checkbox that lays that view's annotation text flat on the sheet, and a sheet dimension's kind, alignment, offset and precision and its tolerance block — `sheets:field:tolMode` (none / symmetric / deviation / limits), `sheets:field:tolUpper`, `sheets:field:tolLower` and the `sheets:field:isReference` checkbox, which an ordinate set's form carries too. `sheets:field:anchors#activate` opens the reference picker on the paper (anchors are clicked as `sheet/anchor:<ref>`, then `modebar/refsel:finish`), `sheets:field:anchors#line<n>` is one anchor row and `sheets:field:anchors#x<n>` drops it. An ORDINATE SET's form adds `sheets:field:axis` and its two reference fields `sheets:field:datum` and `sheets:field:members`; a SECTION's form its `sheets:field:cut` (the cutting line), `sheets:field:sectionLabel` and `sheets:field:sectionFlip`; a DETAIL's form its `sheets:field:centre`, `sheets:field:rim` and `sheets:field:detailLabel` \u{2014} each reference field with the same `#activate`, `#line<n>` and `#x<n>` keys", command: Some("sheet_update_dimension") },
966    HitKeyDoc { panel: "sheets", prefix: "sheets:group:", meaning: "a collapsible group header of the open form (sheets:group:<name>)", command: None },
967    HitKeyDoc { panel: "sheets", prefix: "sheets:bom:", meaning: "the sheet BOM table toggle and column choices: sheets:bom:enabled, sheets:bom:column:<attribute>", command: Some("sheet_update") },
968    HitKeyDoc { panel: "sheets", prefix: "sheets:rev:", meaning: "the SHEET dialog's Revisions section: `sheets:rev:add` appends a row (the next letter, today's date), and per row `sheets:rev:<n>:rev`, `sheets:rev:<n>:date` and `sheets:rev:<n>:description` are its three text edits and `sheets:rev:<n>:remove` removes it. Rows keep their order; the sheet draws them as the revision table beside its title block", command: Some("sheet_add_revision") },
969];
970
971
972
973