1use serde::{Deserialize, Serialize};
16use serde_json::Value;
17use std::collections::HashSet;
18
19pub const BLOCK_KEY: &str = "instructions";
21
22pub const SCHEMA: u32 = 2;
24
25pub const DOCUMENT_CLASS: &str = "instructions";
27
28pub const EXTENSION: &str = ".ibrep";
30
31pub const FASTENER_ATTRIBUTE: &str = "Fastener";
33pub const TORQUE_ATTRIBUTE: &str = "Torque";
35pub const SERIAL_TRACKED_ATTRIBUTE: &str = "Serial_Tracked";
37
38pub const STEPS_PER_PAGE: [u8; 3] = [1, 2, 4];
40
41#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
42#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
43#[serde(rename_all = "camelCase")]
44pub struct Instructions {
45 pub schema: u32,
46 pub target: Target,
49 #[serde(default)]
50 pub template: Template,
51 #[serde(default)]
52 pub front: FrontMatter,
53 #[serde(default)]
55 pub steps: Vec<Step>,
56 #[serde(default)]
57 pub id_counter: u64,
58 #[serde(default, skip_serializing_if = "Option::is_none")]
61 pub retarget: Option<Retarget>,
62}
63
64#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
66#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
67#[serde(rename_all = "camelCase")]
68pub struct Target {
69 pub source_key: String,
72 #[serde(default)]
73 pub part_number: String,
74 #[serde(default)]
76 pub revision: String,
77 #[serde(default)]
79 pub signature: String,
80 #[serde(default)]
82 pub name: String,
83}
84
85#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
86#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
87#[serde(rename_all = "lowercase")]
88pub enum Orientation {
89 #[default]
90 Portrait,
91 Landscape,
92}
93
94#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
96#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
97#[serde(rename_all = "camelCase")]
98pub struct Template {
99 pub steps_per_page: u8,
101 pub orientation: Orientation,
102 pub paper: String,
104}
105
106impl Default for Template {
107 fn default() -> Self {
108 Self { steps_per_page: 1, orientation: Orientation::Portrait, paper: "A4".into() }
109 }
110}
111
112#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
114#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
115#[serde(rename_all = "camelCase")]
116pub struct FrontMatter {
117 #[serde(default)]
118 pub title: String,
119 #[serde(default)]
120 pub subtitle: String,
121 #[serde(default, skip_serializing_if = "Option::is_none")]
123 pub cover_step: Option<String>,
124 pub parts_list: bool,
125 pub tools_list: bool,
126}
127
128impl Default for FrontMatter {
129 fn default() -> Self {
130 Self { title: String::new(), subtitle: String::new(), cover_step: None, parts_list: true, tools_list: true }
131 }
132}
133
134#[derive(Debug, Clone, Deserialize)]
136#[serde(rename_all = "camelCase")]
137struct ChapterV1 {
138 id: String,
139 #[serde(default)]
142 assembly: String,
143 #[serde(default)]
144 title: String,
145 #[serde(default)]
146 steps: Vec<Step>,
147}
148
149#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
150#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
151#[serde(rename_all = "camelCase")]
152pub struct Step {
153 pub id: String,
154 pub title: String,
155 #[serde(default, skip_serializing_if = "String::is_empty")]
156 pub notes: String,
157 #[serde(default)]
158 pub adds: Vec<Add>,
159 #[serde(default, skip_serializing_if = "Option::is_none")]
161 pub view: Option<String>,
162 #[serde(default, skip_serializing_if = "Vec::is_empty")]
163 pub tools: Vec<ToolUse>,
164 #[serde(default, skip_serializing_if = "Option::is_none")]
165 pub torque: Option<Torque>,
166 #[serde(default, skip_serializing_if = "Vec::is_empty")]
167 pub callouts: Vec<Callout>,
168 #[serde(default, skip_serializing_if = "Vec::is_empty")]
170 pub arrows: Vec<Arrow>,
171 #[serde(default, skip_serializing_if = "Option::is_none")]
173 pub motion: Option<Value>,
174 #[serde(default)]
175 pub signoff: Signoff,
176 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
180 pub camera_captured: bool,
181 #[serde(default, skip_serializing_if = "Vec::is_empty")]
184 pub steps: Vec<Step>,
185}
186
187#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
189#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
190#[serde(rename_all = "camelCase")]
191pub struct Add {
192 pub occurrences: Vec<String>,
194 pub part: String,
197 #[serde(default, skip_serializing_if = "String::is_empty")]
200 pub name: String,
201 #[serde(default)]
202 pub find_number: String,
203 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
205 pub subassembly: bool,
206 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
207 pub fastener: bool,
208 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
209 pub serial_tracked: bool,
210}
211
212impl Add {
213 pub fn quantity(&self) -> usize {
214 self.occurrences.len()
215 }
216
217 pub fn display_name(&self) -> &str {
220 if self.name.is_empty() {
221 &self.part
222 } else {
223 &self.name
224 }
225 }
226
227 pub fn named(occurrences: Vec<String>, part: &str, name: &str) -> Self {
230 Self {
231 occurrences,
232 part: part.to_string(),
233 name: if name == part { String::new() } else { name.to_string() },
234 ..Self::default()
235 }
236 }
237
238 fn same_row(&self, other: &Add) -> bool {
241 self.part == other.part && self.find_number == other.find_number && self.subassembly == other.subassembly
242 }
243}
244
245impl Step {
246 pub fn new(id: String, title: String) -> Self {
248 Self { id, title, ..Self::default() }
249 }
250
251 pub fn contains(&self, step_id: &str) -> bool {
253 self.id == step_id || self.steps.iter().any(|s| s.contains(step_id))
254 }
255
256 fn places(&self, occurrence: &str) -> bool {
258 self.adds.iter().any(|a| a.subassembly && a.occurrences.iter().any(|o| o == occurrence))
259 }
260
261 pub fn occurrences_with_descendants<'a>(&'a self, out: &mut Vec<&'a str>) {
263 out.extend(self.adds.iter().flat_map(|a| a.occurrences.iter().map(String::as_str)));
264 for child in &self.steps {
265 child.occurrences_with_descendants(out);
266 }
267 }
268
269 pub fn coalesce_adds(&mut self) {
274 let mut rows: Vec<Add> = Vec::with_capacity(self.adds.len());
275 for mut add in std::mem::take(&mut self.adds) {
276 match rows.iter_mut().find(|row| row.same_row(&add)) {
277 Some(row) => {
278 row.occurrences.append(&mut add.occurrences);
279 row.fastener |= add.fastener;
280 row.serial_tracked |= add.serial_tracked;
281 }
282 None => rows.push(add),
283 }
284 }
285 self.adds = rows;
286 }
287}
288
289#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
292#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
293#[serde(rename_all = "camelCase")]
294pub struct ToolUse {
295 #[serde(default, skip_serializing_if = "Option::is_none")]
296 pub tool_id: Option<String>,
297 pub name: String,
298 #[serde(default)]
299 pub spec: String,
300 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
302 pub unlinked: bool,
303}
304
305#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
306#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
307#[serde(rename_all = "lowercase")]
308pub enum TorqueSource {
309 Part,
311 Override,
313}
314
315#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
316#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
317#[serde(rename_all = "camelCase")]
318pub struct Torque {
319 pub value: String,
321 #[serde(default)]
322 pub unit: String,
323 pub source: TorqueSource,
324}
325
326impl Torque {
327 pub fn from_attribute(text: &str) -> Option<Self> {
330 let text = text.trim();
331 if text.is_empty() {
332 return None;
333 }
334 let (value, unit) = match text.split_once(char::is_whitespace) {
335 Some((value, unit)) => (value.trim(), unit.trim()),
336 None => (text, ""),
337 };
338 Some(Self { value: value.into(), unit: unit.into(), source: TorqueSource::Part })
339 }
340
341 pub fn text(&self) -> String {
343 if self.unit.is_empty() {
344 self.value.clone()
345 } else {
346 format!("{} {}", self.value, self.unit)
347 }
348 }
349}
350
351#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
352#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
353#[serde(rename_all = "lowercase")]
354pub enum CalloutKind {
355 Caution,
356 Note,
357 Check,
358}
359
360impl CalloutKind {
361 pub fn label(self) -> &'static str {
362 match self {
363 Self::Caution => "Caution",
364 Self::Note => "Note",
365 Self::Check => "Check",
366 }
367 }
368}
369
370#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
371#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
372#[serde(rename_all = "camelCase")]
373pub struct Callout {
374 pub id: String,
375 pub kind: CalloutKind,
376 pub text: String,
377 #[serde(default, skip_serializing_if = "Option::is_none")]
379 pub occurrence: Option<String>,
380}
381
382#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
383#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
384#[serde(rename_all = "camelCase")]
385pub struct Arrow {
386 pub occurrence: String,
387 pub direction: [f64; 3],
389 pub distance: f64,
391}
392
393impl Arrow {
394 pub fn start_offset(&self) -> [f64; 3] {
397 let [x, y, z] = self.direction;
398 let length = (x * x + y * y + z * z).sqrt();
399 if !(length > 1e-12) || !self.distance.is_finite() {
400 return [0.0; 3];
401 }
402 let k = -self.distance / length;
403 [x * k, y * k, z * k]
404 }
405}
406
407#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
408#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
409#[serde(rename_all = "camelCase")]
410pub struct Signoff {
411 pub required: bool,
412}
413
414impl Default for Signoff {
415 fn default() -> Self {
416 Self { required: true }
417 }
418}
419
420#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
422#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
423#[serde(rename_all = "camelCase")]
424pub struct OccurrenceChange {
425 pub occurrence: String,
426 pub part: String,
427 #[serde(default, skip_serializing_if = "Option::is_none")]
429 pub was: Option<String>,
430}
431
432#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
435#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
436#[serde(rename_all = "camelCase")]
437pub struct Retarget {
438 pub from: Target,
439 pub to: Target,
440 #[serde(default)]
441 pub added: Vec<OccurrenceChange>,
442 #[serde(default)]
443 pub removed: Vec<OccurrenceChange>,
444 #[serde(default)]
445 pub replaced: Vec<OccurrenceChange>,
446 #[serde(default)]
449 pub touched_steps: Vec<String>,
450 #[serde(default)]
452 pub empty_steps: Vec<String>,
453}
454
455impl Instructions {
456 pub fn new(target: Target) -> Self {
458 let title = target.name.clone();
459 Self {
460 schema: SCHEMA,
461 target,
462 template: Template::default(),
463 front: FrontMatter { title, ..FrontMatter::default() },
464 steps: Vec::new(),
465 id_counter: 0,
466 retarget: None,
467 }
468 }
469
470 pub fn from_value(value: &Value) -> Result<Self, String> {
475 let schema = value.get("schema").and_then(Value::as_u64).unwrap_or(0);
476 let value = if schema == 1 { migrate_chapters(value)? } else { value.clone() };
477 let mut block: Self = serde_json::from_value(value).map_err(|e| format!("instructions block: {e}"))?;
478 block.validate()?;
479 block.coalesce_adds();
480 Ok(block)
481 }
482
483 pub fn coalesce_adds(&mut self) {
485 for_each_step_mut(&mut self.steps, &mut |step| step.coalesce_adds());
486 }
487
488 pub fn from_document(document: &Value) -> Result<Option<Self>, String> {
490 match document.get(BLOCK_KEY) {
491 None | Some(Value::Null) => Ok(None),
492 Some(block) => Self::from_value(block).map(Some),
493 }
494 }
495
496 pub fn to_value(&self) -> Value {
497 serde_json::to_value(self).expect("instructions block serializes")
498 }
499
500 pub fn validate(&self) -> Result<(), String> {
503 if self.schema == 0 || self.schema > SCHEMA {
504 return Err(format!("instructions schema {} is not supported (this build reads up to {SCHEMA})", self.schema));
505 }
506 if !STEPS_PER_PAGE.contains(&self.template.steps_per_page) {
507 return Err(format!("steps per page must be 1, 2 or 4, not {}", self.template.steps_per_page));
508 }
509 let mut ids = HashSet::new();
510 let mut occurrences = HashSet::new();
511 for (_, step) in self.steps() {
512 if !ids.insert(step.id.as_str()) {
513 return Err(format!("duplicate id '{}'", step.id));
514 }
515 for add in &step.adds {
516 for occurrence in &add.occurrences {
517 if !occurrences.insert(occurrence.as_str()) {
518 return Err(format!("occurrence '{occurrence}' is added in more than one step"));
519 }
520 }
521 }
522 }
523 Ok(())
524 }
525
526 pub fn next_id(&mut self, prefix: &str) -> String {
528 self.id_counter += 1;
529 format!("{prefix}{}", self.id_counter)
530 }
531
532 pub fn step_count(&self) -> usize {
533 self.steps().count()
534 }
535
536 pub fn steps(&self) -> impl Iterator<Item = (usize, &Step)> {
539 fn walk<'a>(steps: &'a [Step], depth: usize, out: &mut Vec<(usize, &'a Step)>) {
540 for step in steps {
541 walk(&step.steps, depth + 1, out);
542 out.push((depth, step));
543 }
544 }
545 let mut out = Vec::with_capacity(16);
546 walk(&self.steps, 0, &mut out);
547 out.into_iter()
548 }
549
550 fn path_of(&self, step_id: &str) -> Option<Vec<usize>> {
552 fn walk(steps: &[Step], step_id: &str, path: &mut Vec<usize>) -> bool {
553 for (i, step) in steps.iter().enumerate() {
554 path.push(i);
555 if step.id == step_id || walk(&step.steps, step_id, path) {
556 return true;
557 }
558 path.pop();
559 }
560 false
561 }
562 let mut path = Vec::new();
563 walk(&self.steps, step_id, &mut path).then_some(path)
564 }
565
566 pub fn step(&self, step_id: &str) -> Option<&Step> {
567 self.steps().find(|(_, s)| s.id == step_id).map(|(_, s)| s)
568 }
569
570 pub fn step_mut(&mut self, step_id: &str) -> Option<&mut Step> {
571 let path = self.path_of(step_id)?;
572 let (last, parents) = path.split_last()?;
573 Some(&mut list_at_mut(&mut self.steps, parents)[*last])
574 }
575
576 pub fn siblings(&self, step_id: &str) -> Option<(&[Step], usize)> {
579 let path = self.path_of(step_id)?;
580 let (last, parents) = path.split_last()?;
581 let mut list = &self.steps;
582 for &i in parents {
583 list = &list[i].steps;
584 }
585 Some((list.as_slice(), *last))
586 }
587
588 pub fn siblings_mut(&mut self, step_id: &str) -> Option<(&mut Vec<Step>, usize)> {
589 let path = self.path_of(step_id)?;
590 let (last, parents) = path.split_last()?;
591 Some((list_at_mut(&mut self.steps, parents), *last))
592 }
593
594 pub fn parent_id(&self, step_id: &str) -> Option<Option<&str>> {
597 let path = self.path_of(step_id)?;
598 let (_, parents) = path.split_last()?;
599 let mut list = &self.steps;
600 let mut parent = None;
601 for &i in parents {
602 parent = Some(list[i].id.as_str());
603 list = &list[i].steps;
604 }
605 Some(parent)
606 }
607
608 pub fn depth(&self, step_id: &str) -> Option<usize> {
610 self.path_of(step_id).map(|path| path.len() - 1)
611 }
612
613 pub fn group_steps_mut(&mut self, occurrence: &str) -> Option<&mut Vec<Step>> {
616 if occurrence.is_empty() {
617 return Some(&mut self.steps);
618 }
619 let placing = self.steps().find(|(_, s)| s.places(occurrence)).map(|(_, s)| s.id.clone())?;
620 self.step_mut(&placing).map(|step| &mut step.steps)
621 }
622
623 pub fn step_number(&self, step_id: &str) -> Option<usize> {
625 self.steps().position(|(_, s)| s.id == step_id).map(|n| n + 1)
626 }
627
628 pub fn tools_list(&self) -> Vec<(ToolUse, Vec<String>)> {
630 let mut list: Vec<(ToolUse, Vec<String>)> = Vec::new();
631 for (_, step) in self.steps() {
632 for tool in &step.tools {
633 let same = |t: &ToolUse| match (&t.tool_id, &tool.tool_id) {
634 (Some(a), Some(b)) => a == b,
635 (None, None) => t.name == tool.name && t.spec == tool.spec,
636 _ => false,
637 };
638 match list.iter_mut().find(|(t, _)| same(t)) {
639 Some((_, steps)) => {
640 if !steps.contains(&step.id) {
641 steps.push(step.id.clone());
642 }
643 }
644 None => list.push((tool.clone(), vec![step.id.clone()])),
645 }
646 }
647 }
648 list
649 }
650
651 pub fn parts_list(&self) -> Vec<PartsRow> {
654 let mut rows: Vec<PartsRow> = Vec::new();
655 for (_, step) in self.steps() {
656 for add in &step.adds {
657 match rows.iter_mut().find(|r| r.part == add.part && r.find_number == add.find_number) {
658 Some(row) => row.quantity += add.quantity(),
659 None => rows.push(PartsRow {
660 part: add.part.clone(),
661 name: add.display_name().to_string(),
662 find_number: add.find_number.clone(),
663 quantity: add.quantity(),
664 subassembly: add.subassembly,
665 first_step: step.id.clone(),
666 }),
667 }
668 }
669 }
670 rows
671 }
672}
673
674fn list_at_mut<'a>(mut list: &'a mut Vec<Step>, parents: &[usize]) -> &'a mut Vec<Step> {
676 for &i in parents {
677 list = &mut list[i].steps;
678 }
679 list
680}
681
682pub fn for_each_step_mut(steps: &mut [Step], f: &mut dyn FnMut(&mut Step)) {
684 for step in steps {
685 f(step);
686 for_each_step_mut(&mut step.steps, f);
687 }
688}
689
690pub fn retain_steps(steps: &mut Vec<Step>, keep: &dyn Fn(&Step) -> bool) {
692 steps.retain(keep);
693 for step in steps {
694 retain_steps(&mut step.steps, keep);
695 }
696}
697
698fn migrate_chapters(value: &Value) -> Result<Value, String> {
704 let mut object = value.as_object().cloned().ok_or("instructions block: not an object")?;
705 let chapters: Vec<ChapterV1> = match object.remove("chapters") {
706 Some(chapters) => serde_json::from_value(chapters).map_err(|e| format!("instructions block: chapters: {e}"))?,
707 None => Vec::new(),
708 };
709 object.remove("steps");
711 let (root, others): (Vec<ChapterV1>, Vec<ChapterV1>) = chapters.into_iter().partition(|c| c.assembly.is_empty());
712 let mut steps: Vec<Step> = root.into_iter().flat_map(|c| c.steps).collect();
713 for chapter in others.into_iter().rev() {
717 let mut placing = None;
718 for_each_step_mut(&mut steps, &mut |step| {
719 if placing.is_none() && step.places(&chapter.assembly) {
720 placing = Some(step.id.clone());
721 }
722 });
723 let chapter_steps = chapter.steps;
724 match placing {
725 Some(id) => {
726 for_each_step_mut(&mut steps, &mut |step| {
727 if step.id == id {
728 step.steps = chapter_steps.clone();
729 }
730 });
731 }
732 None => steps.insert(0, Step { id: chapter.id, title: chapter.title, steps: chapter_steps, ..Step::default() }),
733 }
734 }
735 object.insert("schema".into(), Value::from(SCHEMA));
736 object.insert("steps".into(), serde_json::to_value(steps).map_err(|e| format!("instructions block: {e}"))?);
737 Ok(Value::Object(object))
738}
739
740#[derive(Debug, Clone, PartialEq, Serialize)]
742#[serde(rename_all = "camelCase")]
743pub struct PartsRow {
744 pub part: String,
745 pub name: String,
747 pub find_number: String,
748 pub quantity: usize,
749 pub subassembly: bool,
750 pub first_step: String,
751}
752