BREP_app 0.23.0

The BREP CAD application: an eframe (egui + wgpu) host that draws the brep-render 3D engine into an egui frame — native + wasm from one codebase.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
//! The Player pane — the Instructions workbench's
//! ([`crate::workbench::instructions`]) in-app player: Back and Next through
//! the steps in reading order, each step shown through its view (the parts
//! earlier steps placed ghosted, the parts it adds solid and moving home
//! along their insertion arrows).
//!
//! Two modes, as the HTML player has:
//!
//! * **shop** — touch-first: large buttons, the step's parts as a checklist
//!   (with a serial field per unit of a serial-tracked part), tools, torque,
//!   callouts and notes, the fields the author asked to be recorded (a box
//!   to tick, a choice, text, a measurement judged against its limits, a
//!   serial number), and a Sign off button on a step that needs it once
//!   every part is ticked and every required field is in;
//! * **customer** — pictures first: the step's title, its parts by find
//!   number and quantity, and its callouts; nothing else.
//!
//! The ticks, serials, field values and sign-offs are the pane's, for this session: they
//! are a build's record, not the document's, so they never dirty it or
//! enter its undo. The jobs floor queue keeps the record for a real build.

use crate::automation::hit_keys::HitKeyDoc;
use crate::panels::instructions::PartsDrag;
use brep_instructions::fields::{self, FieldKind, StepField};
use brep_instructions::model::{CalloutKind, Instructions, Step};
use brep_instructions::player::Mode;
use brep_render::engine_state::{EngineState, PlayTo};
use std::collections::{BTreeMap, BTreeSet, HashMap};

/// A shop-mode button's height: big enough for a gloved finger.
const TOUCH_HEIGHT: f32 = 44.0;

#[derive(Default)]
pub struct InstructionsPlayerPanel {
    hits: HashMap<String, egui::Rect>,
    /// The PLM client of the open session, for the tools' pictures.
    client: Option<std::rc::Rc<crate::plm::client::PlmClient>>,
    /// The tools' pictures decoded and loaded, by tool id.
    pictures: HashMap<String, egui::TextureHandle>,
    mode: Mode,
    /// Where to go on the next frame drawn (a toolbar button or a command).
    request: Option<PlayTo>,
    /// Ticked parts: step id → indices into the step's `adds`.
    checked: BTreeMap<String, BTreeSet<usize>>,
    /// Captured serials: occurrence path → serial.
    serials: BTreeMap<String, String>,
    /// Recorded field values: step id → field id → the value, as JSON
    /// (`brep_instructions::fields`: a tick is `true`, a choice its option
    /// or an array of them, text and a measurement as typed).
    values: BTreeMap<String, BTreeMap<String, serde_json::Value>>,
    /// Single choices showing their Other box: `(step id, field id)`.
    other_open: BTreeSet<(String, String)>,
    /// Steps signed off.
    signed: BTreeSet<String>,
    error: Option<String>,
    /// What the last drop said ("2 parts joined the step").
    notice: Option<String>,
    /// A BOM row (or a not-yet-planned part) dropped on the shown step's
    /// title this frame: the step and the occurrences, applied after drawing.
    drop: Option<(String, Vec<String>)>,
}

impl InstructionsPlayerPanel {
    pub fn new() -> Self {
        Self::default()
    }

    /// Go somewhere on the next frame the pane draws.
    pub fn request(&mut self, to: PlayTo) {
        self.request = Some(to);
    }

    pub fn mode(&self) -> Mode {
        self.mode
    }

    pub fn set_mode(&mut self, mode: Mode) {
        self.mode = mode;
    }

    pub fn hits_json(&self) -> String {
        crate::automation::hit_rects::hits_json(&self.hits)
    }

    /// Drop the published rects: the dock calls this for a pane it did not
    /// draw this frame.
    pub fn clear_hits(&mut self) {
        self.hits.clear();
    }

