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