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#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
42#[serde(rename_all = "camelCase")]
43pub struct Instructions {
44 pub schema: u32,
45 pub target: Target,
48 #[serde(default)]
49 pub template: Template,
50 #[serde(default)]
51 pub front: FrontMatter,
52 #[serde(default)]
54 pub steps: Vec<Step>,
55 #[serde(default)]
56 pub id_counter: u64,
57 #[serde(default, skip_serializing_if = "Option::is_none")]
60 pub retarget: Option<Retarget>,
61}
62
63#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
65#[serde(rename_all = "camelCase")]
66pub struct Target {
67 pub source_key: String,
70 #[serde(default)]
71 pub part_number: String,
72 #[serde(default)]
74 pub revision: String,
75 #[serde(default)]
77 pub signature: String,
78 #[serde(default)]
80 pub name: String,
81}
82
83#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
84#[serde(rename_all = "lowercase")]
85pub enum Orientation {
86 #[default]
87 Portrait,
88 Landscape,
89}
90
91#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
93#[serde(rename_all = "camelCase")]
94pub struct Template {
95 pub steps_per_page: u8,
97 pub orientation: Orientation,
98 pub paper: String,
100}
101
102impl Default for Template {
103 fn default() -> Self {
104 Self { steps_per_page: 1, orientation: Orientation::Portrait, paper: "A4".into() }
105 }
106}
107
108#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
110#[serde(rename_all = "camelCase")]
111pub struct FrontMatter {
112 #[serde(default)]
113 pub title: String,
114 #[serde(default)]
115 pub subtitle: String,
116 #[serde(default, skip_serializing_if = "Option::is_none")]
118 pub cover_step: Option<String>,
119 pub parts_list: bool,
120 pub tools_list: bool,
121}
122
123impl Default for FrontMatter {
124 fn default() -> Self {
125 Self { title: String::new(), subtitle: String::new(), cover_step: None, parts_list: true, tools_list: true }
126 }
127}
128
129#[derive(Debug, Clone, Deserialize)]
131#[serde(rename_all = "camelCase")]
132struct ChapterV1 {
133 id: String,
134 #[serde(default)]
137 assembly: String,
138 #[serde(default)]
139 title: String,
140 #[serde(default)]
141 steps: Vec<Step>,
142}
143
144#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
145#[serde(rename_all = "camelCase")]
146pub struct Step {
147 pub id: String,
148 pub title: String,
149 #[serde(default, skip_serializing_if = "String::is_empty")]
150 pub notes: String,
151 #[serde(default)]
152 pub adds: Vec<Add>,
153 #[serde(default, skip_serializing_if = "Option::is_none")]
155 pub view: Option<String>,
156 #[serde(default, skip_serializing_if = "Vec::is_empty")]
157 pub tools: Vec<ToolUse>,
158 #[serde(default, skip_serializing_if = "Option::is_none")]
159 pub torque: Option<Torque>,
160 #[serde(default, skip_serializing_if = "Vec::is_empty")]
161 pub callouts: Vec<Callout>,
162 #[serde(default, skip_serializing_if = "Vec::is_empty")]
164 pub arrows: Vec<Arrow>,
165 #[serde(default, skip_serializing_if = "Option::is_none")]
167 pub motion: Option<Value>,
168 #[serde(default)]
169 pub signoff: Signoff,
170 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
174 pub camera_captured: bool,
175 #[serde(default, skip_serializing_if = "Vec::is_empty")]
178 pub steps: Vec<Step>,
179}
180
181#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
183#[serde(rename_all = "camelCase")]
184pub struct Add {
185 pub occurrences: Vec<String>,
187 pub part: String,
190 #[serde(default, skip_serializing_if = "String::is_empty")]
193 pub name: String,
194 #[serde(default)]
195 pub find_number: String,
196 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
198 pub subassembly: bool,
199 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
200 pub fastener: bool,
201 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
202 pub serial_tracked: bool,
203}
204
205impl Add {
206 pub fn quantity(&self) -> usize {
207 self.occurrences.len()
208 }
209
210 pub fn display_name(&self) -> &str {
213 if self.name.is_empty() {
214 &self.part
215 } else {
216 &self.name
217 }
218 }
219
220 pub fn named(occurrences: Vec<String>, part: &str, name: &str) -> Self {
223 Self {
224 occurrences,
225 part: part.to_string(),
226 name: if name == part { String::new() } else { name.to_string() },
227 ..Self::default()
228 }
229 }
230
231 fn same_row(&self, other: &Add) -> bool {
234 self.part == other.part && self.find_number == other.find_number && self.subassembly == other.subassembly
235 }
236}
237
238impl Step {
239 pub fn new(id: String, title: String) -> Self {
241 Self { id, title, ..Self::default() }
242 }
243
244 pub fn contains(&self, step_id: &str) -> bool {
246 self.id == step_id || self.steps.iter().any(|s| s.contains(step_id))
247 }
248
249 fn places(&self, occurrence: &str) -> bool {
251 self.adds.iter().any(|a| a.subassembly && a.occurrences.iter().any(|o| o == occurrence))
252 }
253
254 pub fn occurrences_with_descendants<'a>(&'a self, out: &mut Vec<&'a str>) {
256 out.extend(self.adds.iter().flat_map(|a| a.occurrences.iter().map(String::as_str)));
257 for child in &self.steps {
258 child.occurrences_with_descendants(out);
259 }
260 }
261
262 pub fn coalesce_adds(&mut self) {
267 let mut rows: Vec<Add> = Vec::with_capacity(self.adds.len());
268 for mut add in std::mem::take(&mut self.adds) {
269 match rows.iter_mut().find(|row| row.same_row(&add)) {
270 Some(row) => {
271 row.occurrences.append(&mut add.occurrences);
272 row.fastener |= add.fastener;
273 row.serial_tracked |= add.serial_tracked;
274 }
275 None => rows.push(add),
276 }
277 }
278 self.adds = rows;
279 }
280}
281
282#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
285#[serde(rename_all = "camelCase")]
286pub struct ToolUse {
287 #[serde(default, skip_serializing_if = "Option::is_none")]
288 pub tool_id: Option<String>,
289 pub name: String,
290 #[serde(default)]
291 pub spec: String,
292 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
294 pub unlinked: bool,
295}
296
297#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
298#[serde(rename_all = "lowercase")]
299pub enum TorqueSource {
300 Part,
302 Override,
304}
305
306#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
307#[serde(rename_all = "camelCase")]
308pub struct Torque {
309 pub value: String,
311 #[serde(default)]
312 pub unit: String,
313 pub source: TorqueSource,
314}
315
316impl Torque {
317 pub fn from_attribute(text: &str) -> Option<Self> {
320 let text = text.trim();
321 if text.is_empty() {
322 return None;
323 }
324 let (value, unit) = match text.split_once(char::is_whitespace) {
325 Some((value, unit)) => (value.trim(), unit.trim()),
326 None => (text, ""),
327 };
328 Some(Self { value: value.into(), unit: unit.into(), source: TorqueSource::Part })
329 }
330
331 pub fn text(&self) -> String {
333 if self.unit.is_empty() {
334 self.value.clone()
335 } else {
336 format!("{} {}", self.value, self.unit)
337 }
338 }
339}
340
341#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
342#[serde(rename_all = "lowercase")]
343pub enum CalloutKind {
344 Caution,
345 Note,
346 Check,
347}
348
349impl CalloutKind {
350 pub fn label(self) -> &'static str {
351 match self {
352 Self::Caution => "Caution",
353 Self::Note => "Note",
354 Self::Check => "Check",
355 }
356 }
357}
358
359#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
360#[serde(rename_all = "camelCase")]
361pub struct Callout {
362 pub id: String,
363 pub kind: CalloutKind,
364 pub text: String,
365 #[serde(default, skip_serializing_if = "Option::is_none")]
367 pub occurrence: Option<String>,
368}
369
370#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
371#[serde(rename_all = "camelCase")]
372pub struct Arrow {
373 pub occurrence: String,
374 pub direction: [f64; 3],
376 pub distance: f64,
378}
379
380impl Arrow {
381 pub fn start_offset(&self) -> [f64; 3] {
384 let [x, y, z] = self.direction;
385 let length = (x * x + y * y + z * z).sqrt();
386 if !(length > 1e-12) || !self.distance.is_finite() {
387 return [0.0; 3];
388 }
389 let k = -self.distance / length;
390 [x * k, y * k, z * k]
391 }
392}
393
394#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
395#[serde(rename_all = "camelCase")]
396pub struct Signoff {
397 pub required: bool,
398}
399
400impl Default for Signoff {
401 fn default() -> Self {
402 Self { required: true }
403 }
404}
405
406#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
408#[serde(rename_all = "camelCase")]
409pub struct OccurrenceChange {
410 pub occurrence: String,
411 pub part: String,
412 #[serde(default, skip_serializing_if = "Option::is_none")]
414 pub was: Option<String>,
415}
416
417#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
420#[serde(rename_all = "camelCase")]
421pub struct Retarget {
422 pub from: Target,
423 pub to: Target,
424 #[serde(default)]
425 pub added: Vec<OccurrenceChange>,
426 #[serde(default)]
427 pub removed: Vec<OccurrenceChange>,
428 #[serde(default)]
429 pub replaced: Vec<OccurrenceChange>,
430 #[serde(default)]
433 pub touched_steps: Vec<String>,
434 #[serde(default)]
436 pub empty_steps: Vec<String>,
437}
438
439impl Instructions {
440 pub fn new(target: Target) -> Self {
442 let title = target.name.clone();
443 Self {
444 schema: SCHEMA,
445 target,
446 template: Template::default(),
447 front: FrontMatter { title, ..FrontMatter::default() },
448 steps: Vec::new(),
449 id_counter: 0,
450 retarget: None,
451 }
452 }
453
454 pub fn from_value(value: &Value) -> Result<Self, String> {
459 let schema = value.get("schema").and_then(Value::as_u64).unwrap_or(0);
460 let value = if schema == 1 { migrate_chapters(value)? } else { value.clone() };
461 let mut block: Self = serde_json::from_value(value).map_err(|e| format!("instructions block: {e}"))?;
462 block.validate()?;
463 block.coalesce_adds();
464 Ok(block)
465 }
466
467 pub fn coalesce_adds(&mut self) {
469 for_each_step_mut(&mut self.steps, &mut |step| step.coalesce_adds());
470 }
471
472 pub fn from_document(document: &Value) -> Result<Option<Self>, String> {
474 match document.get(BLOCK_KEY) {
475 None | Some(Value::Null) => Ok(None),
476 Some(block) => Self::from_value(block).map(Some),
477 }
478 }
479
480 pub fn to_value(&self) -> Value {
481 serde_json::to_value(self).expect("instructions block serializes")
482 }
483
484 pub fn validate(&self) -> Result<(), String> {
487 if self.schema == 0 || self.schema > SCHEMA {
488 return Err(format!("instructions schema {} is not supported (this build reads up to {SCHEMA})", self.schema));
489 }
490 if !STEPS_PER_PAGE.contains(&self.template.steps_per_page) {
491 return Err(format!("steps per page must be 1, 2 or 4, not {}", self.template.steps_per_page));
492 }
493 let mut ids = HashSet::new();
494 let mut occurrences = HashSet::new();
495 for (_, step) in self.steps() {
496 if !ids.insert(step.id.as_str()) {
497 return Err(format!("duplicate id '{}'", step.id));
498 }
499 for add in &step.adds {
500 for occurrence in &add.occurrences {
501 if !occurrences.insert(occurrence.as_str()) {
502 return Err(format!("occurrence '{occurrence}' is added in more than one step"));
503 }
504 }
505 }
506 }
507 Ok(())
508 }
509
510 pub fn next_id(&mut self, prefix: &str) -> String {
512 self.id_counter += 1;
513 format!("{prefix}{}", self.id_counter)
514 }
515
516 pub fn step_count(&self) -> usize {
517 self.steps().count()
518 }
519
520 pub fn steps(&self) -> impl Iterator<Item = (usize, &Step)> {
523 fn walk<'a>(steps: &'a [Step], depth: usize, out: &mut Vec<(usize, &'a Step)>) {
524 for step in steps {
525 walk(&step.steps, depth + 1, out);
526 out.push((depth, step));
527 }
528 }
529 let mut out = Vec::with_capacity(16);
530 walk(&self.steps, 0, &mut out);
531 out.into_iter()
532 }
533
534 fn path_of(&self, step_id: &str) -> Option<Vec<usize>> {
536 fn walk(steps: &[Step], step_id: &str, path: &mut Vec<usize>) -> bool {
537 for (i, step) in steps.iter().enumerate() {
538 path.push(i);
539 if step.id == step_id || walk(&step.steps, step_id, path) {
540 return true;
541 }
542 path.pop();
543 }
544 false
545 }
546 let mut path = Vec::new();
547 walk(&self.steps, step_id, &mut path).then_some(path)
548 }
549
550 pub fn step(&self, step_id: &str) -> Option<&Step> {
551 self.steps().find(|(_, s)| s.id == step_id).map(|(_, s)| s)
552 }
553
554 pub fn step_mut(&mut self, step_id: &str) -> Option<&mut Step> {
555 let path = self.path_of(step_id)?;
556 let (last, parents) = path.split_last()?;
557 Some(&mut list_at_mut(&mut self.steps, parents)[*last])
558 }
559
560 pub fn siblings(&self, step_id: &str) -> Option<(&[Step], usize)> {
563 let path = self.path_of(step_id)?;
564 let (last, parents) = path.split_last()?;
565 let mut list = &self.steps;
566 for &i in parents {
567 list = &list[i].steps;
568 }
569 Some((list.as_slice(), *last))
570 }
571
572 pub fn siblings_mut(&mut self, step_id: &str) -> Option<(&mut Vec<Step>, usize)> {
573 let path = self.path_of(step_id)?;
574 let (last, parents) = path.split_last()?;
575 Some((list_at_mut(&mut self.steps, parents), *last))
576 }
577
578 pub fn parent_id(&self, step_id: &str) -> Option<Option<&str>> {
581 let path = self.path_of(step_id)?;
582 let (_, parents) = path.split_last()?;
583 let mut list = &self.steps;
584 let mut parent = None;
585 for &i in parents {
586 parent = Some(list[i].id.as_str());
587 list = &list[i].steps;
588 }
589 Some(parent)
590 }
591
592 pub fn depth(&self, step_id: &str) -> Option<usize> {
594 self.path_of(step_id).map(|path| path.len() - 1)
595 }
596
597 pub fn group_steps_mut(&mut self, occurrence: &str) -> Option<&mut Vec<Step>> {
600 if occurrence.is_empty() {
601 return Some(&mut self.steps);
602 }
603 let placing = self.steps().find(|(_, s)| s.places(occurrence)).map(|(_, s)| s.id.clone())?;
604 self.step_mut(&placing).map(|step| &mut step.steps)
605 }
606
607 pub fn step_number(&self, step_id: &str) -> Option<usize> {
609 self.steps().position(|(_, s)| s.id == step_id).map(|n| n + 1)
610 }
611
612 pub fn tools_list(&self) -> Vec<(ToolUse, Vec<String>)> {
614 let mut list: Vec<(ToolUse, Vec<String>)> = Vec::new();
615 for (_, step) in self.steps() {
616 for tool in &step.tools {
617 let same = |t: &ToolUse| match (&t.tool_id, &tool.tool_id) {
618 (Some(a), Some(b)) => a == b,
619 (None, None) => t.name == tool.name && t.spec == tool.spec,
620 _ => false,
621 };
622 match list.iter_mut().find(|(t, _)| same(t)) {
623 Some((_, steps)) => {
624 if !steps.contains(&step.id) {
625 steps.push(step.id.clone());
626 }
627 }
628 None => list.push((tool.clone(), vec![step.id.clone()])),
629 }
630 }
631 }
632 list
633 }
634
635 pub fn parts_list(&self) -> Vec<PartsRow> {
638 let mut rows: Vec<PartsRow> = Vec::new();
639 for (_, step) in self.steps() {
640 for add in &step.adds {
641 match rows.iter_mut().find(|r| r.part == add.part && r.find_number == add.find_number) {
642 Some(row) => row.quantity += add.quantity(),
643 None => rows.push(PartsRow {
644 part: add.part.clone(),
645 name: add.display_name().to_string(),
646 find_number: add.find_number.clone(),
647 quantity: add.quantity(),
648 subassembly: add.subassembly,
649 first_step: step.id.clone(),
650 }),
651 }
652 }
653 }
654 rows
655 }
656}
657
658fn list_at_mut<'a>(mut list: &'a mut Vec<Step>, parents: &[usize]) -> &'a mut Vec<Step> {
660 for &i in parents {
661 list = &mut list[i].steps;
662 }
663 list
664}
665
666pub fn for_each_step_mut(steps: &mut [Step], f: &mut dyn FnMut(&mut Step)) {
668 for step in steps {
669 f(step);
670 for_each_step_mut(&mut step.steps, f);
671 }
672}
673
674pub fn retain_steps(steps: &mut Vec<Step>, keep: &dyn Fn(&Step) -> bool) {
676 steps.retain(keep);
677 for step in steps {
678 retain_steps(&mut step.steps, keep);
679 }
680}
681
682fn migrate_chapters(value: &Value) -> Result<Value, String> {
688 let mut object = value.as_object().cloned().ok_or("instructions block: not an object")?;
689 let chapters: Vec<ChapterV1> = match object.remove("chapters") {
690 Some(chapters) => serde_json::from_value(chapters).map_err(|e| format!("instructions block: chapters: {e}"))?,
691 None => Vec::new(),
692 };
693 object.remove("steps");
695 let (root, others): (Vec<ChapterV1>, Vec<ChapterV1>) = chapters.into_iter().partition(|c| c.assembly.is_empty());
696 let mut steps: Vec<Step> = root.into_iter().flat_map(|c| c.steps).collect();
697 for chapter in others.into_iter().rev() {
701 let mut placing = None;
702 for_each_step_mut(&mut steps, &mut |step| {
703 if placing.is_none() && step.places(&chapter.assembly) {
704 placing = Some(step.id.clone());
705 }
706 });
707 let chapter_steps = chapter.steps;
708 match placing {
709 Some(id) => {
710 for_each_step_mut(&mut steps, &mut |step| {
711 if step.id == id {
712 step.steps = chapter_steps.clone();
713 }
714 });
715 }
716 None => steps.insert(0, Step { id: chapter.id, title: chapter.title, steps: chapter_steps, ..Step::default() }),
717 }
718 }
719 object.insert("schema".into(), Value::from(SCHEMA));
720 object.insert("steps".into(), serde_json::to_value(steps).map_err(|e| format!("instructions block: {e}"))?);
721 Ok(Value::Object(object))
722}
723
724#[derive(Debug, Clone, PartialEq, Serialize)]
726#[serde(rename_all = "camelCase")]
727pub struct PartsRow {
728 pub part: String,
729 pub name: String,
731 pub find_number: String,
732 pub quantity: usize,
733 pub subassembly: bool,
734 pub first_step: String,
735}
736