    /// What automation reads: the mode, the step shown and how far its parts
    /// have come home (null once they are), and the build's record.
    pub fn state_json(&self, engine: &EngineState) -> String {
        serde_json::json!({
            "mode": self.mode.as_str(),
            "step": engine.instructions_shown_step(),
            "insertion": engine.instructions_insertion_fraction(),
            "pending": self.request.is_some(),
            "checked": self.checked,
            "serials": self.serials,
            "fields": self.values,
            "missing": self.open_reasons(engine),
            "signed": self.signed,
            "error": self.error,
            "notice": self.notice,
        })
        .to_string()
    }

    /// What still keeps the shown step from being signed off or marked
    /// done, as the button's hover says it; empty when nothing does, when no
    /// step is shown, and for a step that is not on the checklist.
    fn open_reasons(&self, engine: &EngineState) -> Vec<String> {
        let Some(id) = engine.instructions_shown_step() else { return Vec::new() };
        let Ok(Some(block)) = engine.instructions() else { return Vec::new() };
        match block.step(&id) {
            Some(step) if step.on_checklist() && !self.signed.contains(&step.id) => self.reasons(step),
            _ => Vec::new(),
        }
    }

    /// Why `step` cannot be completed yet: parts not ticked, serials not
    /// entered, required fields empty, measurements out of limits.
    fn reasons(&self, step: &Step) -> Vec<String> {
        let mut reasons: Vec<String> = Vec::new();
        let ticked = self.checked.get(&step.id).map_or(0, BTreeSet::len);
        if ticked != step.adds.len() {
            reasons.push("tick every part".into());
        }
        let serials_in = step
            .adds
            .iter()
            .filter(|add| add.serial_tracked)
            .flat_map(|add| &add.occurrences)
            .all(|occurrence| self.serials.get(occurrence).is_some_and(|serial| !serial.trim().is_empty()));
        if !serials_in {
            reasons.push("enter every serial".into());
        }
        let values = self.values.get(&step.id);
        reasons.extend(fields::missing(&step.fields, |id| values.and_then(|v| v.get(id))));
        reasons
    }

    pub fn show(&mut self, ui: &mut egui::Ui, engine: &mut EngineState, client: Option<&std::rc::Rc<crate::plm::client::PlmClient>>) {
        self.client = client.cloned();
        self.hits.clear();
        self.hits.insert("panel:clip".into(), ui.clip_rect());
        if !engine.is_instructions() {
            ui.label("Open instructions to play them: New from assembly on the toolbar makes some.");
            return;
        }
        let mut go = self.request.take();
        let block = match engine.instructions() {
            Ok(Some(block)) => block,
            Ok(None) => return,
            Err(error) => {
                ui.colored_label(ui.visuals().error_fg_color, format!("The instructions cannot be read: {error}"));
                return;
            }
        };
        let order: Vec<&Step> = block.steps().map(|(_, step)| step).collect();
        let shown = engine.instructions_shown_step();
        let at = shown.as_deref().and_then(|id| order.iter().position(|step| step.id == id));

        ui.horizontal(|ui| {
            for mode in [Mode::Shop, Mode::Customer] {
                let label = if mode == Mode::Shop { "Shop" } else { "Customer" };
                let toggle = ui.selectable_label(self.mode == mode, label);
                self.hits.insert(format!("player:mode:{}", mode.as_str()), toggle.rect);
                if toggle.clicked() {
                    self.mode = mode;
                }
            }
        });
        if let Some(error) = &self.error {
            let label = ui.colored_label(ui.visuals().error_fg_color, error);
            self.hits.insert("player:error".into(), label.rect);
        }
        if order.is_empty() {
            ui.weak("No steps yet: press Wizard on the toolbar.");
            return;
        }
        let height = if self.mode == Mode::Shop { TOUCH_HEIGHT } else { 0.0 };
        ui.horizontal_wrapped(|ui| {
            let back = ui.add_enabled(at.is_some_and(|i| i > 0), egui::Button::new("◀ Back").min_size(egui::vec2(0.0, height)));
            self.hits.insert("player:back".into(), back.rect);
            if back.clicked() {
                go = Some(PlayTo::Back);
            }
            let next_label = if at.is_none() { "Start ▶" } else { "Next ▶" };
            let next = ui.add_enabled(at.is_none_or(|i| i + 1 < order.len()), egui::Button::new(next_label).min_size(egui::vec2(0.0, height)));
            self.hits.insert("player:next".into(), next.rect);
            if next.clicked() {
                go = Some(if at.is_none() { PlayTo::First } else { PlayTo::Next });
            }
            let replay = ui.add_enabled(at.is_some(), egui::Button::new("Replay").min_size(egui::vec2(0.0, height))).on_hover_text("Show this step's parts coming in again");
            self.hits.insert("player:replay".into(), replay.rect);
            if replay.clicked() {
                go = Some(PlayTo::Replay);
            }
            if let Some(i) = at {
                let count = ui.weak(format!("Step {} of {}", i + 1, order.len()));
                self.hits.insert("player:count".into(), count.rect);
            }
        });
        ui.separator();
        match at {
            Some(i) => self.step(ui, &block, order[i], i + 1),
            None => {
                ui.weak("Press Start to play the steps.");
            }
        }
        if let Some((step, occurrences)) = self.drop.take() {
            match engine.instructions_add_parts(&step, &occurrences) {
                Ok(report) => {
                    // The edit regenerated the step's view and put the shown
                    // step away: show it again, with the part in it.
                    let _ = engine.instructions_show_step(&step);
                    self.error = None;
                    self.notice = Some(match report.added {
                        0 => "No part joined the step".to_string(),
                        1 => "1 part joined the step".to_string(),
                        n => format!("{n} parts joined the step"),
                    });
                }
                Err(error) => self.error = Some(error),
            }
        }
        if let Some(to) = go {
            self.error = engine.instructions_play(to).err();
        }
    }

