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 = "std::ops::Not::not")]
220 pub camera_captured: bool,
221 #[serde(default, skip_serializing_if = "Vec::is_empty")]
224 pub steps: Vec<Step>,
225}
226
227#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
229#[derive(Debug, Clone, Default, PartialEq, Serialize, Deserialize)]
230#[serde(rename_all = "camelCase")]
231pub struct Add {
232 pub occurrences: Vec<String>,
234 pub part: String,
237 #[serde(default, skip_serializing_if = "String::is_empty")]
240 pub name: String,
241 #[serde(default)]
242 pub find_number: String,
243 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
245 pub subassembly: bool,
246 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
247 pub fastener: bool,
248 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
249 pub serial_tracked: bool,
250}
251
252impl Add {
253 pub fn quantity(&self) -> usize {
254 self.occurrences.len()
255 }
256
257 pub fn display_name(&self) -> &str {
260 if self.name.is_empty() {
261 &self.part
262 } else {
263 &self.name
264 }
265 }
266
267 pub fn named(occurrences: Vec<String>, part: &str, name: &str) -> Self {
270 Self {
271 occurrences,
272 part: part.to_string(),
273 name: if name == part { String::new() } else { name.to_string() },
274 ..Self::default()
275 }
276 }
277
278 fn same_row(&self, other: &Add) -> bool {
281 self.part == other.part && self.find_number == other.find_number && self.subassembly == other.subassembly
282 }
283}
284
285impl Step {
286 pub fn new(id: String, title: String) -> Self {
288 Self { id, title, ..Self::default() }
289 }
290
291 pub fn contains(&self, step_id: &str) -> bool {
293 self.id == step_id || self.steps.iter().any(|s| s.contains(step_id))
294 }
295
296 fn places(&self, occurrence: &str) -> bool {
298 self.adds.iter().any(|a| a.subassembly && a.occurrences.iter().any(|o| o == occurrence))
299 }
300
301 pub fn occurrences_with_descendants<'a>(&'a self, out: &mut Vec<&'a str>) {
303 out.extend(self.adds.iter().flat_map(|a| a.occurrences.iter().map(String::as_str)));
304 for child in &self.steps {
305 child.occurrences_with_descendants(out);
306 }
307 }
308
309 pub fn coalesce_adds(&mut self) {
314 let mut rows: Vec<Add> = Vec::with_capacity(self.adds.len());
315 for mut add in std::mem::take(&mut self.adds) {
316 match rows.iter_mut().find(|row| row.same_row(&add)) {
317 Some(row) => {
318 row.occurrences.append(&mut add.occurrences);
319 row.fastener |= add.fastener;
320 row.serial_tracked |= add.serial_tracked;
321 }
322 None => rows.push(add),
323 }
324 }
325 self.adds = rows;
326 }
327}
328
329#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
332#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
333#[serde(rename_all = "camelCase")]
334pub struct ToolUse {
335 #[serde(default, skip_serializing_if = "Option::is_none")]
336 pub tool_id: Option<String>,
337 pub name: String,
338 #[serde(default)]
339 pub spec: String,
340 #[serde(default, skip_serializing_if = "std::ops::Not::not")]
342 pub unlinked: bool,
343}
344
345#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
346#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
347#[serde(rename_all = "lowercase")]
348pub enum TorqueSource {
349 Part,
351 Override,
353}
354
355#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
356#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
357#[serde(rename_all = "camelCase")]
358pub struct Torque {
359 pub value: String,
361 #[serde(default)]
362 pub unit: String,
363 pub source: TorqueSource,
364}
365
366impl Torque {
367 pub fn from_attribute(text: &str) -> Option<Self> {
370 let text = text.trim();
371 if text.is_empty() {
372 return None;
373 }
374 let (value, unit) = match text.split_once(char::is_whitespace) {
375 Some((value, unit)) => (value.trim(), unit.trim()),
376 None => (text, ""),
377 };
378 Some(Self { value: value.into(), unit: unit.into(), source: TorqueSource::Part })
379 }
380
381 pub fn text(&self) -> String {
383 if self.unit.is_empty() {
384 self.value.clone()
385 } else {
386 format!("{} {}", self.value, self.unit)
387 }
388 }
389}
390
391#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
392#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
393#[serde(rename_all = "lowercase")]
394pub enum CalloutKind {
395 Caution,
396 Note,
397 Check,
398}
399
400impl CalloutKind {
401 pub fn label(self) -> &'static str {
402 match self {
403 Self::Caution => "Caution",
404 Self::Note => "Note",
405 Self::Check => "Check",
406 }
407 }
408}
409
410#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
411#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
412#[serde(rename_all = "camelCase")]
413pub struct Callout {
414 pub id: String,
415 pub kind: CalloutKind,
416 pub text: String,
417 #[serde(default, skip_serializing_if = "Option::is_none")]
419 pub occurrence: Option<String>,
420}
421
422#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
423#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
424#[serde(rename_all = "camelCase")]
425pub struct Arrow {
426 pub occurrence: String,
427 pub direction: [f64; 3],
429 pub distance: f64,
431}
432
433impl Arrow {
434 pub fn start_offset(&self) -> [f64; 3] {
437 let [x, y, z] = self.direction;
438 let length = (x * x + y * y + z * z).sqrt();
439 if !(length > 1e-12) || !self.distance.is_finite() {
440 return [0.0; 3];
441 }
442 let k = -self.distance / length;
443 [x * k, y * k, z * k]
444 }
445}
446
447#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
448#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
449#[serde(rename_all = "camelCase")]
450pub struct Signoff {
451 pub required: bool,
452}
453
454impl Default for Signoff {
455 fn default() -> Self {
456 Self { required: true }
457 }
458}
459
460#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
462#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
463#[serde(rename_all = "camelCase")]
464pub struct OccurrenceChange {
465 pub occurrence: String,
466 pub part: String,
467 #[serde(default, skip_serializing_if = "Option::is_none")]
469 pub was: Option<String>,
470}
471
472#[cfg_attr(feature = "schema", derive(schemars::JsonSchema))]
475#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
476#[serde(rename_all = "camelCase")]
477pub struct Retarget {
478 pub from: Target,
479 pub to: Target,
480 #[serde(default)]
481 pub added: Vec<OccurrenceChange>,
482 #[serde(default)]
483 pub removed: Vec<OccurrenceChange>,
484 #[serde(default)]
485 pub replaced: Vec<OccurrenceChange>,
486 #[serde(default)]
489 pub touched_steps: Vec<String>,
490 #[serde(default)]
492 pub empty_steps: Vec<String>,
493}
494
495impl Instructions {
496 pub fn new(target: Target) -> Self {
498 let title = target.name.clone();
499 Self {
500 schema: SCHEMA,
501 target,
502 template: Template::default(),
503 front: FrontMatter { title, ..FrontMatter::default() },
504 steps: Vec::new(),
505 id_counter: 0,
506 retarget: None,
507 }
508 }
509
510 pub fn from_value(value: &Value) -> Result<Self, String> {
515 let schema = value.get("schema").and_then(Value::as_u64).unwrap_or(0);
516 let value = if schema == 1 { migrate_chapters(value)? } else { value.clone() };
517 let mut block: Self = serde_json::from_value(value).map_err(|e| format!("instructions block: {e}"))?;
518 block.validate()?;
519 block.coalesce_adds();
520 Ok(block)
521 }
522
523 pub fn coalesce_adds(&mut self) {
525 for_each_step_mut(&mut self.steps, &mut |step| step.coalesce_adds());
526 }
527
528 pub fn from_document(document: &Value) -> Result<Option<Self>, String> {
530 match document.get(BLOCK_KEY) {
531 None | Some(Value::Null) => Ok(None),
532 Some(block) => Self::from_value(block).map(Some),
533 }
534 }
535
536 pub fn to_value(&self) -> Value {
537 serde_json::to_value(self).expect("instructions block serializes")
538 }
539
540 pub fn validate(&self) -> Result<(), String> {
543 if self.schema == 0 || self.schema > SCHEMA {
544 return Err(format!("instructions schema {} is not supported (this build reads up to {SCHEMA})", self.schema));
545 }
546 if !STEPS_PER_PAGE.contains(&self.template.steps_per_page) {
547 return Err(format!("steps per page must be 1, 2 or 4, not {}", self.template.steps_per_page));
548 }
549 let mut ids = HashSet::new();
550 let mut occurrences = HashSet::new();
551 for (_, step) in self.steps() {
552 if !ids.insert(step.id.as_str()) {
553 return Err(format!("duplicate id '{}'", step.id));
554 }
555 for add in &step.adds {
556 for occurrence in &add.occurrences {
557 if !occurrences.insert(occurrence.as_str()) {
558 return Err(format!("occurrence '{occurrence}' is added in more than one step"));
559 }
560 }
561 }
562 }
563 Ok(())
564 }
565
566 pub fn next_id(&mut self, prefix: &str) -> String {
568 self.id_counter += 1;
569 format!("{prefix}{}", self.id_counter)
570 }
571
572 pub fn step_count(&self) -> usize {
573 self.steps().count()
574 }
575
576 pub fn steps(&self) -> impl Iterator<Item = (usize, &Step)> {
579 fn walk<'a>(steps: &'a [Step], depth: usize, out: &mut Vec<(usize, &'a Step)>) {
580 for step in steps {
581 walk(&step.steps, depth + 1, out);
582 out.push((depth, step));
583 }
584 }
585 let mut out = Vec::with_capacity(16);
586 walk(&self.steps, 0, &mut out);
587 out.into_iter()
588 }
589
590 fn path_of(&self, step_id: &str) -> Option<Vec<usize>> {
592 fn walk(steps: &[Step], step_id: &str, path: &mut Vec<usize>) -> bool {
593 for (i, step) in steps.iter().enumerate() {
594 path.push(i);
595 if step.id == step_id || walk(&step.steps, step_id, path) {
596 return true;
597 }
598 path.pop();
599 }
600 false
601 }
602 let mut path = Vec::new();
603 walk(&self.steps, step_id, &mut path).then_some(path)
604 }
605
606 pub fn step(&self, step_id: &str) -> Option<&Step> {
607 self.steps().find(|(_, s)| s.id == step_id).map(|(_, s)| s)
608 }
609
610 pub fn step_mut(&mut self, step_id: &str) -> Option<&mut Step> {
611 let path = self.path_of(step_id)?;
612 let (last, parents) = path.split_last()?;
613 Some(&mut list_at_mut(&mut self.steps, parents)[*last])
614 }
615
616 pub fn siblings(&self, step_id: &str) -> Option<(&[Step], usize)> {
619 let path = self.path_of(step_id)?;
620 let (last, parents) = path.split_last()?;
621 let mut list = &self.steps;
622 for &i in parents {
623 list = &list[i].steps;
624 }
625 Some((list.as_slice(), *last))
626 }
627
628 pub fn siblings_mut(&mut self, step_id: &str) -> Option<(&mut Vec<Step>, usize)> {
629 let path = self.path_of(step_id)?;
630 let (last, parents) = path.split_last()?;
631 Some((list_at_mut(&mut self.steps, parents), *last))
632 }
633
634 pub fn parent_id(&self, step_id: &str) -> Option<Option<&str>> {
637 let path = self.path_of(step_id)?;
638 let (_, parents) = path.split_last()?;
639 let mut list = &self.steps;
640 let mut parent = None;
641 for &i in parents {
642 parent = Some(list[i].id.as_str());
643 list = &list[i].steps;
644 }
645 Some(parent)
646 }
647
648 pub fn depth(&self, step_id: &str) -> Option<usize> {
650 self.path_of(step_id).map(|path| path.len() - 1)
651 }
652
653 pub fn group_steps_mut(&mut self, occurrence: &str) -> Option<&mut Vec<Step>> {
656 if occurrence.is_empty() {
657 return Some(&mut self.steps);
658 }
659 let placing = self.steps().find(|(_, s)| s.places(occurrence)).map(|(_, s)| s.id.clone())?;
660 self.step_mut(&placing).map(|step| &mut step.steps)
661 }
662
663 pub fn step_number(&self, step_id: &str) -> Option<usize> {
665 self.steps().position(|(_, s)| s.id == step_id).map(|n| n + 1)
666 }
667
668 pub fn tools_list(&self) -> Vec<(ToolUse, Vec<String>)> {
670 let mut list: Vec<(ToolUse, Vec<String>)> = Vec::new();
671 for (_, step) in self.steps() {
672 for tool in &step.tools {
673 let same = |t: &ToolUse| match (&t.tool_id, &tool.tool_id) {
674 (Some(a), Some(b)) => a == b,
675 (None, None) => t.name == tool.name && t.spec == tool.spec,
676 _ => false,
677 };
678 match list.iter_mut().find(|(t, _)| same(t)) {
679 Some((_, steps)) => {
680 if !steps.contains(&step.id) {
681 steps.push(step.id.clone());
682 }
683 }
684 None => list.push((tool.clone(), vec![step.id.clone()])),
685 }
686 }
687 }
688 list
689 }
690
691 pub fn parts_list(&self) -> Vec<PartsRow> {
694 let mut rows: Vec<PartsRow> = Vec::new();
695 for (_, step) in self.steps() {
696 for add in &step.adds {
697 match rows.iter_mut().find(|r| r.part == add.part && r.find_number == add.find_number) {
698 Some(row) => row.quantity += add.quantity(),
699 None => rows.push(PartsRow {
700 part: add.part.clone(),
701 name: add.display_name().to_string(),
702 find_number: add.find_number.clone(),
703 quantity: add.quantity(),
704 subassembly: add.subassembly,
705 first_step: step.id.clone(),
706 }),
707 }
708 }
709 }
710 rows
711 }
712}
713
714fn list_at_mut<'a>(mut list: &'a mut Vec<Step>, parents: &[usize]) -> &'a mut Vec<Step> {
716 for &i in parents {
717 list = &mut list[i].steps;
718 }
719 list
720}
721
722pub fn for_each_step_mut(steps: &mut [Step], f: &mut dyn FnMut(&mut Step)) {
724 for step in steps {
725 f(step);
726 for_each_step_mut(&mut step.steps, f);
727 }
728}
729
730pub fn retain_steps(steps: &mut Vec<Step>, keep: &dyn Fn(&Step) -> bool) {
732 steps.retain(keep);
733 for step in steps {
734 retain_steps(&mut step.steps, keep);
735 }
736}
737
738fn migrate_chapters(value: &Value) -> Result<Value, String> {
744 let mut object = value.as_object().cloned().ok_or("instructions block: not an object")?;
745 let chapters: Vec<ChapterV1> = match object.remove("chapters") {
746 Some(chapters) => serde_json::from_value(chapters).map_err(|e| format!("instructions block: chapters: {e}"))?,
747 None => Vec::new(),
748 };
749 object.remove("steps");
751 let (root, others): (Vec<ChapterV1>, Vec<ChapterV1>) = chapters.into_iter().partition(|c| c.assembly.is_empty());
752 let mut steps: Vec<Step> = root.into_iter().flat_map(|c| c.steps).collect();
753 for chapter in others.into_iter().rev() {
757 let mut placing = None;
758 for_each_step_mut(&mut steps, &mut |step| {
759 if placing.is_none() && step.places(&chapter.assembly) {
760 placing = Some(step.id.clone());
761 }
762 });
763 let chapter_steps = chapter.steps;
764 match placing {
765 Some(id) => {
766 for_each_step_mut(&mut steps, &mut |step| {
767 if step.id == id {
768 step.steps = chapter_steps.clone();
769 }
770 });
771 }
772 None => steps.insert(0, Step { id: chapter.id, title: chapter.title, steps: chapter_steps, ..Step::default() }),
773 }
774 }
775 object.insert("schema".into(), Value::from(SCHEMA));
776 object.insert("steps".into(), serde_json::to_value(steps).map_err(|e| format!("instructions block: {e}"))?);
777 Ok(Value::Object(object))
778}
779
780#[derive(Debug, Clone, PartialEq, Serialize)]
782#[serde(rename_all = "camelCase")]
783pub struct PartsRow {
784 pub part: String,
785 pub name: String,
787 pub find_number: String,
788 pub quantity: usize,
789 pub subassembly: bool,
790 pub first_step: String,
791}
792