Skip to main content

brep_app/panels/
instructions.rs

1//! The Instructions pane — the Instructions workbench's
2//! ([`crate::workbench::instructions`]) step tree over the
3//! document's `instructions` block, and the selected step's editor: its
4//! title, parts, torque, tools, callouts, insertion arrows, the fields the
5//! person doing the work records, notes and sign-off — and the print settings the PDF follows (File ▸ Export writes it).
6//! While a re-target waits (a new revision of the assembly came in through
7//! Update components), the pane lists what changed and the steps it touched,
8//! and Approve makes the new revision the target.
9//!
10//! The pane holds only transient widget state (its hit rects, the selected
11//! step, an action a toolbar button handed it, the tool being typed). Every
12//! record it draws is read from the engine each frame, and every edit goes
13//! through the engine's instructions methods — the same ones the
14//! `instructions_*` automation commands call — so undo, save and reload come
15//! from the document. A field being typed in is one undo step per field.
16
17use crate::ui_kit;
18use crate::automation::hit_keys::HitKeyDoc;
19use brep_instructions::edit;
20use brep_instructions::fields::{FieldKind as StepFieldKind, StepField};
21use brep_instructions::model::{Arrow, Callout, CalloutKind, Instructions, Orientation, Step, Style, Torque, TorqueSource, ToolUse};
22use brep_render::engine_state::PublishedMotion;
23use brep_render::engine_state::{EngineState, InstructionsRefField, RefSelectField, RefSelectTarget};
24use brep_render::style::{FieldKind, FormField};
25use std::collections::HashMap;
26
27/// The owner tag of the hover this pane sets when the pointer rests on an
28/// occurrence field's line (`EngineState::hover_entity_by_name`).
29const DIALOG_HOVER_OWNER: &str = "instructions";
30
31/// An action a toolbar button hands the pane: the pane performs it because
32/// it owns the selection the action reads (where a new step goes).
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum InstructionsRequest {
35    Wizard,
36    NewStep,
37}
38
39/// Where an insertion arrow starts, as the pane offers it: the part comes in
40/// from that side, travelling the opposite way.
41const ARROW_SIDES: [(&str, [f64; 3]); 6] = [
42    ("from above (+Z)", [0.0, 0.0, -1.0]),
43    ("from below (−Z)", [0.0, 0.0, 1.0]),
44    ("from +X", [-1.0, 0.0, 0.0]),
45    ("from −X", [1.0, 0.0, 0.0]),
46    ("from +Y", [0.0, -1.0, 0.0]),
47    ("from −Y", [0.0, 1.0, 0.0]),
48];
49
50/// The default distance an insertion arrow starts from, in model units.
51const ARROW_DISTANCE: f64 = 30.0;
52
53/// In a wrapped row, start a new line before a `label` + control pair that
54/// would not fit whole. egui wraps one widget at a time, and a ComboBox lays
55/// itself out in a child `Ui` that never wraps, so a pair that began near the
56/// end of a line put its combo past the pane edge ("Orientation: Portrai" at
57/// the 1280 dock door split — ui-polish-2026-10-28 row 1). Only breaks a line
58/// that already holds something: a pair wider than the whole pane still draws.
59fn keep_pair_together(ui: &mut egui::Ui, label: &str, control_w: f32) {
60    let font = egui::TextStyle::Body.resolve(ui.style());
61    let label_w = ui.ctx().fonts_mut(|f| f.layout_no_wrap(label.to_owned(), font, egui::Color32::PLACEHOLDER).size().x);
62    let needed = label_w + ui.spacing().item_spacing.x + control_w + 2.0 * ui.spacing().button_padding.x;
63    // `available_width` is the WHOLE row in a wrapping layout; what is left of
64    // this line is `available_rect_before_wrap` — capped at the clip, because a
65    // child that once overflowed has widened the `Ui`'s max_rect for good
66    // (egui expands it to include every child), and the pane's edge is what
67    // the user sees.
68    let edge = ui.max_rect().right().min(ui.clip_rect().right());
69    let remaining = (edge - ui.cursor().left()).max(0.0);
70    if needed > remaining && ui.cursor().left() > ui.max_rect().left() + 0.5 {
71        ui.end_row();
72    }
73}
74
75#[derive(Default)]
76pub struct InstructionsPanel {
77    /// The assembly's studies with a published motion, read each frame
78    /// (`instructions_published_motions`), for the step editor's Motion row.
79    published: Vec<PublishedMotion>,
80    hits: HashMap<String, egui::Rect>,
81    /// The pane's clip rect this frame: every published rect is cut to it,
82    /// so a script's click on a widget that runs past the pane's edge (an
83    /// action row wider than a narrow column) lands on the part on screen.
84    clip: Option<egui::Rect>,
85    selected: Option<String>,
86    request: Option<InstructionsRequest>,
87    /// The tool being typed before Add tool: name and spec.
88    tool_draft: (String, String),
89    notice: Option<String>,
90    error: Option<String>,
91    /// The occurrence pick running in this pane's step editor this frame, if
92    /// one is (an arrow's or a callout's field), read before drawing.
93    picking: Option<RefSelectField>,
94    /// The occurrence (or solid) a field's line is hovered on this frame.
95    hover: Option<String>,
96    /// A step field's number being typed (nominal, min, max), by its hit
97    /// key: the text as typed while the box has focus (`9.` must not snap
98    /// back to `9`), dropped when focus leaves.
99    number_drafts: HashMap<String, String>,
100}
101
102/// What a BOM row, or a part of the "not yet planned" list, carries while
103/// it is dragged: the occurrences it stands for. Dropped on a step's row,
104/// they join that step.
105#[derive(Clone, Debug)]
106pub struct PartsDrag {
107    pub occurrences: Vec<String>,
108    pub part: String,
109}
110
111/// A step's row being dragged: dropped on another step's row, it nests
112/// under that step, its children with it; dropped on the root, it returns
113/// to the top level.
114#[derive(Clone, Debug)]
115struct StepDrag(String);
116
117/// One engine edit the frame asks for, applied after drawing (the list and
118/// the editor read the block while drawing).
119enum Change {
120    Show(String),
121    Restructure(Restructure),
122    /// Parts dropped on, or added to, a step.
123    AddParts { step: String, occurrences: Vec<String> },
124    /// A part taken out of its step: not planned any more.
125    RemoveAdd { step: String, add: usize },
126    /// A step moved under `parent` (`None`: the top level) at `index`.
127    Nest { step: String, parent: Option<String>, index: usize },
128    /// The viewport's camera becomes the step's, kept until reset.
129    CaptureCamera(String),
130    /// The step's camera is generated again.
131    ResetView(String),
132    Step { step: String, coalesce: Option<String>, apply: Box<dyn FnOnce(&mut Step)> },
133    /// A print setting: the page template or the front matter.
134    Print(Box<dyn FnOnce(&mut Instructions)>),
135    /// Approve the pending re-target.
136    ApproveRetarget,
137    /// Reject it: the one undo that takes the revision back.
138    RejectRetarget,
139    /// An occurrence field's Select: pick the part in the viewport, seeded
140    /// with the occurrence the field holds.
141    PickOccurrence { step: String, field: InstructionsRefField, seed: Option<String> },
142    /// The focused occurrence field's Done.
143    FinishPick,
144    /// An ✕ on the focused occurrence field's running pick.
145    RemovePick(usize),
146    /// The study's published motion becomes the step's.
147    AttachMotion { step: String, study: String },
148}
149
150enum Restructure {
151    MoveStep { step: String, index: usize },
152    MergeWithNext { step: String, next: String },
153    Delete(String),
154    Split { step: String, add: usize },
155    MoveAdd { from: String, add: usize, to: String },
156}
157
158impl InstructionsPanel {
159    pub fn new() -> Self {
160        Self::default()
161    }
162
163    /// Hand the pane an action; it performs it on the next frame it draws.
164    pub fn request(&mut self, request: InstructionsRequest) {
165        self.request = Some(request);
166    }
167
168    /// The selected step.
169    pub fn selected(&self) -> Option<&str> {
170        self.selected.as_deref()
171    }
172
173    pub fn hits_json(&self) -> String {
174        crate::automation::hit_rects::hits_json(&self.hits)
175    }
176
177    /// Drop the published rects: the dock calls this for a pane it did not
178    /// draw this frame.
179    pub fn clear_hits(&mut self) {
180        self.hits.clear();
181    }
182
183    /// What automation reads beside the engine's `instructions_state`.
184    pub fn state_json(&self) -> String {
185        let picking = self.picking.as_ref().and_then(|field| match field.target {
186            RefSelectTarget::Instructions { field: InstructionsRefField::Arrow(index) } => Some(format!("arrow:{index}")),
187            RefSelectTarget::Instructions { field: InstructionsRefField::Callout(index) } => Some(format!("callout:{index}")),
188            _ => None,
189        });
190        let mut state = serde_json::json!({ "selected": self.selected, "notice": self.notice, "error": self.error });
191        // Absent, not null, while no pick runs: a script asks `exists`.
192        if let Some(picking) = picking {
193            state["picking"] = serde_json::Value::String(picking);
194        }
195        state.to_string()
196    }
197
198    fn perform(&mut self, request: InstructionsRequest, engine: &mut EngineState) {
199        self.notice = None;
200        self.error = None;
201        let result = match request {
202            InstructionsRequest::Wizard => engine.instructions_run_wizard_when_built().map(|()| {
203                self.selected = None;
204                "The wizard proposed the steps".to_string()
205            }),
206            InstructionsRequest::NewStep => engine.instructions_new_step(self.selected.as_deref()).map(|id| {
207                let _ = engine.instructions_show_step(&id);
208                self.selected = Some(id);
209                "New step: move parts into it from the other steps".to_string()
210            }),
211        };
212        match result {
213            Ok(notice) => self.notice = Some(notice),
214            Err(error) => self.error = Some(error),
215        }
216    }
217
218    pub fn show(&mut self, ui: &mut egui::Ui, engine: &mut EngineState) {
219        self.hits.clear();
220        self.clip = Some(ui.clip_rect());
221        self.hits.insert("panel:clip".into(), ui.clip_rect());
222        if !engine.is_instructions() {
223            ui.label("Open an assembly and press New from assembly on the toolbar: the instructions open in a new tab.");
224            return;
225        }
226        if let Some(request) = self.request.take() {
227            self.perform(request, engine);
228        }
229        let block = match engine.instructions() {
230            Ok(Some(block)) => block,
231            Ok(None) => return,
232            Err(error) => {
233                ui.colored_label(ui.visuals().error_fg_color, format!("The instructions cannot be read: {error}"));
234                return;
235            }
236        };
237        if self.selected.as_deref().is_some_and(|id| block.step(id).is_none()) {
238            self.selected = None;
239        }
240        let shown = engine.instructions_state_json()["shownStep"].as_str().map(str::to_string);
241        if self.selected.is_none() {
242            self.selected = shown.clone();
243        }
244
245        ui.horizontal_wrapped(|ui| {
246            ui.label("For");
247            ui.strong(&block.target.name);
248            if engine.instructions_wizard_pending() {
249                ui.weak("— the wizard runs once the assembly is built");
250            }
251        });
252        if let Some(error) = &self.error {
253            let label = ui.colored_label(ui.visuals().error_fg_color, error);
254            self.hit("instructions:error", label.rect);
255        }
256        if let Some(notice) = &self.notice {
257            let label = ui.weak(notice);
258            self.hit("instructions:notice", label.rect);
259        }
260        ui.separator();
261
262        let mut change = None;
263        if block.retarget.is_some() {
264            self.retarget(ui, &block, shown.as_deref(), &mut change);
265            ui.separator();
266        }
267        self.print_settings(ui, &block, &mut change);
268        ui.separator();
269        let unplanned = engine.instructions_unplanned();
270        self.published = engine.instructions_published_motions().unwrap_or_default();
271        // The occurrence pick running in the step editor, drawn by its own
272        // field (the form infrastructure's reference row) like a PMI form's.
273        self.picking = engine.ref_select_field().filter(|field| matches!(field.target, RefSelectTarget::Instructions { .. }));
274        self.hover = None;
275        self.unplanned_list(ui, &unplanned, &mut change);
276        self.step_list(ui, &block, shown.as_deref(), &mut change);
277        if let Some(step_id) = self.selected.clone() {
278            if let Some(step) = block.step(&step_id) {
279                ui.separator();
280                self.step_actions(ui, &block, step, &mut change);
281                self.step_editor(ui, &block, step, &mut change);
282            }
283        }
284        if let Some(change) = change {
285            self.apply(change, engine);
286        }
287        // This pane drew the pick's field: the shell finishes an in-form pick
288        // no form claims, so one never runs on with its field off screen.
289        if let Some(field) = engine.ref_select_field() {
290            if matches!(field.target, RefSelectTarget::Instructions { .. }) && self.selected.as_deref() == Some(field.subject.as_str()) {
291                engine.ref_select_claim();
292            }
293        }
294        // A hovered field line lights the part it names in the viewport: a
295        // running pick's line is a solid, a stored line an occurrence.
296        let hovered = self.hover.clone().and_then(|name| {
297            if engine.scene.solid(&name).is_some() { Some(name) } else { engine.instructions_occurrence_solid(&name) }
298        });
299        let hover_changed = match hovered {
300            Some(name) => engine.hover_entity_by_name(DIALOG_HOVER_OWNER, &name),
301            None => engine.dialog_hover_end(DIALOG_HOVER_OWNER),
302        };
303        if hover_changed {
304            ui.ctx().request_repaint();
305        }
306    }
307
308    /// A step row's occurrence field — the form infrastructure's reference
309    /// row, as a PMI anchor or a constraint's element is picked: Select
310    /// starts a viewport pick of ONE solid, the focused field lists the
311    /// running pick and its button is Done, a stored line's ✕ clears it.
312    /// `key` is the row (`arrow:0`, `callout:1`); the field's rects are
313    /// published under `instructions:<key>:occurrence` (`#activate`,
314    /// `#line0`, `#x0`). Returns whether the stored line was cleared.
315    fn occurrence_field(&mut self, ui: &mut egui::Ui, key: &str, step: &str, field: InstructionsRefField, occurrence: Option<&str>, change: &mut Option<Change>) -> bool {
316        let spec = FormField {
317            path: vec!["occurrence".into()],
318            label: "Part".into(),
319            group: String::new(),
320            kind: FieldKind::Reference { filter: vec!["SOLID".into()], multiple: false },
321        };
322        let mut current = serde_json::json!({ "occurrence": occurrence });
323        let running: Option<Vec<String>> = self
324            .picking
325            .as_ref()
326            .filter(|f| f.subject == step && f.target == RefSelectTarget::Instructions { field })
327            .map(|f| f.names.clone());
328        let picking = running.as_ref().map(|names| crate::form::ActivePick { path: &spec.path, names });
329        let mut probe = HashMap::new();
330        let mut actions = crate::form::FieldActions::default();
331        let (changed, rect) = crate::form::field_input_with(ui, &spec, &mut current, Some(&mut probe), &mut actions, picking);
332        self.hit(format!("instructions:{key}:occurrence"), rect);
333        for (probe_key, probe_rect) in probe {
334            self.hit(format!("instructions:{key}:{probe_key}"), probe_rect);
335        }
336        if actions.clicked.is_some() {
337            *change = Some(Change::PickOccurrence { step: step.to_string(), field, seed: occurrence.map(str::to_string) });
338        } else if actions.pick_done {
339            *change = Some(Change::FinishPick);
340        } else if let Some(index) = actions.pick_remove {
341            *change = Some(Change::RemovePick(index));
342        }
343        if let Some(name) = actions.hovered_entity {
344            self.hover = Some(name);
345        }
346        changed
347    }
348
349    /// The page template and the front matter the PDF prints: steps per
350    /// page, orientation and paper as dropdowns (`form::enum_dropdown`, the
351    /// combo every panel enum draws), and whether the parts and tools lists
352    /// print as checkboxes.
353    fn print_settings(&mut self, ui: &mut egui::Ui, block: &Instructions, change: &mut Option<Change>) {
354        let template = &block.template;
355        let per_page_choices: Vec<(u8, String)> = brep_instructions::model::STEPS_PER_PAGE.iter().map(|n| (*n, n.to_string())).collect();
356        let per_page_choices: Vec<(u8, &str, &str)> = per_page_choices.iter().map(|(n, s)| (*n, s.as_str(), s.as_str())).collect();
357        let orientation_choices = [(Orientation::Portrait, "Portrait", "Portrait"), (Orientation::Landscape, "Landscape", "Landscape")];
358        let paper_choices: Vec<(String, &str, &str)> = brep_instructions::layout::PAPER_SIZES.iter().map(|(key, _, _)| (key.to_string(), *key, *key)).collect();
359        let style_choices: Vec<(Style, &str, &str)> = Style::CHOICES.iter().map(|(style, key, label)| (*style, *key, *label)).collect();
360        ui.horizontal_wrapped(|ui| {
361            ui.label("Print");
362            let mut probe: HashMap<String, egui::Rect> = HashMap::new();
363            // How every output draws the steps: the PDF, the images, the
364            // HTML player and the Player pane.
365            keep_pair_together(ui, "Style:", 92.0);
366            ui.label("Style:");
367            let mut style = template.style;
368            if crate::form::enum_dropdown(ui, "instructions:print:style", &style_choices, &mut style, Some(92.0), Some(&mut probe)).0 {
369                *change = Some(Change::Print(Box::new(move |block| block.template.style = style)));
370            }
371            keep_pair_together(ui, "Steps a page:", 56.0);
372            ui.label("Steps a page:");
373            let mut per_page = template.steps_per_page;
374            if crate::form::enum_dropdown(ui, "instructions:print:per_page", &per_page_choices, &mut per_page, Some(56.0), Some(&mut probe)).0 {
375                *change = Some(Change::Print(Box::new(move |block| block.template.steps_per_page = per_page)));
376            }
377            keep_pair_together(ui, "Orientation:", 100.0);
378            ui.label("Orientation:");
379            let mut orientation = template.orientation;
380            if crate::form::enum_dropdown(ui, "instructions:print:orientation", &orientation_choices, &mut orientation, Some(100.0), Some(&mut probe)).0 {
381                *change = Some(Change::Print(Box::new(move |block| block.template.orientation = orientation)));
382            }
383            keep_pair_together(ui, "Paper:", 84.0);
384            ui.label("Paper:");
385            let mut paper = template.paper.clone();
386            if crate::form::enum_dropdown(ui, "instructions:print:paper", &paper_choices, &mut paper, Some(84.0), Some(&mut probe)).0 {
387                *change = Some(Change::Print(Box::new(move |block| block.template.paper = paper)));
388            }
389            // Through `hit`, so the rects are cut to the pane like every other.
390            for (key, rect) in probe {
391                self.hit(key, rect);
392            }
393            for (key, label) in [("parts", "Parts list"), ("tools", "Tools list")] {
394                let parts = key == "parts";
395                let mut on = if parts { block.front.parts_list } else { block.front.tools_list };
396                let check = ui_kit::checkbox(ui, &mut on, &label);
397                self.hit(format!("instructions:print:{key}"), check.rect);
398                if check.changed() {
399                    *change = Some(Change::Print(Box::new(move |block| {
400                        if parts { block.front.parts_list = on } else { block.front.tools_list = on }
401                    })));
402                }
403            }
404        });
405    }
406
407    /// The pending re-target: the parts added, removed and replaced in the
408    /// new revision, the steps they touched (a click shows one) and the steps
409    /// left with no parts, which Approve deletes.
410    fn retarget(&mut self, ui: &mut egui::Ui, block: &Instructions, shown: Option<&str>, change: &mut Option<Change>) {
411        let Some(retarget) = &block.retarget else { return };
412        let heading = ui.strong(format!("New revision of {}: review the changes", retarget.to.name));
413        self.hit("instructions:retarget:heading", heading.rect);
414        let groups = [("added", "Added", &retarget.added), ("removed", "Removed", &retarget.removed), ("replaced", "Replaced", &retarget.replaced)];
415        for (key, label, changes) in groups {
416            for (index, occurrence) in changes.iter().enumerate() {
417                let text = match &occurrence.was {
418                    Some(was) => format!("{label}: {} ({was} → {})", occurrence.occurrence, occurrence.part),
419                    None => format!("{label}: {} ({})", occurrence.occurrence, occurrence.part),
420                };
421                let row = ui.label(text);
422                self.hit(format!("instructions:retarget:{key}:{index}"), row.rect);
423            }
424        }
425        let numbers: HashMap<&str, usize> = block.steps().enumerate().map(|(i, (_, s))| (s.id.as_str(), i + 1)).collect();
426        ui.horizontal_wrapped(|ui| {
427            ui.label("Steps changed:");
428            if retarget.touched_steps.is_empty() {
429                ui.weak("none");
430            }
431            for id in &retarget.touched_steps {
432                let Some(number) = numbers.get(id.as_str()) else { continue };
433                let empty = if retarget.empty_steps.contains(id) { " (no parts: deleted on approval)" } else { "" };
434                let row = ui.selectable_label(self.selected.as_deref() == Some(id.as_str()), format!("{number}{empty}"));
435                self.hit(format!("instructions:retarget:step:{id}"), row.rect);
436                if row.clicked() {
437                    self.selected = Some(id.clone());
438                    if shown != Some(id.as_str()) {
439                        *change = Some(Change::Show(id.clone()));
440                    }
441                }
442            }
443        });
444        ui.horizontal(|ui| {
445            let approve = ui.add(ui_kit::Button::new("Approve the new revision"));
446            self.hit("instructions:retarget:approve", approve.rect);
447            if approve.clicked() {
448                *change = Some(Change::ApproveRetarget);
449            }
450            let reject = ui.add(ui_kit::Button::new("Reject: take the revision back")).on_hover_text(
451                "The one undo that takes the new revision and these changes back together, so the instructions keep describing the revision they did",
452            );
453            self.hit("instructions:retarget:reject", reject.rect);
454            if reject.clicked() {
455                *change = Some(Change::RejectRetarget);
456            }
457        });
458    }
459
460    /// The assembly's parts in no step yet, each a drag source (drop it on a
461    /// step's row) with a button for the selected step.
462    fn unplanned_list(&mut self, ui: &mut egui::Ui, unplanned: &[(String, String)], change: &mut Option<Change>) {
463        if unplanned.is_empty() {
464            return;
465        }
466        ui.label(egui::RichText::new("Not yet planned").strong());
467        ui.weak("Drag a part onto a step (from here or from the BOM), or add it to the selected step.");
468        for (occurrence, part) in unplanned {
469            ui.horizontal(|ui| {
470                let row = ui.add(egui::Label::new(format!("{part}  ({occurrence})")).sense(egui::Sense::click_and_drag())).on_hover_cursor(egui::CursorIcon::Grab);
471                row.dnd_set_drag_payload(PartsDrag { occurrences: vec![occurrence.clone()], part: part.clone() });
472                if row.dragged() {
473                    drag_label(ui, part);
474                }
475                self.hit(format!("instructions:unplanned:{occurrence}"), row.rect);
476                if let Some(selected) = self.selected.clone() {
477                    let button = ui.add(ui_kit::Button::new("Add to selected step").size(ui_kit::Size::Sm));
478                    self.hit(format!("instructions:unplanned:{occurrence}:add"), button.rect);
479                    if button.clicked() {
480                        *change = Some(Change::AddParts { step: selected, occurrences: vec![occurrence.clone()] });
481                    }
482                }
483            });
484        }
485        ui.separator();
486    }
487
488    fn step_list(&mut self, ui: &mut egui::Ui, block: &Instructions, shown: Option<&str>, change: &mut Option<Change>) {
489        let root = ui
490            .add(ui_kit::Button::new("Steps (top level)").min_width(ui.available_width()))
491            .on_hover_text("Drop a step here to move it and its children to the end of the top level");
492        self.hit("instructions:root", root.rect);
493        if root.dnd_hover_payload::<StepDrag>().is_some() {
494            ui.painter().rect_stroke(root.rect, 2.0, ui.visuals().selection.stroke, egui::StrokeKind::Outside);
495        }
496        // Do not consume a BOM/part payload: only steps belong at the root.
497        if egui::DragAndDrop::has_payload_of_type::<StepDrag>(ui.ctx()) {
498            if let Some(dragged) = root.dnd_release_payload::<StepDrag>() {
499                *change = Some(Change::Nest { step: dragged.0.clone(), parent: None, index: usize::MAX });
500            }
501        }
502        if block.steps.is_empty() {
503            ui.weak("No steps yet: press Wizard on the toolbar.");
504            return;
505        }
506        let empty = edit::empty_steps(block);
507        let numbers: HashMap<&str, usize> = block.steps().enumerate().map(|(i, (_, s))| (s.id.as_str(), i + 1)).collect();
508        ui.indent("instructions-root", |ui| self.step_rows(ui, &block.steps, &numbers, &empty, shown, change));
509    }
510
511    /// The step tree: a step's row, then its children indented under it. The
512    /// numbers are the reading order, in which the children come first.
513    fn step_rows(
514        &mut self,
515        ui: &mut egui::Ui,
516        steps: &[Step],
517        numbers: &HashMap<&str, usize>,
518        empty: &[String],
519        shown: Option<&str>,
520        change: &mut Option<Change>,
521    ) {
522        for step in steps {
523            let number = numbers.get(step.id.as_str()).copied().unwrap_or(0);
524            let mut text = format!("{number}. {}", step.title);
525            if empty.contains(&step.id) {
526                text.push_str("  (no parts)");
527            }
528            let selected = self.selected.as_deref() == Some(step.id.as_str());
529            // The row is a drag source (drop it on another step to nest it)
530            // and a drop target for parts and steps. Its own response
531            // carries the drag: egui's drag-source helper lays a drag-only
532            // widget over the row, which took the click away from it.
533            let width = ui.available_width();
534            let row = ui_kit::surface::table_row(ui, &[ui_kit::surface::Cell { text: &text, width, number: false }], false, selected).interact(egui::Sense::click_and_drag());
535            row.dnd_set_drag_payload(StepDrag(step.id.clone()));
536            if row.dragged() {
537                drag_label(ui, &text);
538            }
539            self.hit(format!("instructions:step:{}", step.id), row.rect);
540            if row.dnd_hover_payload::<PartsDrag>().is_some() || row.dnd_hover_payload::<StepDrag>().is_some_and(|d| d.0 != step.id) {
541                ui.painter().rect_stroke(row.rect, 2.0, ui.visuals().selection.stroke, egui::StrokeKind::Outside);
542            }
543            // Taking a payload of one type drops a payload of another, so
544            // ask which one is carried first.
545            let (parts, steps_drag) = (
546                egui::DragAndDrop::has_payload_of_type::<PartsDrag>(ui.ctx()),
547                egui::DragAndDrop::has_payload_of_type::<StepDrag>(ui.ctx()),
548            );
549            if let Some(parts) = parts.then(|| row.dnd_release_payload::<PartsDrag>()).flatten() {
550                *change = Some(Change::AddParts { step: step.id.clone(), occurrences: parts.occurrences.clone() });
551            } else if let Some(dragged) = steps_drag.then(|| row.dnd_release_payload::<StepDrag>()).flatten() {
552                if dragged.0 != step.id {
553                    *change = Some(Change::Nest { step: dragged.0.clone(), parent: Some(step.id.clone()), index: usize::MAX });
554                }
555            } else if row.clicked() {
556                self.selected = Some(step.id.clone());
557                if shown != Some(step.id.as_str()) {
558                    *change = Some(Change::Show(step.id.clone()));
559                }
560            }
561            if !step.steps.is_empty() {
562                ui.indent(&step.id, |ui| self.step_rows(ui, &step.steps, numbers, empty, shown, change));
563            }
564        }
565    }
566
567    fn step_actions(&mut self, ui: &mut egui::Ui, block: &Instructions, step: &Step, change: &mut Option<Change>) {
568        let Some((steps, s)) = block.siblings(&step.id) else { return };
569        ui.horizontal_wrapped(|ui| {
570            let up = ui_kit::button::add_enabled(ui, s > 0, ui_kit::Button::new("Move up"));
571            self.hit("instructions:up", up.rect);
572            if up.clicked() {
573                *change = Some(Change::Restructure(Restructure::MoveStep { step: step.id.clone(), index: s - 1 }));
574            }
575            let down = ui_kit::button::add_enabled(ui, s + 1 < steps.len(), ui_kit::Button::new("Move down"));
576            self.hit("instructions:down", down.rect);
577            if down.clicked() {
578                *change = Some(Change::Restructure(Restructure::MoveStep { step: step.id.clone(), index: s + 1 }));
579            }
580            let previous = s.checked_sub(1).map(|p| steps[p].id.clone());
581            let nest = ui_kit::button::add_enabled(ui, previous.is_some(), ui_kit::Button::new("Nest under previous"))
582                .on_hover_text("This step, and the steps under it, build the previous step's group: they come before it and it installs them");
583            self.hit("instructions:nest_previous", nest.rect);
584            if nest.clicked() {
585                if let Some(previous) = previous {
586                    *change = Some(Change::Nest { step: step.id.clone(), parent: Some(previous), index: usize::MAX });
587                }
588            }
589            let parent = block.parent_id(&step.id).flatten().map(str::to_string);
590            let unnest = ui_kit::button::add_enabled(ui, parent.is_some(), ui_kit::Button::new("Unnest")).on_hover_text("Out of its group: a sibling of its parent, right after it");
591            self.hit("instructions:unnest", unnest.rect);
592            if unnest.clicked() {
593                if let Some(parent) = parent {
594                    let grandparent = block.parent_id(&parent).flatten().map(str::to_string);
595                    let index = block.siblings(&parent).map(|(_, i)| i + 1).unwrap_or(usize::MAX);
596                    *change = Some(Change::Nest { step: step.id.clone(), parent: grandparent, index });
597                }
598            }
599            let next = steps.get(s + 1).map(|next| next.id.clone());
600            let merge = ui_kit::button::add_enabled(ui, next.is_some(), ui_kit::Button::new("Merge with next")).on_hover_text("The next step's parts join this one");
601            self.hit("instructions:merge_next", merge.rect);
602            if merge.clicked() {
603                if let Some(next) = next {
604                    *change = Some(Change::Restructure(Restructure::MergeWithNext { step: step.id.clone(), next }));
605                }
606            }
607            let delete = ui_kit::button::add_enabled(ui, step.adds.is_empty() && step.steps.is_empty(), ui_kit::Button::danger("Delete"))
608                .on_disabled_hover_text("Move this step's parts, and the steps under it, elsewhere first");
609            self.hit("instructions:delete", delete.rect);
610            if delete.clicked() {
611                *change = Some(Change::Restructure(Restructure::Delete(step.id.clone())));
612            }
613        });
614        ui.horizontal_wrapped(|ui| {
615            let capture = ui.add(ui_kit::Button::new("Capture camera")).on_hover_text("The view keeps the camera as you see it now, through every edit, until Reset view");
616            self.hit("instructions:capture_camera", capture.rect);
617            if capture.clicked() {
618                *change = Some(Change::CaptureCamera(step.id.clone()));
619            }
620            let reset = ui_kit::button::add_enabled(ui, step.camera_captured, ui_kit::Button::new("Reset view"))
621                .on_hover_text("Back to the generated camera: everything this step shows, from its parent step's direction")
622                .on_disabled_hover_text("The camera is generated from the step's parts; Capture camera keeps your own");
623            self.hit("instructions:reset_view", reset.rect);
624            if reset.clicked() {
625                *change = Some(Change::ResetView(step.id.clone()));
626            }
627            if step.camera_captured {
628                ui.weak("captured camera");
629            }
630        });
631    }
632
633    fn step_editor(&mut self, ui: &mut egui::Ui, block: &Instructions, step: &Step, change: &mut Option<Change>) {
634        let id = step.id.clone();
635        let (steps, s) = block.siblings(&id).expect("a listed step");
636
637        // --- title ------------------------------------------------------------
638        let mut title = step.title.clone();
639        ui.horizontal(|ui| {
640            ui.label("Title");
641            let field = ui.text_edit_singleline(&mut title);
642            self.hit("instructions:field:title", field.rect);
643            if field.changed() {
644                *change = Some(step_change(&id, "title", move |step| step.title = title));
645            }
646        });
647
648        // --- parts ------------------------------------------------------------
649        ui.label(egui::RichText::new("Parts").strong());
650        if step.adds.is_empty() {
651            ui.weak("No parts: move some here from a neighbouring step.");
652        }
653        for (index, add) in step.adds.iter().enumerate() {
654            ui.horizontal_wrapped(|ui| {
655                let mut text = String::new();
656                if !add.find_number.is_empty() {
657                    text.push_str(&format!("[{}] ", add.find_number));
658                }
659                text.push_str(add.display_name());
660                if add.quantity() > 1 {
661                    text.push_str(&format!(" × {}", add.quantity()));
662                }
663                if add.subassembly {
664                    text.push_str(" (sub-assembly)");
665                }
666                let label = ui.label(text);
667                self.hit(format!("instructions:add:{index}"), label.rect);
668                let unplan = ui.add(ui_kit::Button::new("Unplan").size(ui_kit::Size::Sm)).on_hover_text("Out of every step: the part goes back to Not yet planned");
669                self.hit(format!("instructions:add:{index}:unplan"), unplan.rect);
670                if unplan.clicked() {
671                    *change = Some(Change::RemoveAdd { step: id.clone(), add: index });
672                }
673                if let Some(previous) = s.checked_sub(1).map(|p| steps[p].id.clone()) {
674                    let button = ui.add(ui_kit::Button::new("To previous step").size(ui_kit::Size::Sm));
675                    self.hit(format!("instructions:add:{index}:previous"), button.rect);
676                    if button.clicked() {
677                        *change = Some(Change::Restructure(Restructure::MoveAdd { from: id.clone(), add: index, to: previous }));
678                    }
679                }
680                if let Some(next) = steps.get(s + 1).map(|n| n.id.clone()) {
681                    let button = ui.add(ui_kit::Button::new("To next step").size(ui_kit::Size::Sm));
682                    self.hit(format!("instructions:add:{index}:next"), button.rect);
683                    if button.clicked() {
684                        *change = Some(Change::Restructure(Restructure::MoveAdd { from: id.clone(), add: index, to: next }));
685                    }
686                }
687                if step.adds.len() > 1 {
688                    let button = ui.add(ui_kit::Button::new("Split out").size(ui_kit::Size::Sm)).on_hover_text("This part gets a step of its own, right after this one");
689                    self.hit(format!("instructions:add:{index}:split"), button.rect);
690                    if button.clicked() {
691                        *change = Some(Change::Restructure(Restructure::Split { step: id.clone(), add: index }));
692                    }
693                }
694            });
695        }
696
697        // --- torque -----------------------------------------------------------
698        let mut torque = step.torque.as_ref().map(Torque::text).unwrap_or_default();
699        ui.horizontal(|ui| {
700            ui.label("Torque");
701            let field = ui.add(egui::TextEdit::singleline(&mut torque).hint_text("e.g. 12 N·m").desired_width(120.0));
702            self.hit("instructions:field:torque", field.rect);
703            match step.torque.as_ref().map(|t| t.source) {
704                Some(TorqueSource::Part) => {
705                    ui.weak("from the part");
706                }
707                Some(TorqueSource::Override) => {
708                    ui.weak("set on this step");
709                }
710                None => {}
711            }
712            if field.changed() {
713                *change = Some(step_change(&id, "torque", move |step| {
714                    step.torque = Torque::from_attribute(&torque).map(|t| Torque { source: TorqueSource::Override, ..t });
715                }));
716            }
717        });
718
719        // --- tools ------------------------------------------------------------
720        ui.label(egui::RichText::new("Tools").strong());
721        for (index, tool) in step.tools.iter().enumerate() {
722            ui.horizontal(|ui| {
723                let mut text = tool.name.clone();
724                if !tool.spec.is_empty() {
725                    text.push_str(&format!(" — {}", tool.spec));
726                }
727                if tool.unlinked {
728                    text.push_str(" (not in the tools library)");
729                }
730                ui.label(text);
731                let remove = ui.add(ui_kit::Button::new("✕").size(ui_kit::Size::Sm)).on_hover_text("Remove this tool from the step");
732                self.hit(format!("instructions:tool:{index}:remove"), remove.rect);
733                if remove.clicked() {
734                    *change = Some(step_change(&id, "", move |step| {
735                        step.tools.remove(index);
736                    }));
737                }
738            });
739        }
740        ui.horizontal_wrapped(|ui| {
741            let name = ui.add(egui::TextEdit::singleline(&mut self.tool_draft.0).hint_text("Tool").desired_width(110.0));
742            self.hit("instructions:tool:name", name.rect);
743            let spec = ui.add(egui::TextEdit::singleline(&mut self.tool_draft.1).hint_text("Spec").desired_width(110.0));
744            self.hit("instructions:tool:spec", spec.rect);
745            let add = ui_kit::button::add_enabled(ui, !self.tool_draft.0.trim().is_empty(), ui_kit::Button::new("Add tool"));
746            self.hit("instructions:tool:add", add.rect);
747            if add.clicked() {
748                let (name, spec) = std::mem::take(&mut self.tool_draft);
749                *change = Some(step_change(&id, "", move |step| {
750                    step.tools.push(ToolUse { tool_id: None, name: name.trim().into(), spec: spec.trim().into(), unlinked: true });
751                }));
752            }
753        });
754
755        // --- callouts ---------------------------------------------------------
756        ui.label(egui::RichText::new("Callouts").strong());
757        for (index, callout) in step.callouts.iter().enumerate() {
758            ui.horizontal(|ui| {
759                ui.label(format!("{}:", callout.kind.label()));
760                let mut text = callout.text.clone();
761                let field = ui.text_edit_singleline(&mut text);
762                self.hit(format!("instructions:callout:{index}:text"), field.rect);
763                if field.changed() {
764                    *change = Some(step_change(&id, &format!("callout:{index}"), move |step| {
765                        if let Some(callout) = step.callouts.get_mut(index) {
766                            callout.text = text;
767                        }
768                    }));
769                }
770                let remove = ui.add(ui_kit::Button::new("✕").size(ui_kit::Size::Sm));
771                self.hit(format!("instructions:callout:{index}:remove"), remove.rect);
772                if remove.clicked() {
773                    *change = Some(step_change(&id, "", move |step| {
774                        step.callouts.remove(index);
775                    }));
776                }
777            });
778            // The part the callout points at: picked in the viewport.
779            if self.occurrence_field(ui, &format!("callout:{index}"), &id, InstructionsRefField::Callout(index), callout.occurrence.as_deref(), change) {
780                *change = Some(step_change(&id, "", move |step| {
781                    if let Some(callout) = step.callouts.get_mut(index) {
782                        callout.occurrence = None;
783                    }
784                }));
785            }
786        }
787        ui.horizontal(|ui| {
788            for kind in [CalloutKind::Caution, CalloutKind::Note, CalloutKind::Check] {
789                let button = ui.add(ui_kit::Button::new(&format!("+ {}", kind.label())).size(ui_kit::Size::Sm));
790                self.hit(format!("instructions:callout:add:{}", kind.label().to_lowercase()), button.rect);
791                if button.clicked() {
792                    *change = Some(Change::Step {
793                        step: id.clone(),
794                        coalesce: None,
795                        apply: Box::new(move |step: &mut Step| step.callouts.push(Callout { id: String::new(), kind, text: String::new(), occurrence: None })),
796                    });
797                }
798            }
799        });
800
801        // --- insertion arrows -------------------------------------------------
802        ui.label(egui::RichText::new("Insertion arrows").strong());
803        for (index, arrow) in step.arrows.iter().enumerate() {
804            ui.horizontal_wrapped(|ui| {
805                ui.label(format!("Arrow {}", index + 1));
806                let side = ARROW_SIDES.iter().position(|(_, d)| same_direction(*d, arrow.direction));
807                let mut picked = side;
808                // The six sides by index; a direction none of them matches
809                // (set through automation) shows as "custom", listed only then.
810                const SIDE_IDS: [&str; 6] = ["0", "1", "2", "3", "4", "5"];
811                let mut choices: Vec<(Option<usize>, &str, &str)> =
812                    ARROW_SIDES.iter().enumerate().map(|(i, (label, _))| (Some(i), SIDE_IDS[i], *label)).collect();
813                if side.is_none() {
814                    choices.push((None, "custom", "custom"));
815                }
816                let mut rects = HashMap::new();
817                crate::form::enum_dropdown(ui, &format!("instructions:arrow:{index}:side"), &choices, &mut picked, None, Some(&mut rects));
818                for (key, rect) in rects {
819                    self.hit(key, rect);
820                }
821                if picked != side {
822                    if let Some(i) = picked {
823                        let direction = ARROW_SIDES[i].1;
824                        *change = Some(step_change(&id, "", move |step| {
825                            if let Some(arrow) = step.arrows.get_mut(index) {
826                                arrow.direction = direction;
827                            }
828                        }));
829                    }
830                }
831                let mut distance = arrow.distance;
832                let drag = ui.add(egui::DragValue::new(&mut distance).range(0.0..=10_000.0).suffix(" mm"));
833                self.hit(format!("instructions:arrow:{index}:distance"), drag.rect);
834                if drag.changed() {
835                    *change = Some(step_change(&id, &format!("arrow:{index}"), move |step| {
836                        if let Some(arrow) = step.arrows.get_mut(index) {
837                            arrow.distance = distance;
838                        }
839                    }));
840                }
841                let remove = ui.add(ui_kit::Button::new("✕").size(ui_kit::Size::Sm));
842                self.hit(format!("instructions:arrow:{index}:remove"), remove.rect);
843                if remove.clicked() {
844                    *change = Some(step_change(&id, "", move |step| {
845                        step.arrows.remove(index);
846                    }));
847                }
848            });
849            // The part the arrow moves: one of the step's own, picked in the
850            // viewport; clearing it removes the arrow (an arrow moves a part).
851            if self.occurrence_field(ui, &format!("arrow:{index}"), &id, InstructionsRefField::Arrow(index), Some(&arrow.occurrence), change) {
852                *change = Some(step_change(&id, "", move |step| {
853                    if index < step.arrows.len() {
854                        step.arrows.remove(index);
855                    }
856                }));
857            }
858        }
859        // An arrow for the first occurrence of this step that has none.
860        let free = step
861            .adds
862            .iter()
863            .flat_map(|add| add.occurrences.iter())
864            .find(|occurrence| !step.arrows.iter().any(|arrow| &arrow.occurrence == *occurrence))
865            .cloned();
866        let add = ui_kit::button::add_enabled(ui, free.is_some(), ui_kit::Button::new("+ Arrow")).on_hover_text("The part slides in from above; pick the side and distance");
867        self.hit("instructions:arrow:add", add.rect);
868        if add.clicked() {
869            if let Some(occurrence) = free {
870                *change = Some(step_change(&id, "", move |step| {
871                    step.arrows.push(Arrow { occurrence, direction: ARROW_SIDES[0].1, distance: ARROW_DISTANCE });
872                }));
873            }
874        }
875
876        // --- motion: a study's published motion plays in place of the slide ---
877        ui.label(egui::RichText::new("Motion").strong());
878        ui.horizontal_wrapped(|ui| {
879            let attached = step.motion.as_ref().and_then(|m| m.get("study")).and_then(|v| v.as_str()).map(str::to_string);
880            let frames = step.motion.as_ref().and_then(|m| m.get("frames")).and_then(|f| f.as_array()).map_or(0, Vec::len);
881            let label = match &attached {
882                Some(study) => {
883                    let name = self.published.iter().find(|p| &p.study == study).map_or(study.as_str(), |p| p.name.as_str());
884                    format!("{name} ({frames} frames)")
885                }
886                None if self.published.is_empty() => "None published: Publish a study in the assembly's Simulation pane".to_string(),
887                None => "None".to_string(),
888            };
889            let mut picked: Option<String> = None;
890            // As wide as the pane leaves (a remove button may follow), so the
891            // long "None published: …" reading truncates inside the pane
892            // instead of running off it (ui-polish-2026-10-28 row 1).
893            // Measured to the clip (a child that once overflowed widens the
894            // Ui's max_rect for good), and TRUNCATED: in a horizontal row a
895            // ComboBox inherits `Extend`, so without it the button grew to its
896            // 60-character reading (534 pt in a 383-pt pane) whatever width
897            // it was given.
898            let edge = ui.max_rect().right().min(ui.clip_rect().right());
899            let width = (edge - ui.cursor().left() - 36.0).clamp(120.0, 480.0);
900            let combo = egui::ComboBox::from_id_salt("instructions-motion").width(width).truncate().selected_text(label).show_ui(ui, |ui| {
901                for (index, motion) in self.published.iter().enumerate() {
902                    let text = if motion.current { format!("{} ({} frames)", motion.name, motion.frames) } else { format!("{} (published before the assembly changed)", motion.name) };
903                    let option = ui_kit::button::add_enabled(ui, motion.current, ui_kit::Button::new(&text).selected(attached.as_deref() == Some(motion.study.as_str())));
904                    self.hits.insert(format!("instructions:menuitem:motion:{index}"), option.rect);
905                    if option.clicked() {
906                        picked = Some(motion.study.clone());
907                    }
908                }
909            });
910            self.hits.insert("instructions:motion:study".into(), combo.response.rect);
911            if let Some(study) = picked {
912                *change = Some(Change::AttachMotion { step: id.clone(), study });
913            }
914            if attached.is_some() {
915                let remove = ui.add(ui_kit::Button::new("✕").size(ui_kit::Size::Sm)).on_hover_text("Take the motion off: the insertion arrows play again");
916                self.hits.insert("instructions:motion:remove".into(), remove.rect);
917                if remove.clicked() {
918                    *change = Some(step_change(&id, "", |step| step.motion = None));
919                }
920            }
921        });
922
923        self.fields_editor(ui, step, change);
924
925        // --- notes and sign-off -----------------------------------------------
926        ui.label(egui::RichText::new("Notes").strong());
927        let mut notes = step.notes.clone();
928        let field = ui.add(egui::TextEdit::multiline(&mut notes).desired_rows(3).desired_width(f32::INFINITY));
929        self.hit("instructions:field:notes", field.rect);
930        if field.changed() {
931            *change = Some(step_change(&id, "notes", move |step| step.notes = notes));
932        }
933        let mut required = step.signoff.required;
934        let check = ui_kit::checkbox(ui, &mut required, "Sign-off required on the shop floor");
935        self.hit("instructions:field:signoff", check.rect);
936        if check.changed() {
937            *change = Some(step_change(&id, "", move |step| step.signoff.required = required));
938        }
939    }
940
941    /// The step's fields: what the person doing the work records there. One
942    /// block per field — its label, its kind (a dropdown), whether it is
943    /// required, up / down / remove, a line of help, and the kind's own
944    /// settings (a choice's options as an editable list) — then one button
945    /// per kind to add another. Every edit is one undo step; a typing run in
946    /// one box coalesces.
947    fn fields_editor(&mut self, ui: &mut egui::Ui, step: &Step, change: &mut Option<Change>) {
948        let id = step.id.clone();
949        ui.label(egui::RichText::new("Fields to record").strong()).on_hover_text(
950            "What the person doing the work fills in at this step: the players show them in shop mode, the PDF prints them as a form",
951        );
952        if step.fields.is_empty() {
953            ui.weak("None: add a checkbox, a choice, text, a measurement or a serial number.");
954        }
955        let count = step.fields.len();
956        let mut focused_drafts: Vec<String> = Vec::new();
957        for (index, field) in step.fields.iter().enumerate() {
958            let key = format!("instructions:stepfield:{index}");
959            // One edit of this field, addressed by its id (the index may
960            // have moved by the time the edit is applied).
961            let field_id = field.id.clone();
962            let edit_field = |run: &str, apply: Box<dyn FnOnce(&mut StepField)>| -> Change {
963                let field_id = field_id.clone();
964                step_change(&id, &if run.is_empty() { String::new() } else { format!("stepfield:{field_id}:{run}") }, move |step| {
965                    if let Some(field) = step.fields.iter_mut().find(|f| f.id == field_id) {
966                        apply(field);
967                    }
968                })
969            };
970            ui.separator();
971            ui.horizontal_wrapped(|ui| {
972                let mut label = field.label.clone();
973                let text = ui.add(egui::TextEdit::singleline(&mut label).hint_text("Label").desired_width(150.0));
974                self.hit(format!("{key}:label"), text.rect);
975                if text.changed() {
976                    *change = Some(edit_field("label", Box::new(move |f| f.label = label)));
977                }
978                let kinds: Vec<(&str, &str, &str)> = StepFieldKind::CHOICES.iter().map(|(k, label)| (*k, *k, *label)).collect();
979                let mut kind = field.kind.key();
980                let mut rects = HashMap::new();
981                keep_pair_together(ui, "", 120.0);
982                if crate::form::enum_dropdown(ui, &format!("{key}:kind"), &kinds, &mut kind, Some(120.0), Some(&mut rects)).0 {
983                    if let Some(new) = StepFieldKind::new(kind) {
984                        *change = Some(edit_field("", Box::new(move |f| f.kind = new)));
985                    }
986                }
987                for (k, rect) in rects {
988                    self.hit(k, rect);
989                }
990                let mut required = field.required;
991                let check = ui_kit::checkbox(ui, &mut required, "Required").on_hover_text("The step cannot be signed off or marked done until this is filled in");
992                self.hit(format!("{key}:required"), check.rect);
993                if check.changed() {
994                    *change = Some(edit_field("", Box::new(move |f| f.required = required)));
995                }
996                let up = ui_kit::button::add_enabled(ui, index > 0, ui_kit::Button::new("▲").size(ui_kit::Size::Sm)).on_hover_text("Move this field up");
997                self.hit(format!("{key}:up"), up.rect);
998                let down = ui_kit::button::add_enabled(ui, index + 1 < count, ui_kit::Button::new("▼").size(ui_kit::Size::Sm)).on_hover_text("Move this field down");
999                self.hit(format!("{key}:down"), down.rect);
1000                for (button, to) in [(up, index.wrapping_sub(1)), (down, index + 1)] {
1001                    if button.clicked() {
1002                        let field_id = field.id.clone();
1003                        *change = Some(step_change(&id, "", move |step| {
1004                            if let Some(at) = step.fields.iter().position(|f| f.id == field_id) {
1005                                let moved = step.fields.remove(at);
1006                                step.fields.insert(to.min(step.fields.len()), moved);
1007                            }
1008                        }));
1009                    }
1010                }
1011                let remove = ui.add(ui_kit::Button::new("✕").size(ui_kit::Size::Sm)).on_hover_text("Remove this field from the step");
1012                self.hit(format!("{key}:remove"), remove.rect);
1013                if remove.clicked() {
1014                    let field_id = field.id.clone();
1015                    *change = Some(step_change(&id, "", move |step| step.fields.retain(|f| f.id != field_id)));
1016                }
1017            });
1018            match &field.kind {
1019                StepFieldKind::Check | StepFieldKind::Serial => {}
1020                StepFieldKind::Choice { options, multiple, other } => {
1021                    for (k, option) in options.iter().enumerate() {
1022                        ui.horizontal(|ui| {
1023                            ui.add_space(12.0);
1024                            let mut text = option.clone();
1025                            let edit = ui.add(egui::TextEdit::singleline(&mut text).hint_text("Option").desired_width(170.0));
1026                            self.hit(format!("{key}:option:{k}"), edit.rect);
1027                            if edit.changed() {
1028                                *change = Some(edit_field(&format!("option:{k}"), Box::new(move |f| {
1029                                    if let StepFieldKind::Choice { options, .. } = &mut f.kind {
1030                                        if let Some(option) = options.get_mut(k) {
1031                                            *option = text;
1032                                        }
1033                                    }
1034                                })));
1035                            }
1036                            let remove = ui_kit::button::add_enabled(ui, options.len() > 1, ui_kit::Button::new("✕").size(ui_kit::Size::Sm)).on_hover_text("Remove this option");
1037                            self.hit(format!("{key}:option:{k}:remove"), remove.rect);
1038                            if remove.clicked() {
1039                                *change = Some(edit_field("", Box::new(move |f| {
1040                                    if let StepFieldKind::Choice { options, .. } = &mut f.kind {
1041                                        if k < options.len() && options.len() > 1 {
1042                                            options.remove(k);
1043                                        }
1044                                    }
1045                                })));
1046                            }
1047                        });
1048                    }
1049                    ui.horizontal_wrapped(|ui| {
1050                        ui.add_space(12.0);
1051                        let full = options.len() >= brep_instructions::fields::MAX_OPTIONS;
1052                        let add = ui_kit::button::add_enabled(ui, !full, ui_kit::Button::new("+ Option").size(ui_kit::Size::Sm));
1053                        self.hit(format!("{key}:option:add"), add.rect);
1054                        if add.clicked() {
1055                            let name = format!("Option {}", options.len() + 1);
1056                            *change = Some(edit_field("", Box::new(move |f| {
1057                                if let StepFieldKind::Choice { options, .. } = &mut f.kind {
1058                                    options.push(name);
1059                                }
1060                            })));
1061                        }
1062                        let mut several = *multiple;
1063                        let check = ui_kit::checkbox(ui, &mut several, "Pick several").on_hover_text("Any number of the options may be picked (on paper: mark all that apply)");
1064                        self.hit(format!("{key}:multiple"), check.rect);
1065                        if check.changed() {
1066                            *change = Some(edit_field("", Box::new(move |f| {
1067                                if let StepFieldKind::Choice { multiple, .. } = &mut f.kind {
1068                                    *multiple = several;
1069                                }
1070                            })));
1071                        }
1072                        let mut allow = *other;
1073                        let check = ui_kit::checkbox(ui, &mut allow, "Allow Other").on_hover_text("A free-text Other value beside the options");
1074                        self.hit(format!("{key}:other"), check.rect);
1075                        if check.changed() {
1076                            *change = Some(edit_field("", Box::new(move |f| {
1077                                if let StepFieldKind::Choice { other, .. } = &mut f.kind {
1078                                    *other = allow;
1079                                }
1080                            })));
1081                        }
1082                    });
1083                }
1084                StepFieldKind::Text { lines } => {
1085                    ui.horizontal(|ui| {
1086                        ui.add_space(12.0);
1087                        ui.label("Lines");
1088                        let mut count = *lines;
1089                        let drag = ui
1090                            .add(egui::DragValue::new(&mut count).range(1..=brep_instructions::fields::MAX_TEXT_LINES))
1091                            .on_hover_text("1 is a single line; more is a box that many lines tall, in the players and on paper");
1092                        self.hit(format!("{key}:lines"), drag.rect);
1093                        if drag.changed() {
1094                            *change = Some(edit_field("lines", Box::new(move |f| {
1095                                if let StepFieldKind::Text { lines } = &mut f.kind {
1096                                    *lines = count;
1097                                }
1098                            })));
1099                        }
1100                    });
1101                }
1102                StepFieldKind::Number { unit, nominal, min, max, decimals, required_in_limits } => {
1103                    ui.horizontal_wrapped(|ui| {
1104                        ui.add_space(12.0);
1105                        ui.label("Unit");
1106                        let mut text = unit.clone();
1107                        let edit = ui.add(egui::TextEdit::singleline(&mut text).hint_text("mm").desired_width(48.0));
1108                        self.hit(format!("{key}:unit"), edit.rect);
1109                        if edit.changed() {
1110                            *change = Some(edit_field("unit", Box::new(move |f| {
1111                                if let StepFieldKind::Number { unit, .. } = &mut f.kind {
1112                                    *unit = text;
1113                                }
1114                            })));
1115                        }
1116                        for (what, label, current) in [("nominal", "Nominal", *nominal), ("min", "Min", *min), ("max", "Max", *max)] {
1117                            keep_pair_together(ui, label, 64.0);
1118                            ui.label(label);
1119                            let draft_key = format!("{key}:{what}");
1120                            let mut text = self.number_drafts.get(&draft_key).cloned().unwrap_or_else(|| current.map(|v| v.to_string()).unwrap_or_default());
1121                            let edit = ui.add(egui::TextEdit::singleline(&mut text).hint_text("none").desired_width(64.0));
1122                            self.hit(draft_key.clone(), edit.rect);
1123                            if edit.has_focus() || edit.changed() {
1124                                focused_drafts.push(draft_key.clone());
1125                                self.number_drafts.insert(draft_key.clone(), text.clone());
1126                            }
1127                            if edit.changed() {
1128                                // Blank clears it; text that is not yet a
1129                                // number ("-", "1e") waits for the rest.
1130                                let parsed = if text.trim().is_empty() { Some(None) } else { text.trim().parse::<f64>().ok().filter(|v| v.is_finite()).map(Some) };
1131                                if let Some(value) = parsed {
1132                                    *change = Some(edit_field(what, Box::new(move |f| {
1133                                        if let StepFieldKind::Number { nominal, min, max, .. } = &mut f.kind {
1134                                            match what {
1135                                                "nominal" => *nominal = value,
1136                                                "min" => *min = value,
1137                                                _ => *max = value,
1138                                            }
1139                                        }
1140                                    })));
1141                                }
1142                            }
1143                        }
1144                        keep_pair_together(ui, "Decimals", 64.0);
1145                        ui.label("Decimals");
1146                        const DECIMALS: [(Option<u8>, &str, &str); 8] = [
1147                            (None, "auto", "auto"),
1148                            (Some(0), "0", "0"),
1149                            (Some(1), "1", "1"),
1150                            (Some(2), "2", "2"),
1151                            (Some(3), "3", "3"),
1152                            (Some(4), "4", "4"),
1153                            (Some(5), "5", "5"),
1154                            (Some(6), "6", "6"),
1155                        ];
1156                        let mut picked = *decimals;
1157                        let mut rects = HashMap::new();
1158                        if crate::form::enum_dropdown(ui, &format!("{key}:decimals"), &DECIMALS, &mut picked, Some(64.0), Some(&mut rects)).0 {
1159                            *change = Some(edit_field("", Box::new(move |f| {
1160                                if let StepFieldKind::Number { decimals, .. } = &mut f.kind {
1161                                    *decimals = picked;
1162                                }
1163                            })));
1164                        }
1165                        for (k, rect) in rects {
1166                            self.hit(k, rect);
1167                        }
1168                        let mut strict = *required_in_limits;
1169                        let check = ui_kit::checkbox(ui, &mut strict, "Must be in limits")
1170                            .on_hover_text("A value outside the limits keeps the step from being completed; off: it is flagged and accepted");
1171                        self.hit(format!("{key}:in_limits"), check.rect);
1172                        if check.changed() {
1173                            *change = Some(edit_field("", Box::new(move |f| {
1174                                if let StepFieldKind::Number { required_in_limits, .. } = &mut f.kind {
1175                                    *required_in_limits = strict;
1176                                }
1177                            })));
1178                        }
1179                    });
1180                }
1181            }
1182            ui.horizontal(|ui| {
1183                ui.add_space(12.0);
1184                let mut hint = field.hint.clone();
1185                let edit = ui.add(egui::TextEdit::singleline(&mut hint).hint_text("Help shown with the field (optional)").desired_width(f32::INFINITY));
1186                self.hit(format!("{key}:hint"), edit.rect);
1187                if edit.changed() {
1188                    *change = Some(edit_field("hint", Box::new(move |f| f.hint = hint)));
1189                }
1190            });
1191        }
1192        self.number_drafts.retain(|k, _| focused_drafts.contains(k));
1193        if count > 0 {
1194            ui.separator();
1195        }
1196        ui.horizontal_wrapped(|ui| {
1197            for (kind, label) in StepFieldKind::CHOICES {
1198                let button = ui.add(ui_kit::Button::new(&format!("+ {label}")).size(ui_kit::Size::Sm));
1199                self.hit(format!("instructions:stepfield:add:{kind}"), button.rect);
1200                if button.clicked() {
1201                    let name = match kind {
1202                        "check" => "Checked",
1203                        "choice" => "Choice",
1204                        "text" => "Notes",
1205                        "number" => "Measurement",
1206                        _ => "Serial number",
1207                    };
1208                    if let Some(field) = StepField::new(String::new(), kind, name) {
1209                        *change = Some(step_change(&id, "", move |step| step.fields.push(field)));
1210                    }
1211                }
1212            }
1213        });
1214    }
1215
1216    fn apply(&mut self, change: Change, engine: &mut EngineState) {
1217        self.error = None;
1218        self.notice = None;
1219        let result = match change {
1220            Change::Show(step) => engine.instructions_show_step(&step),
1221            Change::ApproveRetarget => engine.instructions_retarget_approve().map(|target| {
1222                self.notice = Some(format!("The instructions now describe the new revision of {}", target.name));
1223            }),
1224            Change::PickOccurrence { step, field, seed } => {
1225                // Focus moves from one selection box to the next: a pick
1226                // already running commits first.
1227                if engine.ref_select_active() {
1228                    engine.finish_ref_select();
1229                }
1230                engine.begin_ref_select_for_instructions(&step, field, seed.as_deref());
1231                Ok(())
1232            }
1233            Change::FinishPick => {
1234                engine.finish_ref_select();
1235                Ok(())
1236            }
1237            Change::RemovePick(index) => {
1238                engine.ref_select_remove(index);
1239                Ok(())
1240            }
1241            Change::RejectRetarget => engine.instructions_retarget_reject().map(|target| {
1242                self.notice = Some(format!("The new revision was taken back: the instructions still describe {} {}", target.name, target.revision).trim_end().to_string());
1243            }),
1244            Change::Print(apply) => engine.instructions_edit(None, |block| {
1245                apply(block);
1246                Ok(())
1247            }),
1248            Change::AddParts { step, occurrences } => engine
1249                .instructions_add_parts(&step, &occurrences)
1250                .map(|report| {
1251                    self.selected = Some(step.clone());
1252                    let numbers = engine.instructions().ok().flatten();
1253                    let number = |id: &str| numbers.as_ref().and_then(|b| b.step_number(id)).map(|n| n.to_string()).unwrap_or_else(|| id.to_string());
1254                    let mut text = match report.added {
1255                        0 => "No part joined the step".to_string(),
1256                        1 => "1 part joined the step".to_string(),
1257                        n => format!("{n} parts joined the step"),
1258                    };
1259                    if !report.left.is_empty() {
1260                        let left: Vec<String> = report.left.iter().map(|l| format!("{} is in step {}", l.occurrence, number(&l.step))).collect();
1261                        text.push_str(&format!("; left where it is: {}", left.join(", ")));
1262                    }
1263                    self.notice = Some(text);
1264                })
1265                .and_then(|()| engine.instructions_show_step(&step)),
1266            Change::RemoveAdd { step, add } => engine.instructions_remove_add(&step, add).and_then(|()| engine.instructions_show_step(&step)),
1267            Change::Nest { step, parent, index } => engine.instructions_nest_step(&step, parent.as_deref(), index).and_then(|()| engine.instructions_show_step(&step)),
1268            Change::CaptureCamera(step) => engine.instructions_capture_camera(&step).and_then(|()| engine.instructions_show_step(&step)),
1269            Change::ResetView(step) => engine.instructions_reset_view(&step).and_then(|()| engine.instructions_show_step(&step)),
1270            Change::Restructure(edit) => {
1271                let selected = &mut self.selected;
1272                engine
1273                    .instructions_restructure(|block| match edit {
1274                        Restructure::MoveStep { step, index } => edit::move_step(block, &step, index),
1275                        Restructure::MergeWithNext { step, next } => edit::merge(block, &[&step, &next]).map(drop),
1276                        Restructure::Delete(step) => {
1277                            edit::delete_step(block, &step)?;
1278                            *selected = None;
1279                            Ok(())
1280                        }
1281                        Restructure::Split { step, add } => edit::split(block, &step, &[add]).map(|new| *selected = Some(new)),
1282                        Restructure::MoveAdd { from, add, to } => edit::move_add(block, &from, add, &to),
1283                    })
1284                    .and_then(|()| match self.selected.clone() {
1285                        Some(step) => engine.instructions_show_step(&step),
1286                        None => Ok(()),
1287                    })
1288            }
1289            Change::AttachMotion { step, study } => engine.instructions_attach_motion(&step, Some(&study)).map(|_| ()),
1290            Change::Step { step, coalesce, apply } => engine.instructions_edit(coalesce.as_deref(), |block| {
1291                let target = block.step_mut(&step).ok_or_else(|| format!("no step '{step}'"))?;
1292                apply(target);
1293                // A field just added takes the next field id.
1294                while block.step(&step).is_some_and(|s| s.fields.iter().any(|f| f.id.is_empty())) {
1295                    let fresh = block.next_id("MF");
1296                    if let Some(field) = block.step_mut(&step).and_then(|s| s.fields.iter_mut().find(|f| f.id.is_empty())) {
1297                        field.id = fresh;
1298                    }
1299                }
1300                let target = block.step_mut(&step).ok_or_else(|| format!("no step '{step}'"))?;
1301                // A callout just added takes the next callout id.
1302                if target.callouts.iter().any(|c| c.id.is_empty()) {
1303                    let fresh = block.next_id("MK");
1304                    if let Some(callout) = block.step_mut(&step).and_then(|s| s.callouts.iter_mut().find(|c| c.id.is_empty())) {
1305                        callout.id = fresh;
1306                    }
1307                }
1308                Ok(())
1309            }),
1310        };
1311        if let Err(error) = result {
1312            self.error = Some(error);
1313        }
1314    }
1315}
1316
1317/// Every step's picture, PNG and SVG, in one zip: `step-01-MS2.png` and
1318/// `step-01-MS2.svg` in reading order. File ▸ Export and `instructions_export`
1319/// both write this.
1320pub fn images_zip(engine: &mut EngineState) -> Result<Vec<u8>, String> {
1321    let block = engine.instructions()?.ok_or("this document is not manufacturing instructions")?;
1322    let mut files: Vec<(String, Vec<u8>)> = Vec::new();
1323    for (index, (_, step)) in block.steps().enumerate() {
1324        let stem = format!("step-{:02}-{}", index + 1, step.id);
1325        files.push((format!("{stem}.png"), engine.instructions_step_png(&step.id, brep_render::engine_state::INSTRUCTIONS_IMAGE_PX)?));
1326        files.push((format!("{stem}.svg"), engine.instructions_step_svg(&step.id)?.into_bytes()));
1327    }
1328    if files.is_empty() {
1329        return Err("no steps yet: run the wizard first".into());
1330    }
1331    Ok(brep_ecad_core::fabrication::zip(files.iter().map(|(name, bytes)| (name.as_str(), bytes.as_slice()))))
1332}
1333
1334/// A step field edit; `field` names the typing run that coalesces into one
1335/// undo step (empty: a one-shot edit, its own undo step).
1336/// What a dragged row shows at the pointer.
1337fn drag_label(ui: &egui::Ui, text: &str) {
1338    if let Some(pos) = ui.ctx().pointer_interact_pos() {
1339        egui::Area::new(egui::Id::new(("instructions-drag-label", text))).order(egui::Order::Tooltip).fixed_pos(pos + egui::vec2(12.0, 12.0)).show(ui.ctx(), |ui| {
1340            egui::Frame::popup(ui.style()).show(ui, |ui| {
1341                ui.label(text);
1342            });
1343        });
1344    }
1345}
1346
1347impl InstructionsPanel {
1348    /// Publish a widget's rect for the headed verifier, cut to the pane's clip
1349    /// (what a click can land on); a widget wholly off screen is not published.
1350    fn hit(&mut self, key: impl Into<String>, rect: egui::Rect) {
1351        let visible = self.clip.map_or(rect, |clip| rect.intersect(clip));
1352        if visible.is_positive() {
1353            self.hits.insert(key.into(), visible);
1354        }
1355    }
1356}
1357
1358fn step_change(step: &str, field: &str, apply: impl FnOnce(&mut Step) + 'static) -> Change {
1359    Change::Step {
1360        step: step.to_string(),
1361        coalesce: (!field.is_empty()).then(|| format!("instructions:{step}:{field}")),
1362        apply: Box::new(apply),
1363    }
1364}
1365
1366fn same_direction(a: [f64; 3], b: [f64; 3]) -> bool {
1367    let length = |v: [f64; 3]| (v[0] * v[0] + v[1] * v[1] + v[2] * v[2]).sqrt();
1368    let (la, lb) = (length(a), length(b));
1369    la > 1e-12 && lb > 1e-12 && (0..3).all(|i| (a[i] / la - b[i] / lb).abs() < 1e-6)
1370}
1371
1372pub static HIT_KEYS: &[HitKeyDoc] = &[
1373    HitKeyDoc { panel: "instructions", prefix: "panel:clip", meaning: "the visible region of the pane (scroll_into_view scrolls an instructions:* widget inside it)", command: None },
1374    HitKeyDoc { panel: "instructions", prefix: "instructions:error", meaning: "why the last action was refused", command: None },
1375    HitKeyDoc { panel: "instructions", prefix: "instructions:notice", meaning: "what the last action did", command: None },
1376    HitKeyDoc { panel: "instructions", prefix: "instructions:print:", meaning: "the print settings as dropdowns (form::enum_dropdown): style (#lineArt, #shaded: how the PDF, images and both players draw the steps), per_page (items #1, #2, #4), orientation (#Portrait, #Landscape), paper (#A4 … #Tabloid, one list), and the parts and tools list checkboxes", command: Some("instructions_update") },
1377    HitKeyDoc { panel: "instructions", prefix: "instructions:retarget:", meaning: "the pending re-target: heading, added:/removed:/replaced:<index> rows, step:<id> (show a step it changed), approve and reject (instructions_retarget_reject)", command: Some("instructions_retarget_approve") },
1378    HitKeyDoc { panel: "instructions", prefix: "instructions:unplanned:", meaning: "a part of the assembly in no step yet, by occurrence (drag it onto a step's row), and its Add to selected step button (:add)", command: Some("instructions_add_parts") },
1379    HitKeyDoc { panel: "instructions", prefix: "instructions:step:", meaning: "a step's row, by step id (a step's children are indented under it): select it and show its view; drop a BOM row or an unplanned part on it to add the parts, drop another step's row on it to nest that step under it; drag it to nest it elsewhere", command: Some("instructions_show_step") },
1380    HitKeyDoc { panel: "instructions", prefix: "instructions:root", meaning: "the top-level Steps node: drop a step here to move it and its children to the end of the top level", command: Some("instructions_move_step") },
1381    HitKeyDoc { panel: "instructions", prefix: "instructions:nest_previous", meaning: "nest the selected step under its previous sibling", command: Some("instructions_move_step") },
1382    HitKeyDoc { panel: "instructions", prefix: "instructions:unnest", meaning: "move the selected step out of its group, right after its parent", command: Some("instructions_move_step") },
1383    HitKeyDoc { panel: "instructions", prefix: "instructions:up", meaning: "move the selected step up among its siblings", command: Some("instructions_move_step") },
1384    HitKeyDoc { panel: "instructions", prefix: "instructions:down", meaning: "move the selected step down among its siblings", command: Some("instructions_move_step") },
1385    HitKeyDoc { panel: "instructions", prefix: "instructions:merge_next", meaning: "merge the next step into the selected one", command: Some("instructions_merge") },
1386    HitKeyDoc { panel: "instructions", prefix: "instructions:delete", meaning: "delete the selected (empty) step", command: Some("instructions_delete_step") },
1387    HitKeyDoc { panel: "instructions", prefix: "instructions:capture_camera", meaning: "the viewport's camera becomes the selected step's view camera, kept until Reset view", command: Some("instructions_capture_camera") },
1388    HitKeyDoc { panel: "instructions", prefix: "instructions:reset_view", meaning: "the selected step's camera is generated again from its parts (enabled while a captured camera is kept)", command: Some("instructions_reset_view") },
1389    HitKeyDoc { panel: "instructions", prefix: "instructions:field:", meaning: "the selected step's title, torque and notes fields and the sign-off checkbox", command: Some("instructions_update_step") },
1390    HitKeyDoc { panel: "instructions", prefix: "instructions:add:", meaning: "a part of the selected step (by index) and its Unplan, To previous step, To next step and Split out buttons", command: Some("instructions_move_add") },
1391    HitKeyDoc { panel: "instructions", prefix: "instructions:tool:", meaning: "the selected step's tools (remove by index) and the Tool, Spec and Add tool fields", command: Some("instructions_update_step") },
1392    HitKeyDoc { panel: "instructions", prefix: "instructions:callout:", meaning: "the selected step's callouts (text and remove by index, and the part it points at: `<index>:occurrence` with `#activate` to pick a solid in the viewport, `#line0` the stored part and `#x0` to clear it) and the + Caution, + Note and + Check buttons", command: Some("instructions_update_step") },
1393    HitKeyDoc { panel: "instructions", prefix: "instructions:arrow:", meaning: "the selected step's insertion arrows (side, distance and remove by index — `<index>:side` is a dropdown whose entries are `<index>:side#<side index>` while open — and the part it moves: `<index>:occurrence` with `#activate` to pick one of the step's own solids in the viewport, `#line0` the part and `#x0` to remove the arrow) and + Arrow", command: Some("instructions_update_step") },
1394    HitKeyDoc { panel: "instructions", prefix: "instructions:stepfield:", meaning: "the selected step's fields to record, by index: `<index>:label`, `<index>:kind` (a dropdown: `#check`, `#choice`, `#text`, `#number`, `#serial` while open), `<index>:required`, `<index>:up`, `<index>:down`, `<index>:remove`, `<index>:hint`; a choice's `<index>:option:<n>` (text), `:option:<n>:remove`, `:option:add`, `:multiple`, `:other`; a text's `:lines`; a measurement's `:unit`, `:nominal`, `:min`, `:max`, `:decimals` (a dropdown: `#auto`, `#0` … `#6`), `:in_limits`; and the add buttons `add:check`, `add:choice`, `add:text`, `add:number`, `add:serial`", command: Some("instructions_add_field") },
1395    HitKeyDoc { panel: "instructions", prefix: "instructions:motion:", meaning: "the selected step's Motion row: the study menu (:study; a published study of the assembly plays in place of the insertion arrows) and remove (:remove)", command: Some("instructions_attach_motion") },
1396    HitKeyDoc { panel: "instructions", prefix: "instructions:menuitem:motion:", meaning: "the Motion menu's entries, by published study index (a stale one is greyed)", command: Some("instructions_attach_motion") },
1397];
1398