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))]
97#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
98#[serde(rename_all = "camelCase")]
99pub enum Style {
100 LineArt,
105 Shaded,
109}
110
111impl Style {
112 pub const CHOICES: [(Style, &'static str, &'static str); 2] =
114 [(Style::LineArt, "lineArt", "Line art"), (Style::Shaded, "shaded", "Shaded")];
115
116 pub fn saved_before_styles() -> Self {
118 Style::Shaded
119 }
120
121 pub fn as_str(self) -> &'static str {
122 match self {
123 Style::LineArt => "lineArt",
124 Style::Shaded => "shaded",
125 }
126 }
127}
128
129#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
131#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
132#[serde(rename_all = "camelCase")]
133pub struct Template {
134 pub steps_per_page: u8,
136 pub orientation: Orientation,
137 pub paper: String,
139 #[serde(default = "Style::saved_before_styles")]
143 pub style: Style,
144}
145
146impl Default for Template {
147 fn default() -> Self {
148 Self { steps_per_page: 1, orientation: Orientation::Portrait, paper: "A4".into(), style: Style::LineArt }
149 }
150}
151
152#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
154#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
155#[serde(rename_all = "camelCase")]
156pub struct FrontMatter {
157 #[serde(default)]
158 pub title: String,
159 #[serde(default)]
160 pub subtitle: String,
161 #[serde(default, skip_serializing_if = "Option::is_none")]
163 pub cover_step: Option<String>,
164 pub parts_list: bool,
165 pub tools_list: bool,
166}
167
168impl Default for FrontMatter {
169 fn default() -> Self {
170 Self { title: String::new(), subtitle: String::new(), cover_step: None, parts_list: true, tools_list: true }
171 }
172}
173
174#[derive(Debug, Clone, Deserialize)]
176#[serde(rename_all = "camelCase")]
177struct ChapterV1 {
178 id: String,
179 #[serde(default)]
182 assembly: String,
183 #[serde(default)]
184 title: String,
185 #[serde(default)]
186 steps: Vec<Step>,
187}
188
189#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
190#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
191#[serde(rename_all = "camelCase")]
192pub struct Step {
193 pub id: String,
194 pub title: String,
195 #[serde(default, skip_serializing_if = "String::is_empty")]
196 pub notes: String,
197 #[serde(default)]
198 pub adds: Vec<Add>,
199 #[serde(default, skip_serializing_if = "Option::is_none")]
201 pub view: Option<String>,
202 #[serde(default, skip_serializing_if = "Vec::is_empty")]
203 pub tools: Vec<ToolUse>,
204 #[serde(default, skip_serializing_if = "Option::is_none")]
205 pub torque: Option<Torque>,
206 #[serde(default, skip_serializing_if = "Vec::is_empty")]
207 pub callouts: Vec<Callout>,
208 #[serde(default, skip_serializing_if = "Vec::is_empty")]
210 pub arrows: Vec<Arrow>,
211 #[serde(default, skip_serializing_if = "Option::is_none")]
213 pub motion: Option<Value>,
214 #[serde(default)]
215 pub signoff: Signoff,
216 #[serde(default, skip_serializing_if = "Vec::is_empty")]
219 pub fields: Vec<crate::fields::StepField>,
220 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
224 pub camera_captured: bool,
225 #[serde(default, skip_serializing_if = "Vec::is_empty")]
228 pub steps: Vec<Step>,
229}
230
231#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
233#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
234#[serde(rename_all = "camelCase")]
235pub struct Add {
236 pub occurrences: Vec<String>,
238 pub part: String,
241 #[serde(default, skip_serializing_if = "String::is_empty")]
244 pub name: String,
245 #[serde(default)]
246 pub find_number: String,
247 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
249 pub subassembly: bool,
250 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
251 pub fastener: bool,
252 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
253 pub serial_tracked: bool,
254}
255
256impl Add {
257 pub fn quantity(&self) -> usize {
258 self.occurrences.len()
259 }
260
261 pub fn display_name(&self) -> &str {
264 if self.name.is_empty() {
265 &self.part
266 } else {
267 &self.name
268 }
269 }
270
271 pub fn named(occurrences: Vec<String>, part: &str, name: &str) -> Self {
274 Self {
275 occurrences,
276 part: part.to_string(),
277 name: if name == part { String::new() } else { name.to_string() },
278 ..Self::default()
279 }
280 }
281
282 fn same_row(&self, other: &Add) -> bool {
285 self.part == other.part && self.find_number == other.find_number && self.subassembly == other.subassembly
286 }
287}
288
289impl Step {
290 pub fn new(id: String, title: String) -> Self {
292 Self { id, title, ..Self::default() }
293 }
294
295 pub fn contains(&self, step_id: &str) -> bool {
297 self.id == step_id || self.steps.iter().any(|s| s.contains(step_id))
298 }
299
300 pub fn on_checklist(&self) -> bool {
304 self.signoff.required || !self.fields.is_empty()
305 }
306
307 fn places(&self, occurrence: &str) -> bool {
309 self.adds.iter().any(|a| a.subassembly && a.occurrences.iter().any(|o| o == occurrence))
310 }
311
312 pub fn occurrences_with_descendants<'a>(&'a self, out: &mut Vec<&'a str>) {
314 out.extend(self.adds.iter().flat_map(|a| a.occurrences.iter().map(String::as_str)));
315 for child in &self.steps {
316 child.occurrences_with_descendants(out);
317 }
318 }
319
320 pub fn coalesce_adds(&mut self) {
325 let mut rows: Vec<Add> = Vec::with_capacity(self.adds.len());
326 for mut add in std::mem::take(&mut self.adds) {
327 match rows.iter_mut().find(|row| row.same_row(&add)) {
328 Some(row) => {
329 row.occurrences.append(&mut add.occurrences);
330 row.fastener |= add.fastener;
331 row.serial_tracked |= add.serial_tracked;
332 }
333 None => rows.push(add),
334 }
335 }
336 self.adds = rows;
337 }
338}
339
340#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
343#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
344#[serde(rename_all = "camelCase")]
345pub struct ToolUse {
346 #[serde(default, skip_serializing_if = "Option::is_none")]
347 pub tool_id: Option<String>,
348 pub name: String,
349 #[serde(default)]
350 pub spec: String,
351 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
353 pub unlinked: bool,
354}
355
356#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
357#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
358#[serde(rename_all = "lowercase")]
359pub enum TorqueSource {
360 Part,
362 Override,
364}
365
366#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
367#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
368#[serde(rename_all = "camelCase")]
369pub struct Torque {
370 pub value: String,
372 #[serde(default)]
373 pub unit: String,
374 pub source: TorqueSource,
375}
376
377impl Torque {
378 pub fn from_attribute(text: &str) -> Option<Self> {
381 let text = text.trim();
382 if text.is_empty() {
383 return None;
384 }
385 let (value, unit) = match text.split_once(char::is_whitespace) {
386 Some((value, unit)) => (value.trim(), unit.trim()),
387 None => (text, ""),
388 };
389 Some(Self { value: value.into(), unit: unit.into(), source: TorqueSource::Part })
390 }
391
392 pub fn text(&self) -> String {
394 if self.unit.is_empty() {
395 self.value.clone()
396 } else {
397 format!("{} {}", self.value, self.unit)
398 }
399 }
400}
401
402#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
403#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
404#[serde(rename_all = "lowercase")]
405pub enum CalloutKind {
406 Caution,
407 Note,
408 Check,
409}
410
411impl CalloutKind {
412 pub fn label(self) -> &'static str {
413 match self {
414 Self::Caution => "Caution",
415 Self::Note => "Note",
416 Self::Check => "Check",
417 }
418 }
419}
420
421#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
422#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
423#[serde(rename_all = "camelCase")]
424pub struct Callout {
425 pub id: String,
426 pub kind: CalloutKind,
427 pub text: String,
428 #[serde(default, skip_serializing_if = "Option::is_none")]
430 pub occurrence: Option<String>,
431}
432
433#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
434#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
435#[serde(rename_all = "camelCase")]
436pub struct Arrow {
437 pub occurrence: String,
438 pub direction: [f64; 3],
440 pub distance: f64,
442}
443
444impl Arrow {
445 pub fn start_offset(&self) -> [f64; 3] {
448 let [x, y, z] = self.direction;
449 let length = (x * x + y * y + z * z).sqrt();
450 if !(length > 1e-12) || !self.distance.is_finite() {
451 return [0.0; 3];
452 }
453 let k = -self.distance / length;
454 [x * k, y * k, z * k]
455 }
456}
457
458#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
459#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
460#[serde(rename_all = "camelCase")]
461pub struct Signoff {
462 pub required: bool,
463}
464
465impl Default for Signoff {
466 fn default() -> Self {
467 Self { required: true }
468 }
469}
470
471#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
473#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
474#[serde(rename_all = "camelCase")]
475pub struct OccurrenceChange {
476 pub occurrence: String,
477 pub part: String,
478 #[serde(default, skip_serializing_if = "Option::is_none")]
480 pub was: Option<String>,
481}
482
483#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
486#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
487#[serde(rename_all = "camelCase")]
488pub struct Retarget {
489 pub from: Target,
490 pub to: Target,
491 #[serde(default)]
492 pub added: Vec<OccurrenceChange>,
493 #[serde(default)]
494 pub removed: Vec<OccurrenceChange>,
495 #[serde(default)]
496 pub replaced: Vec<OccurrenceChange>,
497 #[serde(default)]
500 pub touched_steps: Vec<String>,
501 #[serde(default)]
503 pub empty_steps: Vec<String>,
504}
505
506impl Instructions {
507 pub fn new(target: Target) -> Self {
509 let title = target.name.clone();
510 Self {
511 schema: SCHEMA,
512 target,
513 template: Template::default(),
514 front: FrontMatter { title, ..FrontMatter::default() },
515 steps: Vec::new(),
516 id_counter: 0,
517 retarget: None,
518 }
519 }
520
521 pub fn from_value(value: &Value) -> Result<Self, String> {
526 let schema = value.get("schema").and_then(Value::as_u64).unwrap_or(0);
527 let value = if schema == 1 { migrate_chapters(value)? } else { value.clone() };
528 let mut block: Self = serde_json::from_value(value).map_err(|e| format!("instructions block: {e}"))?;
529 block.validate()?;
530 block.coalesce_adds();
531 Ok(block)
532 }
533
534 pub fn coalesce_adds(&mut self) {
536 for_each_step_mut(&mut self.steps, &mut |step| step.coalesce_adds());
537 }
538
539 pub fn from_document(document: &Value) -> Result<Option<Self>, String> {
541 match document.get(BLOCK_KEY) {
542 None | Some(Value::Null) => Ok(None),
543 Some(block) => Self::from_value(block).map(Some),
544 }
545 }
546
547 pub fn to_value(&self) -> Value {
548 serde_json::to_value(self).expect("instructions block serializes")
549 }
550
551 pub fn validate(&self) -> Result<(), String> {
555 if self.schema == 0 || self.schema > SCHEMA {
556 return Err(format!("instructions schema {} is not supported (this build reads up to {SCHEMA})", self.schema));
557 }
558 if !STEPS_PER_PAGE.contains(&self.template.steps_per_page) {
559 return Err(format!("steps per page must be 1, 2 or 4, not {}", self.template.steps_per_page));
560 }
561 let mut ids = HashSet::new();
562 let mut occurrences = HashSet::new();
563 for (_, step) in self.steps() {
564 if !ids.insert(step.id.as_str()) {
565 return Err(format!("duplicate id '{}'", step.id));
566 }
567 for field in &step.fields {
568 if field.id.is_empty() || !ids.insert(field.id.as_str()) {
569 return Err(format!("duplicate id '{}'", field.id));
570 }
571 field.validate()?;
572 }
573 for add in &step.adds {
574 for occurrence in &add.occurrences {
575 if !occurrences.insert(occurrence.as_str()) {
576 return Err(format!("occurrence '{occurrence}' is added in more than one step"));
577 }
578 }
579 }
580 }
581 Ok(())
582 }
583
584 pub fn next_id(&mut self, prefix: &str) -> String {
587 self.id_counter += 1;
588 format!("{prefix}{}", self.id_counter)
589 }
590
591 pub fn step_count(&self) -> usize {
592 self.steps().count()
593 }
594
595 pub fn steps(&self) -> impl Iterator<Item = (usize, &Step)> {
598 fn walk<'a>(steps: &'a [Step], depth: usize, out: &mut Vec<(usize, &'a Step)>) {
599 for step in steps {
600 walk(&step.steps, depth + 1, out);
601 out.push((depth, step));
602 }
603 }
604 let mut out = Vec::with_capacity(16);
605 walk(&self.steps, 0, &mut out);
606 out.into_iter()
607 }
608
609 fn path_of(&self, step_id: &str) -> Option<Vec<usize>> {
611 fn walk(steps: &[Step], step_id: &str, path: &mut Vec<usize>) -> bool {
612 for (i, step) in steps.iter().enumerate() {
613 path.push(i);
614 if step.id == step_id || walk(&step.steps, step_id, path) {
615 return true;
616 }
617 path.pop();
618 }
619 false
620 }
621 let mut path = Vec::new();
622 walk(&self.steps, step_id, &mut path).then_some(path)
623 }
624
625 pub fn step(&self, step_id: &str) -> Option<&Step> {
626 self.steps().find(|(_, s)| s.id == step_id).map(|(_, s)| s)
627 }
628
629 pub fn step_mut(&mut self, step_id: &str) -> Option<&mut Step> {
630 let path = self.path_of(step_id)?;
631 let (last, parents) = path.split_last()?;
632 Some(&mut list_at_mut(&mut self.steps, parents)[*last])
633 }
634
635 pub fn siblings(&self, step_id: &str) -> Option<(&[Step], usize)> {
638 let path = self.path_of(step_id)?;
639 let (last, parents) = path.split_last()?;
640 let mut list = &self.steps;
641 for &i in parents {
642 list = &list[i].steps;
643 }
644 Some((list.as_slice(), *last))
645 }
646
647 pub fn siblings_mut(&mut self, step_id: &str) -> Option<(&mut Vec<Step>, usize)> {
648 let path = self.path_of(step_id)?;
649 let (last, parents) = path.split_last()?;
650 Some((list_at_mut(&mut self.steps, parents), *last))
651 }
652
653 pub fn parent_id(&self, step_id: &str) -> Option<Option<&str>> {
656 let path = self.path_of(step_id)?;
657 let (_, parents) = path.split_last()?;
658 let mut list = &self.steps;
659 let mut parent = None;
660 for &i in parents {
661 parent = Some(list[i].id.as_str());
662 list = &list[i].steps;
663 }
664 Some(parent)
665 }
666
667 pub fn depth(&self, step_id: &str) -> Option<usize> {
669 self.path_of(step_id).map(|path| path.len() - 1)
670 }
671
672 pub fn group_steps_mut(&mut self, occurrence: &str) -> Option<&mut Vec<Step>> {
675 if occurrence.is_empty() {
676 return Some(&mut self.steps);
677 }
678 let placing = self.steps().find(|(_, s)| s.places(occurrence)).map(|(_, s)| s.id.clone())?;
679 self.step_mut(&placing).map(|step| &mut step.steps)
680 }
681
682 pub fn step_number(&self, step_id: &str) -> Option<usize> {
684 self.steps().position(|(_, s)| s.id == step_id).map(|n| n + 1)
685 }
686
687 pub fn tools_list(&self) -> Vec<(ToolUse, Vec<String>)> {
689 let mut list: Vec<(ToolUse, Vec<String>)> = Vec::new();
690 for (_, step) in self.steps() {
691 for tool in &step.tools {
692 let same = |t: &ToolUse| match (&t.tool_id, &tool.tool_id) {
693 (Some(a), Some(b)) => a == b,
694 (None, None) => t.name == tool.name && t.spec == tool.spec,
695 _ => false,
696 };
697 match list.iter_mut().find(|(t, _)| same(t)) {
698 Some((_, steps)) => {
699 if !steps.contains(&step.id) {
700 steps.push(step.id.clone());
701 }
702 }
703 None => list.push((tool.clone(), vec![step.id.clone()])),
704 }
705 }
706 }
707 list
708 }
709
710 pub fn parts_list(&self) -> Vec<PartsRow> {
713 let mut rows: Vec<PartsRow> = Vec::new();
714 for (_, step) in self.steps() {
715 for add in &step.adds {
716 match rows.iter_mut().find(|r| r.part == add.part && r.find_number == add.find_number) {
717 Some(row) => row.quantity += add.quantity(),
718 None => rows.push(PartsRow {
719 part: add.part.clone(),
720 name: add.display_name().to_string(),
721 find_number: add.find_number.clone(),
722 quantity: add.quantity(),
723 subassembly: add.subassembly,
724 first_step: step.id.clone(),
725 }),
726 }
727 }
728 }
729 rows
730 }
731}
732
733fn list_at_mut<'a>(mut list: &'a mut Vec<Step>, parents: &[usize]) -> &'a mut Vec<Step> {
735 for &i in parents {
736 list = &mut list[i].steps;
737 }
738 list
739}
740
741pub fn for_each_step_mut(steps: &mut [Step], f: &mut dyn FnMut(&mut Step)) {
743 for step in steps {
744 f(step);
745 for_each_step_mut(&mut step.steps, f);
746 }
747}
748
749pub fn retain_steps(steps: &mut Vec<Step>, keep: &dyn Fn(&Step) -> bool) {
751 steps.retain(keep);
752 for step in steps {
753 retain_steps(&mut step.steps, keep);
754 }
755}
756
757fn migrate_chapters(value: &Value) -> Result<Value, String> {
763 let mut object = value.as_object().cloned().ok_or("instructions block: not an object")?;
764 let chapters: Vec<ChapterV1> = match object.remove("chapters") {
765 Some(chapters) => serde_json::from_value(chapters).map_err(|e| format!("instructions block: chapters: {e}"))?,
766 None => Vec::new(),
767 };
768 object.remove("steps");
770 let (root, others): (Vec<ChapterV1>, Vec<ChapterV1>) = chapters.into_iter().partition(|c| c.assembly.is_empty());
771 let mut steps: Vec<Step> = root.into_iter().flat_map(|c| c.steps).collect();
772 for chapter in others.into_iter().rev() {
776 let mut placing = None;
777 for_each_step_mut(&mut steps, &mut |step| {
778 if placing.is_none() && step.places(&chapter.assembly) {
779 placing = Some(step.id.clone());
780 }
781 });
782 let chapter_steps = chapter.steps;
783 match placing {
784 Some(id) => {
785 for_each_step_mut(&mut steps, &mut |step| {
786 if step.id == id {
787 step.steps = chapter_steps.clone();
788 }
789 });
790 }
791 None => steps.insert(0, Step { id: chapter.id, title: chapter.title, steps: chapter_steps, ..Step::default() }),
792 }
793 }
794 object.insert("schema".into(), Value::from(SCHEMA));
795 object.insert("steps".into(), serde_json::to_value(steps).map_err(|e| format!("instructions block: {e}"))?);
796 Ok(Value::Object(object))
797}
798
799#[derive(Debug, Clone, PartialEq, Serialize)]
801#[serde(rename_all = "camelCase")]
802pub struct PartsRow {
803 pub part: String,
804 pub name: String,
806 pub find_number: String,
807 pub quantity: usize,
808 pub subassembly: bool,
809 pub first_step: String,
810}
811