Skip to main content

brep_instructions/
record.rs

1//! The printed pages' Record block: a step's fields as a paper form.
2//!
3//! What the players show as inputs, the paper shows as places to write: an
4//! empty box to tick, a choice's options each as its own box to mark (a
5//! dropdown cannot be opened on paper), ruled lines for text, a ruled line
6//! with its unit and limits for a measurement, and a ruled line per serial
7//! number — the step's own fields and one line per unit of each
8//! serial-tracked part it adds. A step that needs a sign-off ends with a
9//! Signed and a Date line.
10//!
11//! The block is a list of [`Item`]s, each drawn as one or more [`Band`]s:
12//! full-width strips stacked down the page, the unit the page layout flows
13//! (a band is never split; an item may continue on the next page between
14//! two bands). A band is made of [`Mark`]s in millimetres from its own
15//! top-left corner: text runs and strokes. Boxes and rules are strokes the
16//! sheet writers draw as vector lines, never characters of a font.
17//!
18//! Everything here is measured through a [`TextMeasure`], so the layout that
19//! pages the bands and the renderer that draws them agree to the millimetre.
20
21use crate::fields::{FieldKind, StepField};
22use crate::layout::{wrap, TextMeasure, BODY_MM, LEADING};
23use crate::model::Step;
24use serde::Serialize;
25
26/// Small print's cap height: a hint, a measurement's limits, "(mark one)".
27pub const SMALL_MM: f64 = 2.2;
28/// A box to tick: its side.
29pub const BOX_MM: f64 = 3.4;
30/// The pitch of a line to write on by hand.
31pub const WRITE_MM: f64 = 8.0;
32/// The shortest ruled line worth writing on.
33const MIN_RULE_MM: f64 = 30.0;
34/// A measurement's ruled line.
35const NUMBER_RULE_MM: f64 = 26.0;
36
37/// One piece of a step's Record block.
38#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
39#[serde(tag = "item", rename_all = "camelCase")]
40pub enum Item {
41    /// The block's heading.
42    Heading,
43    /// The serial of one unit of a serial-tracked part the step adds: the
44    /// add's index and the unit's (its occurrence).
45    Serial { add: usize, unit: usize },
46    /// One of the step's fields, by index.
47    Field { index: usize },
48    /// The Signed and Date lines of a step that needs a sign-off.
49    Signoff,
50}
51
52/// One mark of a band, in millimetres from the band's top-left corner.
53#[derive(Debug, Clone, PartialEq)]
54pub enum Mark {
55    /// A run of text whose line box starts at `(x, y)`, `cap` its cap height.
56    Text { text: String, x: f64, y: f64, cap: f64 },
57    /// An empty square to tick or mark, its top-left corner at `(x, y)`.
58    Box { x: f64, y: f64, size: f64 },
59    /// A line to write on, from `x0` to `x1` at height `y`.
60    Rule { x0: f64, x1: f64, y: f64 },
61    /// Any other stroke: a write-in box's sides and top, the heading's rule.
62    Line(Vec<[f64; 2]>),
63}
64
65/// One full-width strip of the block.
66#[derive(Debug, Clone, PartialEq, Default)]
67pub struct Band {
68    pub h: f64,
69    pub marks: Vec<Mark>,
70}
71
72impl Band {
73    fn new(h: f64) -> Self {
74        Band { h, marks: Vec::new() }
75    }
76
77    fn text(mut self, text: impl Into<String>, x: f64, y: f64, cap: f64) -> Self {
78        self.marks.push(Mark::Text { text: text.into(), x, y, cap });
79        self
80    }
81
82    /// How many boxes to tick the band draws.
83    pub fn boxes(&self) -> usize {
84        self.marks.iter().filter(|m| matches!(m, Mark::Box { .. })).count()
85    }
86
87    /// How many lines to write on the band draws.
88    pub fn rules(&self) -> usize {
89        self.marks.iter().filter(|m| matches!(m, Mark::Rule { .. })).count()
90    }
91
92    /// The band's text runs, in drawing order.
93    pub fn texts(&self) -> Vec<&str> {
94        self.marks.iter().filter_map(|m| if let Mark::Text { text, .. } = m { Some(text.as_str()) } else { None }).collect()
95    }
96}
97
98/// The Record block of `step`, in print order: the heading, a serial line per
99/// unit of each serial-tracked add, the fields, then the sign-off lines.
100/// Empty for a step that records nothing and needs no sign-off; a step that
101/// only needs a sign-off gets its Signed line alone, without a heading.
102pub fn items(step: &Step) -> Vec<Item> {
103    let mut out = Vec::new();
104    for (add, part) in step.adds.iter().enumerate() {
105        if part.serial_tracked {
106            out.extend((0..part.occurrences.len()).map(|unit| Item::Serial { add, unit }));
107        }
108    }
109    out.extend((0..step.fields.len()).map(|index| Item::Field { index }));
110    if !out.is_empty() {
111        out.insert(0, Item::Heading);
112    }
113    if step.signoff.required {
114        out.push(Item::Signoff);
115    }
116    out
117}
118
119const PITCH: f64 = BODY_MM * LEADING;
120
121/// A label over (or before) one line to write on: on one band when the
122/// label leaves room for a line worth writing on, else the label's lines and
123/// then a full-width line.
124fn write_line(label: &str, width: f64, m: &dyn TextMeasure) -> Vec<Band> {
125    let w = m.width_mm(label, BODY_MM);
126    let baseline = WRITE_MM - 1.2;
127    if w + 3.0 + MIN_RULE_MM <= width {
128        let mut band = Band::new(WRITE_MM).text(label, 0.0, baseline - BODY_MM - 0.6, BODY_MM);
129        band.marks.push(Mark::Rule { x0: w + 3.0, x1: width, y: baseline });
130        return vec![band];
131    }
132    let mut bands: Vec<Band> = wrap(label, width, BODY_MM, m).into_iter().map(|line| Band::new(PITCH).text(line, 0.0, (PITCH - BODY_MM) / 2.0, BODY_MM)).collect();
133    let mut rule = Band::new(WRITE_MM);
134    rule.marks.push(Mark::Rule { x0: 0.0, x1: width, y: baseline });
135    bands.push(rule);
136    bands
137}
138
139fn label_bands(text: &str, width: f64, m: &dyn TextMeasure) -> Vec<Band> {
140    wrap(text, width, BODY_MM, m).into_iter().map(|line| Band::new(PITCH).text(line, 0.0, (PITCH - BODY_MM) / 2.0, BODY_MM)).collect()
141}
142
143fn field_bands(field: &StepField, width: f64, m: &dyn TextMeasure) -> Vec<Band> {
144    let star = if field.required { " *" } else { "" };
145    let name = if field.label.trim().is_empty() { "Field" } else { field.label.trim() };
146    let label = format!("{name}{star}");
147    let mut bands = match &field.kind {
148        FieldKind::Check => {
149            let h = PITCH.max(BOX_MM + 1.6);
150            wrap(&label, width - BOX_MM - 2.0, BODY_MM, m)
151                .into_iter()
152                .enumerate()
153                .map(|(i, line)| {
154                    let mut band = Band::new(h).text(line, BOX_MM + 2.0, (h - BODY_MM) / 2.0, BODY_MM);
155                    if i == 0 {
156                        band.marks.insert(0, Mark::Box { x: 0.0, y: (h - BOX_MM) / 2.0, size: BOX_MM });
157                    }
158                    band
159                })
160                .collect()
161        }
162        FieldKind::Choice { multiple, other, .. } => {
163            let how = if *multiple { "(mark all that apply)" } else { "(mark one)" };
164            let mut bands = label_bands(&format!("{label} {how}"), width, m);
165            // Every option is its own box, flowing left to right and
166            // wrapping; an option too long for a line wraps under its box.
167            let h = PITCH.max(BOX_MM + 2.4);
168            let (gap, after) = (1.5, 5.0);
169            let mut row = Band::new(h);
170            let mut x = 0.0;
171            let flush = |row: &mut Band, x: &mut f64, bands: &mut Vec<Band>| {
172                if !row.marks.is_empty() {
173                    bands.push(std::mem::replace(row, Band::new(h)));
174                }
175                *x = 0.0;
176            };
177            for option in field.options() {
178                let w = m.width_mm(option, BODY_MM);
179                if BOX_MM + gap + w > width {
180                    flush(&mut row, &mut x, &mut bands);
181                    for (i, line) in wrap(option, width - BOX_MM - gap, BODY_MM, m).into_iter().enumerate() {
182                        let mut band = Band::new(h).text(line, BOX_MM + gap, (h - BODY_MM) / 2.0, BODY_MM);
183                        if i == 0 {
184                            band.marks.insert(0, Mark::Box { x: 0.0, y: (h - BOX_MM) / 2.0, size: BOX_MM });
185                        }
186                        bands.push(band);
187                    }
188                    continue;
189                }
190                if x > 0.0 && x + BOX_MM + gap + w > width {
191                    flush(&mut row, &mut x, &mut bands);
192                }
193                row.marks.push(Mark::Box { x, y: (h - BOX_MM) / 2.0, size: BOX_MM });
194                row.marks.push(Mark::Text { text: option.to_string(), x: x + BOX_MM + gap, y: (h - BODY_MM) / 2.0, cap: BODY_MM });
195                x += BOX_MM + gap + w + after;
196            }
197            if *other {
198                let text = "Other:";
199                let w = m.width_mm(text, BODY_MM);
200                if x > 0.0 && x + BOX_MM + gap + w + 2.0 + MIN_RULE_MM > width {
201                    flush(&mut row, &mut x, &mut bands);
202                }
203                row.marks.push(Mark::Box { x, y: (h - BOX_MM) / 2.0, size: BOX_MM });
204                row.marks.push(Mark::Text { text: text.into(), x: x + BOX_MM + gap, y: (h - BODY_MM) / 2.0, cap: BODY_MM });
205                row.marks.push(Mark::Rule { x0: x + BOX_MM + gap + w + 2.0, x1: width, y: h - 1.0 });
206            }
207            flush(&mut row, &mut x, &mut bands);
208            bands
209        }
210        FieldKind::Text { lines } if *lines > 1 => {
211            // A ruled box: `lines` lines to write on, framed.
212            let mut bands = label_bands(&label, width, m);
213            for i in 0..*lines {
214                let mut band = Band::new(WRITE_MM);
215                if i == 0 {
216                    band.marks.push(Mark::Line(vec![[0.0, 0.0], [width, 0.0]]));
217                }
218                band.marks.push(Mark::Line(vec![[0.0, 0.0], [0.0, WRITE_MM]]));
219                band.marks.push(Mark::Line(vec![[width, 0.0], [width, WRITE_MM]]));
220                band.marks.push(Mark::Rule { x0: 0.0, x1: width, y: WRITE_MM });
221                bands.push(band);
222            }
223            bands
224        }
225        FieldKind::Text { .. } | FieldKind::Serial => write_line(&label, width, m),
226        FieldKind::Number { .. } => {
227            // Label, a line for the value, the unit, and the nominal and
228            // limits in small print (on a line of their own when the first
229            // is full).
230            let unit = field.unit();
231            let limits = field.limits_text();
232            let label_w = m.width_mm(&label, BODY_MM);
233            let unit_w = if unit.is_empty() { 0.0 } else { m.width_mm(unit, BODY_MM) + 1.5 };
234            let baseline = WRITE_MM - 1.2;
235            let text_y = baseline - BODY_MM - 0.6;
236            let mut bands = Vec::new();
237            let mut band = Band::new(WRITE_MM);
238            let mut x = 0.0;
239            if label_w + 3.0 + NUMBER_RULE_MM + unit_w <= width {
240                band = band.text(label.as_str(), 0.0, text_y, BODY_MM);
241                x = label_w + 3.0;
242            } else {
243                bands.extend(label_bands(&label, width, m));
244            }
245            let rule_end = (x + NUMBER_RULE_MM).min(width - unit_w).max(x);
246            band.marks.push(Mark::Rule { x0: x, x1: rule_end, y: baseline });
247            x = rule_end;
248            if !unit.is_empty() {
249                band = band.text(unit, x + 1.5, text_y, BODY_MM);
250                x += unit_w;
251            }
252            if !limits.is_empty() {
253                let small = format!("({limits})");
254                let small_w = m.width_mm(&small, SMALL_MM);
255                if x + 3.0 + small_w <= width {
256                    band = band.text(small, x + 3.0, baseline - SMALL_MM - 0.6, SMALL_MM);
257                    bands.push(band);
258                } else {
259                    bands.push(band);
260                    for line in wrap(&small, width, SMALL_MM, m) {
261                        bands.push(Band::new(SMALL_MM * LEADING).text(line, 0.0, (SMALL_MM * LEADING - SMALL_MM) / 2.0, SMALL_MM));
262                    }
263                }
264            } else {
265                bands.push(band);
266            }
267            bands
268        }
269    };
270    let hint = field.hint.trim();
271    if !hint.is_empty() {
272        for line in wrap(hint, width, SMALL_MM, m) {
273            bands.push(Band::new(SMALL_MM * LEADING).text(line, 0.0, (SMALL_MM * LEADING - SMALL_MM) / 2.0, SMALL_MM));
274        }
275    }
276    // A little air before the next field.
277    if let Some(last) = bands.last_mut() {
278        last.h += 1.2;
279    }
280    bands
281}
282
283/// The bands of one item of `step`'s block (its `number` in reading order)
284/// in a column `width` wide. `continued`: the heading of a block carried
285/// over to a Record page, which names its step.
286pub fn bands(step: &Step, number: usize, item: &Item, width: f64, continued: bool, m: &dyn TextMeasure) -> Vec<Band> {
287    match item {
288        Item::Heading => {
289            let h = PITCH + 2.0;
290            let text = if continued { format!("Step {number} record (continued)") } else { "Record".to_string() };
291            let mut band = Band::new(h).text(text, 0.0, 0.6, BODY_MM);
292            band.marks.push(Mark::Line(vec![[0.0, h - 1.4], [width, h - 1.4]]));
293            vec![band]
294        }
295        Item::Serial { add, unit } => {
296            let Some(part) = step.adds.get(*add) else { return Vec::new() };
297            let which = if part.occurrences.len() > 1 { format!(" #{}", unit + 1) } else { String::new() };
298            let mut bands = write_line(&format!("Serial: {}{which} *", part.display_name()), width, m);
299            if let Some(last) = bands.last_mut() {
300                last.h += 1.2;
301            }
302            bands
303        }
304        Item::Field { index } => step.fields.get(*index).map(|field| field_bands(field, width, m)).unwrap_or_default(),
305        Item::Signoff => {
306            let h = WRITE_MM + 1.5;
307            let baseline = h - 1.2;
308            let text_y = baseline - BODY_MM - 0.6;
309            let signed_w = m.width_mm("Signed", BODY_MM);
310            let date_w = m.width_mm("Date", BODY_MM);
311            let free = (width - signed_w - date_w - 8.0).max(0.0);
312            let signed_end = signed_w + 2.0 + free * 0.62;
313            let mut band = Band::new(h).text("Signed", 0.0, text_y, BODY_MM).text("Date", signed_end + 4.0, text_y, BODY_MM);
314            band.marks.push(Mark::Rule { x0: signed_w + 2.0, x1: signed_end, y: baseline });
315            band.marks.push(Mark::Rule { x0: signed_end + 4.0 + date_w + 2.0, x1: width, y: baseline });
316            vec![band]
317        }
318    }
319}
320