    fn step(&mut self, ui: &mut egui::Ui, block: &Instructions, step: &Step, number: usize) {
        if let Some(parent) = block.parent_id(&step.id).flatten().and_then(|parent| block.step(parent)) {
            ui.weak(&parent.title);
        }
        let title = ui.heading(format!("{number}. {}", step.title));
        self.hits.insert("player:title".into(), title.rect);
        // A part dragged here (a BOM row, a not-yet-planned part) joins the
        // shown step, as a drop on the step's row in the Instructions pane.
        if title.dnd_hover_payload::<PartsDrag>().is_some() {
            ui.painter().rect_stroke(title.rect, 2.0, ui.visuals().selection.stroke, egui::StrokeKind::Outside);
        }
        if egui::DragAndDrop::has_payload_of_type::<PartsDrag>(ui.ctx()) {
            if let Some(parts) = title.dnd_release_payload::<PartsDrag>() {
                self.drop = Some((step.id.clone(), parts.occurrences.clone()));
            }
        }
        if let Some(notice) = &self.notice {
            let label = ui.weak(notice);
            self.hits.insert("player:notice".into(), label.rect);
        }
        match self.mode {
            Mode::Shop => self.shop(ui, step),
            Mode::Customer => self.customer(ui, step),
        }
    }

    fn shop(&mut self, ui: &mut egui::Ui, step: &Step) {
        ui.label(egui::RichText::new("Parts").strong());
        let ticked = self.checked.entry(step.id.clone()).or_default();
        for (index, add) in step.adds.iter().enumerate() {
            let mut on = ticked.contains(&index);
            let tick = ui.checkbox(&mut on, egui::RichText::new(part_text(add)).size(16.0));
            self.hits.insert(format!("player:part:{index}"), tick.rect);
            if tick.changed() {
                if on {
                    ticked.insert(index);
                } else {
                    ticked.remove(&index);
                }
            }
            if add.serial_tracked {
                for (unit, occurrence) in add.occurrences.iter().enumerate() {
                    ui.horizontal(|ui| {
                        ui.label(format!("Serial {}", unit + 1));
                        let serial = self.serials.entry(occurrence.clone()).or_default();
                        let field = ui.add(egui::TextEdit::singleline(serial).min_size(egui::vec2(160.0, 0.0)));
                        self.hits.insert(format!("player:serial:{index}:{unit}"), field.rect);
                    });
                }
            }
        }
        if !step.tools.is_empty() {
            let tools: Vec<String> =
                step.tools.iter().map(|tool| if tool.spec.is_empty() { tool.name.clone() } else { format!("{} ({})", tool.name, tool.spec) }).collect();
            let label = ui.label(format!("Tools: {}", tools.join(", ")));
            self.hits.insert("player:tools".into(), label.rect);
            // The linked tools' pictures from the library (PNG, the type the
            // app decodes), asked for once per session, shown as they land.
            let ids: Vec<String> = step.tools.iter().filter_map(|tool| tool.tool_id.clone()).collect();
            if let Some(client) = &self.client {
                crate::plm::tool_pictures::request(client, &ids);
            }
            ui.horizontal_wrapped(|ui| {
                for id in &ids {
                    let texture = match self.pictures.get(id) {
                        Some(texture) => texture.clone(),
                        None => {
                            let Some(image) = crate::plm::tool_pictures::png_of(id).and_then(|bytes| crate::plm::thumbnail_view::decode(&bytes)) else { continue };
                            let texture = ui.ctx().load_texture(format!("tool-picture-{id}"), image, egui::TextureOptions::LINEAR);
                            self.pictures.insert(id.clone(), texture.clone());
                            texture
                        }
                    };
                    let image = ui.add(egui::Image::new(&texture).fit_to_exact_size(egui::vec2(64.0, 64.0)));
                    self.hits.insert(format!("player:tool:{id}:picture"), image.rect);
                }
            });
        }
        if let Some(torque) = &step.torque {
            let label = ui.label(egui::RichText::new(format!("Torque: {}", torque.text())).strong());
            self.hits.insert("player:torque".into(), label.rect);
        }
        self.callouts(ui, step);
        if !step.notes.is_empty() {
            let notes = ui.label(&step.notes);
            self.hits.insert("player:notes".into(), notes.rect);
        }
        if !step.fields.is_empty() {
            ui.add_space(6.0);
            ui.label(egui::RichText::new("Record").strong());
            let locked = self.signed.contains(&step.id);
            for (index, field) in step.fields.iter().enumerate() {
                ui.add_enabled_ui(!locked, |ui| self.field(ui, &step.id, index, field));
            }
        }
        if step.on_checklist() {
            ui.add_space(6.0);
            let done = if step.signoff.required { "✔ Signed off" } else { "✔ Done" };
            if self.signed.contains(&step.id) {
                let label = ui.label(egui::RichText::new(done).strong());
                self.hits.insert("player:signed".into(), label.rect);
            } else {
                // What still keeps the step open, said on the button's hover.
                let reasons = self.reasons(step);
                let label = if step.signoff.required { "Sign off step" } else { "Mark step done" };
                let sign = ui
                    .add_enabled(reasons.is_empty(), egui::Button::new(label).min_size(egui::vec2(0.0, TOUCH_HEIGHT)))
                    .on_disabled_hover_text(format!("First: {}", reasons.join("; ")));
                self.hits.insert("player:signoff".into(), sign.rect);
                if !reasons.is_empty() {
                    let why = ui.weak(format!("First: {}", reasons.join("; ")));
                    self.hits.insert("player:signoff:why".into(), why.rect);
                }
                if sign.clicked() {
                    self.signed.insert(step.id.clone());
                }
            }
        }
    }

