1use crate::model::{Instructions, Orientation, Step};
19use crate::record::{self, Item};
20use serde::Serialize;
21
22pub const BODY_MM: f64 = 2.8;
24pub const HEADING_MM: f64 = 4.2;
26pub const LEADING: f64 = 1.75;
28pub const TEXT_INSET_MM: f64 = 3.0;
30pub const TEXT_SHARE: f64 = 0.3;
32pub const PICTURE_MIN_SHARE: f64 = 0.3;
36pub const PICTURE_MIN_MM: f64 = 60.0;
37pub const RECORD_COLUMN_MM: f64 = 180.0;
40
41pub trait TextMeasure {
44 fn width_mm(&self, text: &str, cap: f64) -> f64;
46}
47
48pub 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
59pub 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#[derive(Debug, Clone, PartialEq)]
80pub enum TextLine {
81 Text { text: String, cap: f64, indent: f64 },
83 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
96pub 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
141pub 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
148pub 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;
161pub 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 PartsList { first: usize, count: usize },
193 ToolsList { first: usize, count: usize },
195 Steps,
196 Record,
199}
200
201#[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 #[serde(skip_serializing_if = "std::ops::Not::not")]
215 pub continued: bool,
216 pub rect: Rect,
217}
218
219#[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 pub picture: Rect,
228 pub text: Rect,
230 #[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 pub number: usize,
241 pub width_mm: f64,
242 pub height_mm: f64,
243 #[serde(flatten)]
244 pub kind: PageKind,
245 pub content: Rect,
247 #[serde(skip_serializing_if = "Vec::is_empty")]
248 pub slots: Vec<Slot>,
249 #[serde(skip_serializing_if = "Vec::is_empty")]
251 pub records: Vec<RecordRow>,
252}
253
254pub 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
266pub fn pages(block: &Instructions) -> Result<Vec<Page>, String> {
270 pages_with(block, &Estimate)
271}
272
273pub 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 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
336fn 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
356const RECORD_GAP_MM: f64 = 2.0;
358
359fn 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
388fn 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 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
432fn 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
438fn 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
447fn 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
468fn 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