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