    /// One field of the shown step, as an input: the value goes to
    /// `self.values` as the JSON `brep_instructions::fields` reads.
    fn field(&mut self, ui: &mut egui::Ui, step: &str, index: usize, field: &StepField) {
        use serde_json::Value;
        let key = format!("player:field:{index}");
        let stored = self.values.get(step).and_then(|v| v.get(&field.id)).cloned();
        let text_of = |v: &Option<Value>| v.as_ref().and_then(Value::as_str).unwrap_or("").to_string();
        let mut set: Option<Option<Value>> = None;
        let star = if field.required { " *" } else { "" };
        let name = format!("{}{star}", if field.label.trim().is_empty() { "Field" } else { field.label.trim() });
        match &field.kind {
            FieldKind::Check => {
                let mut on = stored.as_ref().and_then(Value::as_bool).unwrap_or(false);
                let tick = ui.checkbox(&mut on, egui::RichText::new(&name).size(16.0));
                self.hits.insert(key.clone(), tick.rect);
                if tick.changed() {
                    set = Some(on.then_some(Value::Bool(true)));
                }
            }
            FieldKind::Choice { multiple: true, other, .. } => {
                ui.label(format!("{name} (any that apply)"));
                let options = field.options();
                let picked: Vec<String> = stored.as_ref().and_then(Value::as_array).map(|a| a.iter().filter_map(Value::as_str).map(str::to_string).collect()).unwrap_or_default();
                let mut next: Vec<String> = Vec::new();
                let mut changed = false;
                for (k, option) in options.iter().enumerate() {
                    let mut on = picked.iter().any(|p| p == option);
                    let tick = ui.checkbox(&mut on, *option);
                    self.hits.insert(format!("{key}:option:{k}"), tick.rect);
                    changed |= tick.changed();
                    if on {
                        next.push((*option).to_string());
                    }
                }
                if *other {
                    let mut text = picked.iter().find(|p| !options.contains(&p.as_str())).cloned().unwrap_or_default();
                    ui.horizontal(|ui| {
                        ui.label("Other");
                        let edit = ui.add(egui::TextEdit::singleline(&mut text).min_size(egui::vec2(160.0, 0.0)));
                        self.hits.insert(format!("{key}:other"), edit.rect);
                        changed |= edit.changed();
                    });
                    if !text.trim().is_empty() {
                        next.push(text);
                    }
                }
                if changed {
                    set = Some((!next.is_empty()).then(|| Value::Array(next.into_iter().map(Value::String).collect())));
                }
            }
            FieldKind::Choice { other, .. } => {
                let options = field.options();
                let current = text_of(&stored);
                let slot = (step.to_string(), field.id.clone());
                let is_other = *other && (self.other_open.contains(&slot) || (!current.is_empty() && !options.contains(&current.as_str())));
                // The dropdown's entries: nothing, each option, and Other.
                const NONE: &str = "\u{0}none";
                const OTHER: &str = "\u{0}other";
                let ids: Vec<String> = (0..options.len()).map(|k| k.to_string()).collect();
                let mut choices: Vec<(String, &str, &str)> = vec![(NONE.to_string(), "none", "—")];
                choices.extend(options.iter().zip(&ids).map(|(option, id)| ((*option).to_string(), id.as_str(), *option)));
                if *other {
                    choices.push((OTHER.to_string(), "other", "Other…"));
                }
                let mut picked = if is_other { OTHER.to_string() } else if current.is_empty() { NONE.to_string() } else { current.clone() };
                ui.horizontal_wrapped(|ui| {
                    ui.label(&name);
                    let mut rects = HashMap::new();
                    if crate::form::enum_dropdown(ui, &key, &choices, &mut picked, Some(180.0), Some(&mut rects)).0 {
                        if picked == OTHER {
                            self.other_open.insert(slot.clone());
                            set = Some(None);
                        } else {
                            self.other_open.remove(&slot);
                            set = Some((picked != NONE).then(|| Value::String(picked.clone())));
                        }
                    }
                    self.hits.extend(rects);
                    if is_other && picked == OTHER {
                        let mut text = if options.contains(&current.as_str()) { String::new() } else { current.clone() };
                        let edit = ui.add(egui::TextEdit::singleline(&mut text).hint_text("Other").min_size(egui::vec2(160.0, 0.0)));
                        self.hits.insert(format!("{key}:other"), edit.rect);
                        if edit.changed() {
                            set = Some((!text.trim().is_empty()).then_some(Value::String(text)));
                        }
                    }
                });
            }
            FieldKind::Text { lines } => {
                let mut text = text_of(&stored);
                ui.label(&name);
                let edit = if *lines > 1 {
                    ui.add(egui::TextEdit::multiline(&mut text).desired_rows(*lines as usize).desired_width(f32::INFINITY))
                } else {
                    ui.add(egui::TextEdit::singleline(&mut text).desired_width(f32::INFINITY))
                };
                self.hits.insert(key.clone(), edit.rect);
                if edit.changed() {
                    set = Some((!text.is_empty()).then_some(Value::String(text)));
                }
            }
            FieldKind::Serial => {
                let mut text = text_of(&stored);
                ui.horizontal(|ui| {
                    ui.label(&name);
                    let edit = ui.add(egui::TextEdit::singleline(&mut text).min_size(egui::vec2(160.0, 0.0)));
                    self.hits.insert(key.clone(), edit.rect);
                    if edit.changed() {
                        set = Some((!text.is_empty()).then_some(Value::String(text)));
                    }
                });
            }
            FieldKind::Number { .. } => {
                let mut text = text_of(&stored);
                ui.horizontal_wrapped(|ui| {
                    ui.label(&name);
                    let edit = ui.add(egui::TextEdit::singleline(&mut text).desired_width(90.0));
                    self.hits.insert(key.clone(), edit.rect);
                    if edit.changed() {
                        set = Some((!text.is_empty()).then_some(Value::String(text.clone())));
                    }
                    if !field.unit().is_empty() {
                        ui.label(field.unit());
                    }
                    let limits = field.limits_text();
                    if !limits.is_empty() {
                        ui.weak(format!("({limits})"));
                    }
                    // Out of limits, or not a number, is said beside the box.
                    let flag = match fields::evaluate(field, stored.as_ref()) {
                        Err(_) => Some("not a number"),
                        Ok(read) if read.in_limits == Some(false) => Some("out of limits"),
                        Ok(_) => None,
                    };
                    if let Some(flag) = flag {
                        let label = ui.colored_label(ui.visuals().warn_fg_color, format!("⚠ {flag}"));
                        self.hits.insert(format!("{key}:flag"), label.rect);
                    }
                });
            }
        }
        if !field.hint.trim().is_empty() {
            ui.weak(field.hint.trim());
        }
        if let Some(value) = set {
            let values = self.values.entry(step.to_string()).or_default();
            match value {
                Some(value) => {
                    values.insert(field.id.clone(), value);
                }
                None => {
                    values.remove(&field.id);
                }
            }
        }
    }

