Skip to main content

brep_instructions/
layout.rs

1//! Printed pages from the document's template: a cover, the parts list, the
2//! tools list, then the steps at 1, 2 or 4 per page, portrait or landscape.
3//!
4//! Everything is in paper millimetres from the page's top-left corner. The
5//! layout only says WHERE each thing goes; the renderer draws the step's view
6//! into a slot's `picture` and its text into `text`.
7//!
8//! A step's Record block ([`crate::record`]: its fields as a paper form, a
9//! serial line per serial-tracked unit, the sign-off lines) goes under the
10//! step's text. Its height is known here, measured through a
11//! [`TextMeasure`], so the paging accounts for it: a step with a block may
12//! take more of a tall cell from its picture (down to [`PICTURE_MIN_SHARE`]
13//! of the cell and [`PICTURE_MIN_MM`]),
14//! and what still does not fit continues on Record pages right after the
15//! steps page, never over the picture and never cut off. A document whose
16//! steps record nothing and need no sign-off lays out exactly as before.
17
18use crate::model::{Instructions, Orientation, Step};
19use crate::record::{self, Item};
20use serde::Serialize;
21
22/// Body text's cap height, in millimetres.
23pub const BODY_MM: f64 = 2.8;
24/// A heading's cap height.
25pub const HEADING_MM: f64 = 4.2;
26/// Line pitch over cap height.
27pub const LEADING: f64 = 1.75;
28/// The inset of a step's text inside its text area.
29pub const TEXT_INSET_MM: f64 = 3.0;
30/// The share of a tall cell the text area takes.
31pub const TEXT_SHARE: f64 = 0.3;
32/// What the picture of a step with a Record block keeps when the text area
33/// grows into it: this share of the cell's height, and never less than
34/// [`PICTURE_MIN_MM`] (a picture smaller than that says little).
35pub const PICTURE_MIN_SHARE: f64 = 0.3;
36pub const PICTURE_MIN_MM: f64 = 60.0;
37/// The widest a Record page's column is: a line longer than this is hard
38/// to write along.
39pub const RECORD_COLUMN_MM: f64 = 180.0;
40
41/// How wide a run of text is on paper: the renderer's font metrics, so the
42/// layout and the drawing agree.
43pub trait TextMeasure {
44    /// The width in millimetres of `text` at cap height `cap`.
45    fn width_mm(&self, text: &str, cap: f64) -> f64;
46}
47
48/// A measure for a caller without font metrics (a page count on a server, a
49/// test): every character half an em wide, the em 1.39 cap heights. Close
50/// to a sans-serif's average; a renderer passes its own.
51pub struct Estimate;
52
53impl TextMeasure for Estimate {
54    fn width_mm(&self, text: &str, cap: f64) -> f64 {
55        text.chars().count() as f64 * 0.5 * cap * 1.39
56    }
57}
58
59/// `text` broken into lines no wider than `width` at cap height `cap`, at
60/// spaces; a word wider than the line stands alone on one.
61pub fn wrap(text: &str, width: f64, cap: f64, m: &dyn TextMeasure) -> Vec<String> {
62    let mut lines = Vec::new();
63    for paragraph in text.lines() {
64        let mut line = String::new();
65        for word in paragraph.split_whitespace() {
66            let candidate = if line.is_empty() { word.to_string() } else { format!("{line} {word}") };
67            if !line.is_empty() && m.width_mm(&candidate, cap) > width {
68                lines.push(std::mem::replace(&mut line, word.to_string()));
69            } else {
70                line = candidate;
71            }
72        }
73        lines.push(line);
74    }
75    lines
76}
77
78/// One line of a step's text column.
79#[derive(Debug, Clone, PartialEq)]
80pub enum TextLine {
81    /// A run at cap height `cap`, `indent` millimetres in.
82    Text { text: String, cap: f64, indent: f64 },
83    /// A little space between two groups of lines.
84    Gap,
85}
86
87impl TextLine {
88    pub fn height(&self) -> f64 {
89        match self {
90            TextLine::Text { cap, .. } => cap * LEADING,
91            TextLine::Gap => BODY_MM * 0.6,
92        }
93    }
94}
95
96/// What a step's text area says, top to bottom, wrapped to `width`: its
97/// number and title, the parts it adds, its tools and torque, its callouts
98/// and its notes.
99pub fn step_text(step: &Step, number: usize, width: f64, m: &dyn TextMeasure) -> Vec<TextLine> {
100    let mut out = Vec::new();
101    let wrapped = |out: &mut Vec<TextLine>, text: &str, cap: f64, indent: f64| {
102        out.extend(wrap(text, width - indent, cap, m).into_iter().map(|text| TextLine::Text { text, cap, indent }));
103    };
104    out.push(TextLine::Text { text: format!("Step {number}"), cap: HEADING_MM, indent: 0.0 });
105    if !step.title.is_empty() {
106        wrapped(&mut out, &step.title, BODY_MM * 1.15, 0.0);
107    }
108    out.push(TextLine::Gap);
109    if !step.adds.is_empty() {
110        out.push(TextLine::Text { text: "Parts".into(), cap: BODY_MM, indent: 0.0 });
111        for add in &step.adds {
112            let find = if add.find_number.is_empty() { String::new() } else { format!("({}) ", add.find_number) };
113            wrapped(&mut out, &format!("{find}{} \u{d7} {}", add.quantity(), add.display_name()), BODY_MM, 3.0);
114        }
115        out.push(TextLine::Gap);
116    }
117    if !step.tools.is_empty() {
118        out.push(TextLine::Text { text: "Tools".into(), cap: BODY_MM, indent: 0.0 });
119        for tool in &step.tools {
120            let text = if tool.spec.is_empty() { tool.name.clone() } else { format!("{} \u{2014} {}", tool.name, tool.spec) };
121            wrapped(&mut out, &text, BODY_MM, 3.0);
122        }
123        out.push(TextLine::Gap);
124    }
125    if let Some(torque) = &step.torque {
126        wrapped(&mut out, &format!("Torque: {}", torque.text()), BODY_MM, 0.0);
127        out.push(TextLine::Gap);
128    }
129    for callout in &step.callouts {
130        wrapped(&mut out, &format!("{}: {}", callout.kind.label().to_uppercase(), callout.text), BODY_MM, 0.0);
131    }
132    if !step.callouts.is_empty() {
133        out.push(TextLine::Gap);
134    }
135    if !step.notes.is_empty() {
136        wrapped(&mut out, &step.notes, BODY_MM, 0.0);
137    }
138    out
139}
140
141/// The height of [`step_text`]: trailing space not counted.
142pub fn step_text_height(step: &Step, number: usize, width: f64, m: &dyn TextMeasure) -> f64 {
143    let lines = step_text(step, number, width, m);
144    let end = lines.iter().rposition(|line| matches!(line, TextLine::Text { .. })).map_or(0, |i| i + 1);
145    lines[..end].iter().map(TextLine::height).sum()
146}
147
148/// Paper sizes in millimetres, landscape (the same keys and sizes as drawing
149/// sheets; portrait swaps them).
150pub const PAPER_SIZES: &[(&str, f64, f64)] = &[
151    ("A4", 297.0, 210.0),
152    ("A3", 420.0, 297.0),
153    ("A2", 594.0, 420.0),
154    ("A1", 841.0, 594.0),
155    ("A0", 1189.0, 841.0),
156    ("Letter", 279.4, 215.9),
157    ("Tabloid", 431.8, 279.4),
158];
159
160pub const MARGIN_MM: f64 = 12.0;
161/// The band at the top of every page: document title and page number.
162pub const HEADER_MM: f64 = 12.0;
163pub const GUTTER_MM: f64 = 6.0;
164pub const PARTS_ROW_MM: f64 = 12.0;
165pub const TOOLS_ROW_MM: f64 = 16.0;
166
167#[derive(Debug, Clone, Copy, PartialEq, Serialize)]
168pub struct Rect {
169    pub x: f64,
170    pub y: f64,
171    pub w: f64,
172    pub h: f64,
173}
174
175impl Rect {
176    pub fn contains(&self, other: &Rect) -> bool {
177        const E: f64 = 1e-9;
178        other.x >= self.x - E && other.y >= self.y - E && other.x + other.w <= self.x + self.w + E && other.y + other.h <= self.y + self.h + E
179    }
180
181    pub fn overlaps(&self, other: &Rect) -> bool {
182        const E: f64 = 1e-9;
183        self.x + E < other.x + other.w && other.x + E < self.x + self.w && self.y + E < other.y + other.h && other.y + E < self.y + self.h
184    }
185}
186
187#[derive(Debug, Clone, PartialEq, Serialize)]
188#[serde(tag = "kind", rename_all = "camelCase")]
189pub enum PageKind {
190    Cover,
191    /// Rows `first .. first + count` of the parts list.
192    PartsList { first: usize, count: usize },
193    /// Rows `first .. first + count` of the tools list.
194    ToolsList { first: usize, count: usize },
195    Steps,
196    /// Record blocks carried over from the steps page before it: the rows
197    /// are the page's `records`.
198    Record,
199}
200
201/// One band of a step's Record block, placed: the item it belongs to, which
202/// of the item's bands it is, and where it goes. The renderer draws
203/// [`record::bands`] of the item at `rect.w` and takes band `band`.
204#[derive(Debug, Clone, PartialEq, Serialize)]
205#[serde(rename_all = "camelCase")]
206pub struct RecordRow {
207    pub step_id: String,
208    pub step_number: usize,
209    #[serde(flatten)]
210    pub item: Item,
211    pub band: usize,
212    /// The heading of a block carried over to a Record page (it names its
213    /// step).
214    #[serde(skip_serializing_if = "std::ops::Not::not")]
215    pub continued: bool,
216    pub rect: Rect,
217}
218
219/// One step's place on a page.
220#[derive(Debug, Clone, PartialEq, Serialize)]
221#[serde(rename_all = "camelCase")]
222pub struct Slot {
223    pub step_id: String,
224    pub step_number: usize,
225    pub rect: Rect,
226    /// Where the step's view is drawn.
227    pub picture: Rect,
228    /// Where the step's number, parts, tools, torque, callouts and notes go.
229    pub text: Rect,
230    /// The bands of the step's Record block that fit under its text, placed
231    /// inside `text`; the rest are on the Record page(s) that follow.
232    #[serde(skip_serializing_if = "Vec::is_empty")]
233    pub record: Vec<RecordRow>,
234}
235
236#[derive(Debug, Clone, PartialEq, Serialize)]
237#[serde(rename_all = "camelCase")]
238pub struct Page {
239    /// 1-based.
240    pub number: usize,
241    pub width_mm: f64,
242    pub height_mm: f64,
243    #[serde(flatten)]
244    pub kind: PageKind,
245    /// The area below the header and inside the margins.
246    pub content: Rect,
247    #[serde(skip_serializing_if = "Vec::is_empty")]
248    pub slots: Vec<Slot>,
249    /// A Record page's rows.
250    #[serde(skip_serializing_if = "Vec::is_empty")]
251    pub records: Vec<RecordRow>,
252}
253
254/// A paper key's millimetres in `orientation`.
255pub fn paper_mm(paper: &str, orientation: Orientation) -> Result<(f64, f64), String> {
256    let &(_, w, h) = PAPER_SIZES
257        .iter()
258        .find(|(key, _, _)| key.eq_ignore_ascii_case(paper))
259        .ok_or_else(|| format!("unknown paper size '{paper}'"))?;
260    Ok(match orientation {
261        Orientation::Landscape => (w, h),
262        Orientation::Portrait => (h, w),
263    })
264}
265
266/// The block's pages, in print order, measured with [`Estimate`]: for a
267/// caller without font metrics. A renderer calls [`pages_with`] with its own
268/// measure, so its pages are the ones it draws.
269pub fn pages(block: &Instructions) -> Result<Vec<Page>, String> {
270    pages_with(block, &Estimate)
271}
272
273/// The block's pages, in print order, text measured by `m`.
274pub fn pages_with(block: &Instructions, m: &dyn TextMeasure) -> Result<Vec<Page>, String> {
275    let template = &block.template;
276    if !crate::model::STEPS_PER_PAGE.contains(&template.steps_per_page) {
277        return Err(format!("steps per page must be 1, 2 or 4, not {}", template.steps_per_page));
278    }
279    let (width, height) = paper_mm(&template.paper, template.orientation)?;
280    let content = Rect {
281        x: MARGIN_MM,
282        y: MARGIN_MM + HEADER_MM,
283        w: width - 2.0 * MARGIN_MM,
284        h: height - 2.0 * MARGIN_MM - HEADER_MM,
285    };
286    let mut pages = Vec::new();
287    let push = |kind: PageKind, slots: Vec<Slot>, pages: &mut Vec<Page>| {
288        let number = pages.len() + 1;
289        pages.push(Page { number, width_mm: width, height_mm: height, kind, content, slots, records: Vec::new() });
290    };
291    push(PageKind::Cover, Vec::new(), &mut pages);
292    if block.front.parts_list {
293        let rows = block.parts_list().len();
294        for (first, count) in chunks(rows, rows_per_page(content.h, PARTS_ROW_MM)) {
295            push(PageKind::PartsList { first, count }, Vec::new(), &mut pages);
296        }
297    }
298    if block.front.tools_list {
299        let rows = block.tools_list().len();
300        if rows > 0 {
301            for (first, count) in chunks(rows, rows_per_page(content.h, TOOLS_ROW_MM)) {
302                push(PageKind::ToolsList { first, count }, Vec::new(), &mut pages);
303            }
304        }
305    }
306    let cells = grid(content, template.steps_per_page, template.orientation);
307    let steps: Vec<&Step> = block.steps().map(|(_, s)| s).collect();
308    for (page_index, chunk) in steps.chunks(cells.len()).enumerate() {
309        // What did not fit under a step's text: the step, its number and the
310        // items left, in order.
311        let mut carried: Vec<(&Step, usize, Vec<Item>)> = Vec::new();
312        let slots = chunk
313            .iter()
314            .zip(&cells)
315            .enumerate()
316            .map(|(i, (step, cell))| {
317                let step_number = page_index * cells.len() + i + 1;
318                let items = record::items(step);
319                let (picture, text) = if items.is_empty() { split_cell(*cell) } else { split_cell_for(*cell, step, step_number, &items, m) };
320                let (rows, left) = place_record(step, step_number, &items, text, m);
321                if !left.is_empty() {
322                    carried.push((step, step_number, left));
323                }
324                Slot { step_id: step.id.clone(), step_number, rect: *cell, picture, text, record: rows }
325            })
326            .collect();
327        push(PageKind::Steps, slots, &mut pages);
328        for records in record_pages(&carried, content, m) {
329            push(PageKind::Record, Vec::new(), &mut pages);
330            pages.last_mut().expect("just pushed").records = records;
331        }
332    }
333    Ok(pages)
334}
335
336/// A cell's picture and text areas for a step with a Record block: in a
337/// tall cell (text below the picture) the text area grows from its usual
338/// share to what the step's text and block need, while the picture keeps
339/// [`PICTURE_MIN_SHARE`] of the cell and at least [`PICTURE_MIN_MM`]. A wide
340/// cell's text column already runs the cell's height.
341fn split_cell_for(cell: Rect, step: &Step, number: usize, items: &[Item], m: &dyn TextMeasure) -> (Rect, Rect) {
342    if cell.w > 1.3 * cell.h {
343        return split_cell(cell);
344    }
345    let width = cell.w - 2.0 * TEXT_INSET_MM;
346    let block: f64 = items.iter().flat_map(|item| record::bands(step, number, item, width, false, m)).map(|band| band.h).sum();
347    let needed = step_text_height(step, number, width, m) + RECORD_GAP_MM + block + 2.0 * TEXT_INSET_MM;
348    let usual = cell.h * TEXT_SHARE;
349    let most = (cell.h - GUTTER_MM / 2.0 - (cell.h * PICTURE_MIN_SHARE).max(PICTURE_MIN_MM)).max(usual);
350    let text_h = needed.clamp(usual, most);
351    let picture = Rect { x: cell.x, y: cell.y, w: cell.w, h: cell.h - text_h - GUTTER_MM / 2.0 };
352    let text = Rect { x: cell.x, y: cell.y + cell.h - text_h, w: cell.w, h: text_h };
353    (picture, text)
354}
355
356/// The space between a step's text and its Record block.
357const RECORD_GAP_MM: f64 = 2.0;
358
359/// Place the step's Record block under its text inside the text area: whole
360/// items, in order, while they fit (the heading only with the item after
361/// it). Returns the placed rows and the items left for a Record page.
362fn place_record(step: &Step, number: usize, items: &[Item], text: Rect, m: &dyn TextMeasure) -> (Vec<RecordRow>, Vec<Item>) {
363    if items.is_empty() {
364        return (Vec::new(), Vec::new());
365    }
366    let area = Rect { x: text.x + TEXT_INSET_MM, y: text.y + TEXT_INSET_MM, w: text.w - 2.0 * TEXT_INSET_MM, h: text.h - 2.0 * TEXT_INSET_MM };
367    let bottom = area.y + area.h + 1e-9;
368    let mut y = area.y + step_text_height(step, number, area.w, m) + RECORD_GAP_MM;
369    let heights = |item: &Item| -> Vec<f64> { record::bands(step, number, item, area.w, false, m).iter().map(|band| band.h).collect() };
370    let mut rows = Vec::new();
371    for (i, item) in items.iter().enumerate() {
372        let own = heights(item);
373        let mut needed: f64 = own.iter().sum();
374        if *item == Item::Heading {
375            needed += items.get(i + 1).map_or(0.0, |next| heights(next).iter().sum());
376        }
377        if y + needed > bottom {
378            return (rows, items[i..].to_vec());
379        }
380        for (band, h) in own.into_iter().enumerate() {
381            rows.push(RecordRow { step_id: step.id.clone(), step_number: number, item: *item, band, continued: false, rect: Rect { x: area.x, y, w: area.w, h } });
382            y += h;
383        }
384    }
385    (rows, Vec::new())
386}
387
388/// The Record pages after a steps page: each carried step's heading (naming
389/// the step) and the bands of its remaining items, flowing down one column
390/// and onto as many pages as they need. A heading stays with the band after
391/// it; a band taller than a page still gets a page of its own.
392fn record_pages(carried: &[(&Step, usize, Vec<Item>)], content: Rect, m: &dyn TextMeasure) -> Vec<Vec<RecordRow>> {
393    let width = content.w.min(RECORD_COLUMN_MM);
394    let bottom = content.y + content.h + 1e-9;
395    let mut pages: Vec<Vec<RecordRow>> = Vec::new();
396    let mut y = content.y;
397    for (step, number, items) in carried {
398        // The bands in order, the block's own heading replaced by the
399        // carried one.
400        let mut bands: Vec<(Item, usize, bool, f64)> = Vec::new();
401        for (band, b) in record::bands(step, *number, &Item::Heading, width, true, m).iter().enumerate() {
402            bands.push((Item::Heading, band, true, b.h));
403        }
404        for item in items.iter().filter(|item| **item != Item::Heading) {
405            for (band, b) in record::bands(step, *number, item, width, false, m).iter().enumerate() {
406                bands.push((*item, band, false, b.h));
407            }
408        }
409        if !pages.is_empty() {
410            y += 4.0;
411        }
412        for (i, (item, band, continued, h)) in bands.iter().enumerate() {
413            let with_next = if *continued { bands.get(i + 1).map_or(0.0, |next| next.3) } else { 0.0 };
414            if pages.is_empty() || (y + h + with_next > bottom && y > content.y + 1e-9) {
415                pages.push(Vec::new());
416                y = content.y;
417            }
418            pages.last_mut().expect("a page was just opened").push(RecordRow {
419                step_id: step.id.clone(),
420                step_number: *number,
421                item: *item,
422                band: *band,
423                continued: *continued,
424                rect: Rect { x: content.x, y, w: width, h: *h },
425            });
426            y += h;
427        }
428    }
429    pages
430}
431
432/// Rows a list page holds: the content height in rows, less one for the
433/// column headings, at least one.
434fn rows_per_page(content_h: f64, row_mm: f64) -> usize {
435    ((content_h / row_mm).floor() as usize).saturating_sub(1).max(1)
436}
437
438/// `(first, count)` chunks of `rows`; one empty chunk for no rows, so the
439/// list still prints its headings.
440fn chunks(rows: usize, per_page: usize) -> Vec<(usize, usize)> {
441    if rows == 0 {
442        return vec![(0, 0)];
443    }
444    (0..rows).step_by(per_page).map(|first| (first, per_page.min(rows - first))).collect()
445}
446
447/// The step cells of a page: 1 fills it; 2 stack (portrait) or sit side by
448/// side (landscape); 4 make a 2 × 2 grid. Reading order: left to right, top
449/// to bottom.
450fn grid(content: Rect, per_page: u8, orientation: Orientation) -> Vec<Rect> {
451    let (columns, rows) = match (per_page, orientation) {
452        (1, _) => (1, 1),
453        (2, Orientation::Portrait) => (1, 2),
454        (2, Orientation::Landscape) => (2, 1),
455        _ => (2, 2),
456    };
457    let w = (content.w - GUTTER_MM * (columns - 1) as f64) / columns as f64;
458    let h = (content.h - GUTTER_MM * (rows - 1) as f64) / rows as f64;
459    let mut cells = Vec::new();
460    for r in 0..rows {
461        for c in 0..columns {
462            cells.push(Rect { x: content.x + c as f64 * (w + GUTTER_MM), y: content.y + r as f64 * (h + GUTTER_MM), w, h });
463        }
464    }
465    cells
466}
467
468/// A cell's picture and text areas: text on the right of a wide cell, below
469/// a tall one.
470fn split_cell(cell: Rect) -> (Rect, Rect) {
471    if cell.w > 1.3 * cell.h {
472        let text_w = (cell.w * 0.34).max(40.0f64.min(cell.w * 0.5));
473        let picture = Rect { x: cell.x, y: cell.y, w: cell.w - text_w - GUTTER_MM / 2.0, h: cell.h };
474        let text = Rect { x: cell.x + cell.w - text_w, y: cell.y, w: text_w, h: cell.h };
475        (picture, text)
476    } else {
477        let text_h = cell.h * TEXT_SHARE;
478        let picture = Rect { x: cell.x, y: cell.y, w: cell.w, h: cell.h - text_h - GUTTER_MM / 2.0 };
479        let text = Rect { x: cell.x, y: cell.y + cell.h - text_h, w: cell.w, h: text_h };
480        (picture, text)
481    }
482}
483