1use crate::automation::hit_keys::HitKeyDoc;
23use crate::panels::instructions::PartsDrag;
24use brep_instructions::fields::{self, FieldKind, StepField};
25use brep_instructions::model::{CalloutKind, Instructions, Step};
26use brep_instructions::player::Mode;
27use brep_render::engine_state::{EngineState, PlayTo};
28use std::collections::{BTreeMap, BTreeSet, HashMap};
29
30const TOUCH_HEIGHT: f32 = 44.0;
32
33#[derive(Default)]
34pub struct InstructionsPlayerPanel {
35 hits: HashMap<String, egui::Rect>,
36 client: Option<std::rc::Rc<crate::plm::client::PlmClient>>,
38 pictures: HashMap<String, egui::TextureHandle>,
40 mode: Mode,
41 request: Option<PlayTo>,
43 checked: BTreeMap<String, BTreeSet<usize>>,
45 serials: BTreeMap<String, String>,
47 values: BTreeMap<String, BTreeMap<String, serde_json::Value>>,
51 other_open: BTreeSet<(String, String)>,
53 signed: BTreeSet<String>,
55 error: Option<String>,
56 notice: Option<String>,
58 drop: Option<(String, Vec<String>)>,
61}
62
63impl InstructionsPlayerPanel {
64 pub fn new() -> Self {
65 Self::default()
66 }
67
68 pub fn request(&mut self, to: PlayTo) {
70 self.request = Some(to);
71 }
72
73 pub fn mode(&self) -> Mode {
74 self.mode
75 }
76
77 pub fn set_mode(&mut self, mode: Mode) {
78 self.mode = mode;
79 }
80
81 pub fn hits_json(&self) -> String {
82 crate::automation::hit_rects::hits_json(&self.hits)
83 }
84
85 pub fn clear_hits(&mut self) {
88 self.hits.clear();
89 }
90
91 pub fn state_json(&self, engine: &EngineState) -> String {
94 serde_json::json!({
95 "mode": self.mode.as_str(),
96 "step": engine.instructions_shown_step(),
97 "insertion": engine.instructions_insertion_fraction(),
98 "pending": self.request.is_some(),
99 "checked": self.checked,
100 "serials": self.serials,
101 "fields": self.values,
102 "missing": self.open_reasons(engine),
103 "signed": self.signed,
104 "error": self.error,
105 "notice": self.notice,
106 })
107 .to_string()
108 }
109
110 fn open_reasons(&self, engine: &EngineState) -> Vec<String> {
114 let Some(id) = engine.instructions_shown_step() else { return Vec::new() };
115 let Ok(Some(block)) = engine.instructions() else { return Vec::new() };
116 match block.step(&id) {
117 Some(step) if step.on_checklist() && !self.signed.contains(&step.id) => self.reasons(step),
118 _ => Vec::new(),
119 }
120 }
121
122 fn reasons(&self, step: &Step) -> Vec<String> {
125 let mut reasons: Vec<String> = Vec::new();
126 let ticked = self.checked.get(&step.id).map_or(0, BTreeSet::len);
127 if ticked != step.adds.len() {
128 reasons.push("tick every part".into());
129 }
130 let serials_in = step
131 .adds
132 .iter()
133 .filter(|add| add.serial_tracked)
134 .flat_map(|add| &add.occurrences)
135 .all(|occurrence| self.serials.get(occurrence).is_some_and(|serial| !serial.trim().is_empty()));
136 if !serials_in {
137 reasons.push("enter every serial".into());
138 }
139 let values = self.values.get(&step.id);
140 reasons.extend(fields::missing(&step.fields, |id| values.and_then(|v| v.get(id))));
141 reasons
142 }
143
144 pub fn show(&mut self, ui: &mut egui::Ui, engine: &mut EngineState, client: Option<&std::rc::Rc<crate::plm::client::PlmClient>>) {
145 self.client = client.cloned();
146 self.hits.clear();
147 self.hits.insert("panel:clip".into(), ui.clip_rect());
148 if !engine.is_instructions() {
149 ui.label("Open instructions to play them: New from assembly on the toolbar makes some.");
150 return;
151 }
152 let mut go = self.request.take();
153 let block = match engine.instructions() {
154 Ok(Some(block)) => block,
155 Ok(None) => return,
156 Err(error) => {
157 ui.colored_label(ui.visuals().error_fg_color, format!("The instructions cannot be read: {error}"));
158 return;
159 }
160 };
161 let order: Vec<&Step> = block.steps().map(|(_, step)| step).collect();
162 let shown = engine.instructions_shown_step();
163 let at = shown.as_deref().and_then(|id| order.iter().position(|step| step.id == id));
164
165 ui.horizontal(|ui| {
166 for mode in [Mode::Shop, Mode::Customer] {
167 let label = if mode == Mode::Shop { "Shop" } else { "Customer" };
168 let toggle = ui.selectable_label(self.mode == mode, label);
169 self.hits.insert(format!("player:mode:{}", mode.as_str()), toggle.rect);
170 if toggle.clicked() {
171 self.mode = mode;
172 }
173 }
174 });
175 if let Some(error) = &self.error {
176 let label = ui.colored_label(ui.visuals().error_fg_color, error);
177 self.hits.insert("player:error".into(), label.rect);
178 }
179 if order.is_empty() {
180 ui.weak("No steps yet: press Wizard on the toolbar.");
181 return;
182 }
183 let height = if self.mode == Mode::Shop { TOUCH_HEIGHT } else { 0.0 };
184 ui.horizontal_wrapped(|ui| {
185 let back = ui.add_enabled(at.is_some_and(|i| i > 0), egui::Button::new("◀ Back").min_size(egui::vec2(0.0, height)));
186 self.hits.insert("player:back".into(), back.rect);
187 if back.clicked() {
188 go = Some(PlayTo::Back);
189 }
190 let next_label = if at.is_none() { "Start ▶" } else { "Next ▶" };
191 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)));
192 self.hits.insert("player:next".into(), next.rect);
193 if next.clicked() {
194 go = Some(if at.is_none() { PlayTo::First } else { PlayTo::Next });
195 }
196 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");
197 self.hits.insert("player:replay".into(), replay.rect);
198 if replay.clicked() {
199 go = Some(PlayTo::Replay);
200 }
201 if let Some(i) = at {
202 let count = ui.weak(format!("Step {} of {}", i + 1, order.len()));
203 self.hits.insert("player:count".into(), count.rect);
204 }
205 });
206 ui.separator();
207 match at {
208 Some(i) => self.step(ui, &block, order[i], i + 1),
209 None => {
210 ui.weak("Press Start to play the steps.");
211 }
212 }
213 if let Some((step, occurrences)) = self.drop.take() {
214 match engine.instructions_add_parts(&step, &occurrences) {
215 Ok(report) => {
216 let _ = engine.instructions_show_step(&step);
219 self.error = None;
220 self.notice = Some(match report.added {
221 0 => "No part joined the step".to_string(),
222 1 => "1 part joined the step".to_string(),
223 n => format!("{n} parts joined the step"),
224 });
225 }
226 Err(error) => self.error = Some(error),
227 }
228 }
229 if let Some(to) = go {
230 self.error = engine.instructions_play(to).err();
231 }
232 }
233
234 fn step(&mut self, ui: &mut egui::Ui, block: &Instructions, step: &Step, number: usize) {
235 if let Some(parent) = block.parent_id(&step.id).flatten().and_then(|parent| block.step(parent)) {
236 ui.weak(&parent.title);
237 }
238 let title = ui.heading(format!("{number}. {}", step.title));
239 self.hits.insert("player:title".into(), title.rect);
240 if title.dnd_hover_payload::<PartsDrag>().is_some() {
243 ui.painter().rect_stroke(title.rect, 2.0, ui.visuals().selection.stroke, egui::StrokeKind::Outside);
244 }
245 if egui::DragAndDrop::has_payload_of_type::<PartsDrag>(ui.ctx()) {
246 if let Some(parts) = title.dnd_release_payload::<PartsDrag>() {
247 self.drop = Some((step.id.clone(), parts.occurrences.clone()));
248 }
249 }
250 if let Some(notice) = &self.notice {
251 let label = ui.weak(notice);
252 self.hits.insert("player:notice".into(), label.rect);
253 }
254 match self.mode {
255 Mode::Shop => self.shop(ui, step),
256 Mode::Customer => self.customer(ui, step),
257 }
258 }
259
260 fn shop(&mut self, ui: &mut egui::Ui, step: &Step) {
261 ui.label(egui::RichText::new("Parts").strong());
262 let ticked = self.checked.entry(step.id.clone()).or_default();
263 for (index, add) in step.adds.iter().enumerate() {
264 let mut on = ticked.contains(&index);
265 let tick = ui.checkbox(&mut on, egui::RichText::new(part_text(add)).size(16.0));
266 self.hits.insert(format!("player:part:{index}"), tick.rect);
267 if tick.changed() {
268 if on {
269 ticked.insert(index);
270 } else {
271 ticked.remove(&index);
272 }
273 }
274 if add.serial_tracked {
275 for (unit, occurrence) in add.occurrences.iter().enumerate() {
276 ui.horizontal(|ui| {
277 ui.label(format!("Serial {}", unit + 1));
278 let serial = self.serials.entry(occurrence.clone()).or_default();
279 let field = ui.add(egui::TextEdit::singleline(serial).min_size(egui::vec2(160.0, 0.0)));
280 self.hits.insert(format!("player:serial:{index}:{unit}"), field.rect);
281 });
282 }
283 }
284 }
285 if !step.tools.is_empty() {
286 let tools: Vec<String> =
287 step.tools.iter().map(|tool| if tool.spec.is_empty() { tool.name.clone() } else { format!("{} ({})", tool.name, tool.spec) }).collect();
288 let label = ui.label(format!("Tools: {}", tools.join(", ")));
289 self.hits.insert("player:tools".into(), label.rect);
290 let ids: Vec<String> = step.tools.iter().filter_map(|tool| tool.tool_id.clone()).collect();
293 if let Some(client) = &self.client {
294 crate::plm::tool_pictures::request(client, &ids);
295 }
296 ui.horizontal_wrapped(|ui| {
297 for id in &ids {
298 let texture = match self.pictures.get(id) {
299 Some(texture) => texture.clone(),
300 None => {
301 let Some(image) = crate::plm::tool_pictures::png_of(id).and_then(|bytes| crate::plm::thumbnail_view::decode(&bytes)) else { continue };
302 let texture = ui.ctx().load_texture(format!("tool-picture-{id}"), image, egui::TextureOptions::LINEAR);
303 self.pictures.insert(id.clone(), texture.clone());
304 texture
305 }
306 };
307 let image = ui.add(egui::Image::new(&texture).fit_to_exact_size(egui::vec2(64.0, 64.0)));
308 self.hits.insert(format!("player:tool:{id}:picture"), image.rect);
309 }
310 });
311 }
312 if let Some(torque) = &step.torque {
313 let label = ui.label(egui::RichText::new(format!("Torque: {}", torque.text())).strong());
314 self.hits.insert("player:torque".into(), label.rect);
315 }
316 self.callouts(ui, step);
317 if !step.notes.is_empty() {
318 let notes = ui.label(&step.notes);
319 self.hits.insert("player:notes".into(), notes.rect);
320 }
321 if !step.fields.is_empty() {
322 ui.add_space(6.0);
323 ui.label(egui::RichText::new("Record").strong());
324 let locked = self.signed.contains(&step.id);
325 for (index, field) in step.fields.iter().enumerate() {
326 ui.add_enabled_ui(!locked, |ui| self.field(ui, &step.id, index, field));
327 }
328 }
329 if step.on_checklist() {
330 ui.add_space(6.0);
331 let done = if step.signoff.required { "✔ Signed off" } else { "✔ Done" };
332 if self.signed.contains(&step.id) {
333 let label = ui.label(egui::RichText::new(done).strong());
334 self.hits.insert("player:signed".into(), label.rect);
335 } else {
336 let reasons = self.reasons(step);
338 let label = if step.signoff.required { "Sign off step" } else { "Mark step done" };
339 let sign = ui
340 .add_enabled(reasons.is_empty(), egui::Button::new(label).min_size(egui::vec2(0.0, TOUCH_HEIGHT)))
341 .on_disabled_hover_text(format!("First: {}", reasons.join("; ")));
342 self.hits.insert("player:signoff".into(), sign.rect);
343 if !reasons.is_empty() {
344 let why = ui.weak(format!("First: {}", reasons.join("; ")));
345 self.hits.insert("player:signoff:why".into(), why.rect);
346 }
347 if sign.clicked() {
348 self.signed.insert(step.id.clone());
349 }
350 }
351 }
352 }
353
354 fn field(&mut self, ui: &mut egui::Ui, step: &str, index: usize, field: &StepField) {
357 use serde_json::Value;
358 let key = format!("player:field:{index}");
359 let stored = self.values.get(step).and_then(|v| v.get(&field.id)).cloned();
360 let text_of = |v: &Option<Value>| v.as_ref().and_then(Value::as_str).unwrap_or("").to_string();
361 let mut set: Option<Option<Value>> = None;
362 let star = if field.required { " *" } else { "" };
363 let name = format!("{}{star}", if field.label.trim().is_empty() { "Field" } else { field.label.trim() });
364 match &field.kind {
365 FieldKind::Check => {
366 let mut on = stored.as_ref().and_then(Value::as_bool).unwrap_or(false);
367 let tick = ui.checkbox(&mut on, egui::RichText::new(&name).size(16.0));
368 self.hits.insert(key.clone(), tick.rect);
369 if tick.changed() {
370 set = Some(on.then_some(Value::Bool(true)));
371 }
372 }
373 FieldKind::Choice { multiple: true, other, .. } => {
374 ui.label(format!("{name} (any that apply)"));
375 let options = field.options();
376 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();
377 let mut next: Vec<String> = Vec::new();
378 let mut changed = false;
379 for (k, option) in options.iter().enumerate() {
380 let mut on = picked.iter().any(|p| p == option);
381 let tick = ui.checkbox(&mut on, *option);
382 self.hits.insert(format!("{key}:option:{k}"), tick.rect);
383 changed |= tick.changed();
384 if on {
385 next.push((*option).to_string());
386 }
387 }
388 if *other {
389 let mut text = picked.iter().find(|p| !options.contains(&p.as_str())).cloned().unwrap_or_default();
390 ui.horizontal(|ui| {
391 ui.label("Other");
392 let edit = ui.add(egui::TextEdit::singleline(&mut text).min_size(egui::vec2(160.0, 0.0)));
393 self.hits.insert(format!("{key}:other"), edit.rect);
394 changed |= edit.changed();
395 });
396 if !text.trim().is_empty() {
397 next.push(text);
398 }
399 }
400 if changed {
401 set = Some((!next.is_empty()).then(|| Value::Array(next.into_iter().map(Value::String).collect())));
402 }
403 }
404 FieldKind::Choice { other, .. } => {
405 let options = field.options();
406 let current = text_of(&stored);
407 let slot = (step.to_string(), field.id.clone());
408 let is_other = *other && (self.other_open.contains(&slot) || (!current.is_empty() && !options.contains(¤t.as_str())));
409 const NONE: &str = "\u{0}none";
411 const OTHER: &str = "\u{0}other";
412 let ids: Vec<String> = (0..options.len()).map(|k| k.to_string()).collect();
413 let mut choices: Vec<(String, &str, &str)> = vec![(NONE.to_string(), "none", "—")];
414 choices.extend(options.iter().zip(&ids).map(|(option, id)| ((*option).to_string(), id.as_str(), *option)));
415 if *other {
416 choices.push((OTHER.to_string(), "other", "Other…"));
417 }
418 let mut picked = if is_other { OTHER.to_string() } else if current.is_empty() { NONE.to_string() } else { current.clone() };
419 ui.horizontal_wrapped(|ui| {
420 ui.label(&name);
421 let mut rects = HashMap::new();
422 if crate::form::enum_dropdown(ui, &key, &choices, &mut picked, Some(180.0), Some(&mut rects)).0 {
423 if picked == OTHER {
424 self.other_open.insert(slot.clone());
425 set = Some(None);
426 } else {
427 self.other_open.remove(&slot);
428 set = Some((picked != NONE).then(|| Value::String(picked.clone())));
429 }
430 }
431 self.hits.extend(rects);
432 if is_other && picked == OTHER {
433 let mut text = if options.contains(¤t.as_str()) { String::new() } else { current.clone() };
434 let edit = ui.add(egui::TextEdit::singleline(&mut text).hint_text("Other").min_size(egui::vec2(160.0, 0.0)));
435 self.hits.insert(format!("{key}:other"), edit.rect);
436 if edit.changed() {
437 set = Some((!text.trim().is_empty()).then_some(Value::String(text)));
438 }
439 }
440 });
441 }
442 FieldKind::Text { lines } => {
443 let mut text = text_of(&stored);
444 ui.label(&name);
445 let edit = if *lines > 1 {
446 ui.add(egui::TextEdit::multiline(&mut text).desired_rows(*lines as usize).desired_width(f32::INFINITY))
447 } else {
448 ui.add(egui::TextEdit::singleline(&mut text).desired_width(f32::INFINITY))
449 };
450 self.hits.insert(key.clone(), edit.rect);
451 if edit.changed() {
452 set = Some((!text.is_empty()).then_some(Value::String(text)));
453 }
454 }
455 FieldKind::Serial => {
456 let mut text = text_of(&stored);
457 ui.horizontal(|ui| {
458 ui.label(&name);
459 let edit = ui.add(egui::TextEdit::singleline(&mut text).min_size(egui::vec2(160.0, 0.0)));
460 self.hits.insert(key.clone(), edit.rect);
461 if edit.changed() {
462 set = Some((!text.is_empty()).then_some(Value::String(text)));
463 }
464 });
465 }
466 FieldKind::Number { .. } => {
467 let mut text = text_of(&stored);
468 ui.horizontal_wrapped(|ui| {
469 ui.label(&name);
470 let edit = ui.add(egui::TextEdit::singleline(&mut text).desired_width(90.0));
471 self.hits.insert(key.clone(), edit.rect);
472 if edit.changed() {
473 set = Some((!text.is_empty()).then_some(Value::String(text.clone())));
474 }
475 if !field.unit().is_empty() {
476 ui.label(field.unit());
477 }
478 let limits = field.limits_text();
479 if !limits.is_empty() {
480 ui.weak(format!("({limits})"));
481 }
482 let flag = match fields::evaluate(field, stored.as_ref()) {
484 Err(_) => Some("not a number"),
485 Ok(read) if read.in_limits == Some(false) => Some("out of limits"),
486 Ok(_) => None,
487 };
488 if let Some(flag) = flag {
489 let label = ui.colored_label(ui.visuals().warn_fg_color, format!("⚠ {flag}"));
490 self.hits.insert(format!("{key}:flag"), label.rect);
491 }
492 });
493 }
494 }
495 if !field.hint.trim().is_empty() {
496 ui.weak(field.hint.trim());
497 }
498 if let Some(value) = set {
499 let values = self.values.entry(step.to_string()).or_default();
500 match value {
501 Some(value) => {
502 values.insert(field.id.clone(), value);
503 }
504 None => {
505 values.remove(&field.id);
506 }
507 }
508 }
509 }
510
511 fn customer(&mut self, ui: &mut egui::Ui, step: &Step) {
512 for (index, add) in step.adds.iter().enumerate() {
513 let label = ui.label(egui::RichText::new(part_text(add)).size(18.0));
514 self.hits.insert(format!("player:part:{index}"), label.rect);
515 }
516 self.callouts(ui, step);
517 }
518
519 fn callouts(&mut self, ui: &mut egui::Ui, step: &Step) {
520 for (index, callout) in step.callouts.iter().enumerate() {
521 let (kind, colour) = match callout.kind {
522 CalloutKind::Caution => ("⚠ Caution", ui.visuals().warn_fg_color),
523 CalloutKind::Note => ("ℹ Note", ui.visuals().text_color()),
524 CalloutKind::Check => ("✔ Check", ui.visuals().text_color()),
525 };
526 let label = ui.colored_label(colour, format!("{kind}: {}", callout.text));
527 self.hits.insert(format!("player:callout:{index}"), label.rect);
528 }
529 }
530}
531
532fn part_text(add: &brep_instructions::model::Add) -> String {
534 let mut text = String::new();
535 if !add.find_number.is_empty() {
536 text.push_str(&format!("[{}] ", add.find_number));
537 }
538 text.push_str(add.display_name());
539 if add.quantity() > 1 {
540 text.push_str(&format!(" × {}", add.quantity()));
541 }
542 text
543}
544
545pub static HIT_KEYS: &[HitKeyDoc] = &[
546 HitKeyDoc { panel: "instructionsplayer", prefix: "panel:clip", meaning: "the visible region of the pane (scroll_into_view scrolls a player:* widget inside it)", command: None },
547 HitKeyDoc { panel: "instructionsplayer", prefix: "player:mode:", meaning: "the mode toggle, by mode (shop, customer)", command: Some("instructions_play") },
548 HitKeyDoc { panel: "instructionsplayer", prefix: "player:error", meaning: "why the last move was refused", command: None },
549 HitKeyDoc { panel: "instructionsplayer", prefix: "player:back", meaning: "show the previous step", command: Some("instructions_play") },
550 HitKeyDoc { panel: "instructionsplayer", prefix: "player:next", meaning: "show the next step (Start: the first)", command: Some("instructions_play") },
551 HitKeyDoc { panel: "instructionsplayer", prefix: "player:replay", meaning: "show the step's parts coming in again", command: Some("instructions_play") },
552 HitKeyDoc { panel: "instructionsplayer", prefix: "player:count", meaning: "where the shown step is: Step N of M", command: None },
553 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") },
554 HitKeyDoc { panel: "instructionsplayer", prefix: "player:notice", meaning: "what the last drop on the title said", command: None },
555 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 },
556 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 },
557 HitKeyDoc { panel: "instructionsplayer", prefix: "player:tools", meaning: "the step's tools (shop mode)", command: None },
558 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 },
559 HitKeyDoc { panel: "instructionsplayer", prefix: "player:torque", meaning: "the step's torque (shop mode)", command: None },
560 HitKeyDoc { panel: "instructionsplayer", prefix: "player:callout:", meaning: "a callout of the step, by index", command: None },
561 HitKeyDoc { panel: "instructionsplayer", prefix: "player:notes", meaning: "the step's notes (shop mode)", command: None },
562 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 },
563 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 },
564 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 },
565 HitKeyDoc { panel: "instructionsplayer", prefix: "player:signed", meaning: "the step is signed off (shop mode)", command: None },
566];