    fn customer(&mut self, ui: &mut egui::Ui, step: &Step) {
        for (index, add) in step.adds.iter().enumerate() {
            let label = ui.label(egui::RichText::new(part_text(add)).size(18.0));
            self.hits.insert(format!("player:part:{index}"), label.rect);
        }
        self.callouts(ui, step);
    }

    fn callouts(&mut self, ui: &mut egui::Ui, step: &Step) {
        for (index, callout) in step.callouts.iter().enumerate() {
            let (kind, colour) = match callout.kind {
                CalloutKind::Caution => ("⚠ Caution", ui.visuals().warn_fg_color),
                CalloutKind::Note => ("ℹ Note", ui.visuals().text_color()),
                CalloutKind::Check => ("✔ Check", ui.visuals().text_color()),
            };
            let label = ui.colored_label(colour, format!("{kind}: {}", callout.text));
            self.hits.insert(format!("player:callout:{index}"), label.rect);
        }
    }
}

/// `[2] widget × 4`: the find number, the part and the quantity.
fn part_text(add: &brep_instructions::model::Add) -> String {
    let mut text = String::new();
    if !add.find_number.is_empty() {
        text.push_str(&format!("[{}] ", add.find_number));
    }
    text.push_str(add.display_name());
    if add.quantity() > 1 {
        text.push_str(&format!(" × {}", add.quantity()));
    }
    text
}

