kicad_monkey_fab/
tabular.rs1use crate::FabViewData;
4use crate::geom::LayerSide;
5use std::collections::BTreeMap;
6use std::fmt::Write as _;
7
8#[must_use]
10pub fn write_pnp_csv(view: &FabViewData, use_aux_origin: bool) -> String {
11 let (ox, oy) = if use_aux_origin {
12 (view.aux_origin.x, view.aux_origin.y)
13 } else {
14 (0, 0)
15 };
16 let mut rows: Vec<_> = view
17 .components
18 .iter()
19 .filter(|c| c.fitted && !c.exclude_from_pos && !c.board_only)
20 .collect();
21 rows.sort_by(|a, b| natural_cmp(&a.designator, &b.designator));
22
23 let mut out = String::with_capacity(rows.len() * 64 + 64);
24 out.push_str("Designator,Val,Package,Mid X,Mid Y,Rotation,Layer\n");
25 for comp in rows {
26 let layer = if comp.side == LayerSide::Bottom {
27 "bottom"
28 } else {
29 "top"
30 };
31 let _ = writeln!(
32 out,
33 "{},{},{},{:.4},{:.4},{:.2},{layer}",
34 csv_escape(&comp.designator),
35 csv_escape(&comp.value),
36 csv_escape(&comp.footprint),
37 (comp.center.x - ox) as f64 / 1e6,
38 (comp.center.y - oy) as f64 / 1e6,
39 comp.rotation_deg.rem_euclid(360.0),
40 );
41 }
42 out
43}
44
45#[must_use]
47pub fn write_bom_csv(view: &FabViewData) -> String {
48 let mut groups: BTreeMap<(String, String, String), Vec<String>> = BTreeMap::new();
49 for comp in &view.components {
50 if !comp.fitted || comp.exclude_from_bom || comp.board_only {
51 continue;
52 }
53 groups
54 .entry((
55 comp.value.clone(),
56 comp.footprint.clone(),
57 comp.description.clone(),
58 ))
59 .or_default()
60 .push(comp.designator.clone());
61 }
62
63 let mut ordered: Vec<_> = groups
64 .into_iter()
65 .map(|(key, mut des)| {
66 des.sort_by(|a, b| natural_cmp(a, b));
67 (key, des)
68 })
69 .collect();
70 ordered.sort_by(|a, b| {
71 let a_first = a.1.first().map(String::as_str).unwrap_or("");
72 let b_first = b.1.first().map(String::as_str).unwrap_or("");
73 natural_cmp(a_first, b_first)
74 });
75
76 let mut out = String::with_capacity(ordered.len() * 80 + 64);
77 out.push_str("Item,Quantity,Designators,Value,Footprint,Description\n");
78 for (idx, ((val, fp, desc), des)) in ordered.into_iter().enumerate() {
79 let joined = des.join(" ");
80 let _ = writeln!(
81 out,
82 "{},{},{},{},{},{}",
83 idx + 1,
84 des.len(),
85 csv_escape(&joined),
86 csv_escape(&val),
87 csv_escape(&fp),
88 csv_escape(&desc),
89 );
90 }
91 out
92}
93
94fn csv_escape(value: &str) -> String {
95 if value.contains([',', '"', '\n', '\r']) {
96 format!("\"{}\"", value.replace('"', "\"\""))
97 } else {
98 value.to_owned()
99 }
100}
101
102fn natural_cmp(a: &str, b: &str) -> std::cmp::Ordering {
103 let (ap, an) = split_prefix_num(a);
104 let (bp, bn) = split_prefix_num(b);
105 ap.cmp(bp).then_with(|| an.cmp(&bn)).then_with(|| a.cmp(b))
106}
107
108fn split_prefix_num(s: &str) -> (&str, Option<u64>) {
109 let split = s.find(|c: char| c.is_ascii_digit()).unwrap_or(s.len());
110 let num = s[split..].parse::<u64>().ok();
111 (&s[..split], num)
112}