pub static HIT_KEYS: &[HitKeyDoc] = &[
    HitKeyDoc { panel: "instructionsplayer", prefix: "panel:clip", meaning: "the visible region of the pane (scroll_into_view scrolls a player:* widget inside it)", command: None },
    HitKeyDoc { panel: "instructionsplayer", prefix: "player:mode:", meaning: "the mode toggle, by mode (shop, customer)", command: Some("instructions_play") },
    HitKeyDoc { panel: "instructionsplayer", prefix: "player:error", meaning: "why the last move was refused", command: None },
    HitKeyDoc { panel: "instructionsplayer", prefix: "player:back", meaning: "show the previous step", command: Some("instructions_play") },
    HitKeyDoc { panel: "instructionsplayer", prefix: "player:next", meaning: "show the next step (Start: the first)", command: Some("instructions_play") },
    HitKeyDoc { panel: "instructionsplayer", prefix: "player:replay", meaning: "show the step's parts coming in again", command: Some("instructions_play") },
    HitKeyDoc { panel: "instructionsplayer", prefix: "player:count", meaning: "where the shown step is: Step N of M", command: None },
    HitKeyDoc { panel: "instructionsplayer", prefix: "player:title", meaning: "the shown step's number and title; a BOM row or a not-yet-planned part dropped on it joins the shown step (instructions_add_parts), the outcome said under it (player:notice)", command: Some("instructions_add_parts") },
    HitKeyDoc { panel: "instructionsplayer", prefix: "player:notice", meaning: "what the last drop on the title said", command: None },
    HitKeyDoc { panel: "instructionsplayer", prefix: "player:part:", meaning: "a part the step adds, by index: a checklist tick in shop mode, a label in customer mode", command: None },
    HitKeyDoc { panel: "instructionsplayer", prefix: "player:serial:", meaning: "the serial field of one unit of a serial-tracked part, by part and unit index (shop mode)", command: None },
    HitKeyDoc { panel: "instructionsplayer", prefix: "player:tools", meaning: "the step's tools (shop mode)", command: None },
    HitKeyDoc { panel: "instructionsplayer", prefix: "player:tool:", meaning: "a linked tool's picture from the PLM tools library, `<tool id>:picture` (shown once fetched; PNG pictures only in the pane)", command: None },
    HitKeyDoc { panel: "instructionsplayer", prefix: "player:torque", meaning: "the step's torque (shop mode)", command: None },
    HitKeyDoc { panel: "instructionsplayer", prefix: "player:callout:", meaning: "a callout of the step, by index", command: None },
    HitKeyDoc { panel: "instructionsplayer", prefix: "player:notes", meaning: "the step's notes (shop mode)", command: None },
    HitKeyDoc { panel: "instructionsplayer", prefix: "player:field:", meaning: "a field the step records, by index (shop mode): a tick, a text, serial or measurement box (`<index>:flag` beside a measurement that is out of limits or not a number), a single choice's dropdown (`<index>#none`, `<index>#<option index>`, `<index>#other` while open, and `<index>:other` its Other box), a multiple choice's boxes `<index>:option:<n>` and `<index>:other`; the values are in the pane state's `fields` (step id → field id → value)", command: None },
    HitKeyDoc { panel: "instructionsplayer", prefix: "player:signoff", meaning: "sign the step off (Mark step done on a step with fields and no sign-off), once every part is ticked, every serial entered, every required field filled and every measurement that must be is inside its limits (shop mode); the line under it says what is still missing", command: None },
    HitKeyDoc { panel: "instructionsplayer", prefix: "player:signoff:why", meaning: "what still keeps the shown step from being signed off or marked done (shop mode; drawn only while something does)", command: None },
    HitKeyDoc { panel: "instructionsplayer", prefix: "player:signed", meaning: "the step is signed off (shop mode)", command: None },
];