1use crate::analysis::{Band, bounds, record_cycle, utilisation, verdict_bands};
7use crate::{Sim, catalog, charts};
8use sim_core::{Config, ConfigError, MachineEntry, Translations};
9use std::collections::BTreeMap;
10use std::fmt::Write as _;
11
12pub fn check_key(check: &str, linear: bool) -> String {
15 if linear && check == "motor-speed" { "check-motor-speed-linear".into() } else { format!("check-{check}") }
16}
17
18pub fn check_labels(ids: &str, linear: bool, tr: &Translations) -> String {
21 let label = |id: &str| {
22 let key = check_key(id, linear);
23 if tr.has(&key) { tr.tr(&key).to_string() } else { id.to_string() }
24 };
25 let mut labels: Vec<String> = Vec::new();
26 for shown in ids.split(", ").map(label) {
27 if !labels.contains(&shown) {
28 labels.push(shown);
29 }
30 }
31 labels.join("; ")
32}
33
34#[derive(Debug, Clone, PartialEq)]
36pub enum Block {
37 Heading(String),
38 Text(String),
39 Table(Vec<String>, Vec<(Vec<String>, bool)>),
41 Plot(Plot),
42 SignOff(Vec<String>, Vec<String>),
44}
45
46#[derive(Debug, Clone, PartialEq)]
47pub struct Plot {
48 pub title: String,
49 pub x_label: String,
50 pub y_label: String,
51 pub series: Vec<(String, Vec<[f64; 2]>, bool)>,
53}
54
55#[derive(Debug, Clone, PartialEq)]
56pub struct Report {
57 pub title: String,
58 pub blocks: Vec<Block>,
59 pub passed: bool,
61}
62
63pub fn sources(text: &str) -> BTreeMap<String, String> {
70 let tags = |comment: &str| {
71 let lower = comment.to_lowercase();
72 let mut found: Vec<(usize, &str)> = ["catalogue", "estimate", "cad"]
73 .into_iter()
74 .filter_map(|t| lower.find(&format!("[{t}]")).map(|at| (at, t)))
75 .collect();
76 found.sort();
77 (!found.is_empty()).then(|| found.iter().map(|(_, t)| format!("[{t}]")).collect::<Vec<_>>().join(" / "))
78 };
79 let (mut out, mut table, mut table_tag) = (BTreeMap::new(), Some(String::new()), None);
80 let (mut block, mut current): (Option<Option<String>>, Option<String>) = (None, None);
82 for line in text.lines().map(str::trim) {
83 let (code, comment) = line.split_once('#').map_or((line, ""), |(code, comment)| (code.trim(), comment));
84 if line.is_empty() {
85 (block, current) = (None, None);
86 } else if code.is_empty() {
87 block = Some(tags(comment).or(block.flatten()));
89 } else if code.starts_with("[[") {
90 (table, block, current) = (None, None, None);
92 } else if let Some(name) = code.strip_prefix('[').and_then(|l| l.split(']').next()) {
93 (table, table_tag, block, current) =
94 (Some(name.trim().to_string()), tags(comment).or(block.flatten()), None, None);
95 } else if let (Some(table), Some((key, _))) = (&table, code.split_once('=')) {
96 if let Some(found) = block.take() {
97 current = found;
98 }
99 let key = key.trim().trim_matches('"');
100 let path = if table.is_empty() { key.to_string() } else { format!("{table}.{key}") };
101 if let Some(t) = tags(comment).or_else(|| current.clone()).or_else(|| table_tag.clone()) {
102 out.insert(path, t);
103 }
104 if current.as_deref() == Some("[cad]") {
105 current = None;
106 }
107 }
108 }
109 out
110}
111
112pub fn make(
117 entry: &MachineEntry,
118 text: &str,
119 source: &str,
120 named: &Config,
121 cfg: &Config,
122 bands: bool,
123 tr: &Translations,
124) -> Result<Report, ConfigError> {
125 let resolved = catalog::resolve(entry, cfg)?;
126 let sim = Sim::new(entry, &resolved)?;
127 let motors = sim.machine.motors().to_vec();
128 let signals = sim.signal_infos();
129 let judged = verdict_bands(entry, &resolved, &if bands { bounds(&resolved)? } else { Vec::new() })?;
130 let rows = record_cycle(entry, &resolved)?;
131 let t = |key: &str| tr.tr(key).to_string();
132 let motor_name =
133 |k: Option<usize>| k.map_or(String::new(), |k| format!("{} ({})", motors[k].id, tr.tr(motors[k].key)));
134 let failed = judged.iter().filter(|b| !(if bands { b.ok } else { b.verdict.ok })).count();
135 let passed = failed == 0;
136
137 let mut blocks = vec![Block::Heading(t("report-machine"))];
138 let summary = if passed {
139 tr.tr_arg("report-pass", &judged.len().to_string())
140 } else {
141 tr.tr_arg("report-fail", &format!("{failed} / {}", judged.len()))
142 };
143 let duration =
145 rows.last().map_or(0.0, |r| r[0] + if rows.len() > 1 { r[0] - rows[rows.len() - 2][0] } else { 0.0 });
146 let facts = [
147 ("report-machine-name", tr.tr(entry.key).to_string()),
148 ("report-config", source.to_string()),
149 ("report-date", today()),
150 ("report-version", env!("CARGO_PKG_VERSION").to_string()),
151 ("report-cycle-time", format!("{duration:.3} s")),
152 ("report-result", summary),
153 ];
154 blocks.push(Block::Table(
155 vec![t("report-item"), t("report-value")],
156 facts.into_iter().map(|(k, v)| (vec![t(k), v], false)).collect(),
157 ));
158 let source_of = provenance(entry, text, named, &resolved, tr)?;
159 let parts =
161 named.leaves().into_iter().filter(|(path, value)| path.starts_with("parts.") && value.as_str() != Some(""));
162 let described: Vec<(Vec<String>, bool)> = parts
163 .chain(
164 resolved
165 .leaves()
166 .into_iter()
167 .filter(|(path, _)| path.starts_with("mass.") || path.starts_with("geometry.")),
168 )
169 .map(|(path, value)| (vec![label(&path, tr), shown(&value), source_of(&path)], false))
170 .collect();
171 blocks.push(Block::Table(vec![t("report-quantity"), t("report-value"), t("report-source")], described));
172
173 blocks.push(Block::Heading(t("report-cycle")));
174 blocks.push(Block::Text(t("report-cycle-text")));
175 let column = |id: String| signals.iter().position(|s| s.id == id);
176 let series = |quantity: &str| -> Vec<(String, Vec<[f64; 2]>, bool)> {
177 motors
178 .iter()
179 .filter_map(|m| {
180 column(format!("motor.{}.{quantity}", m.id))
181 .map(|c| (m.id.to_string(), rows.iter().map(|r| [r[0], r[c]]).collect(), false))
182 })
183 .collect()
184 };
185 blocks.push(Block::Plot(Plot {
186 title: t("report-plot-torque"),
187 x_label: "t [s]".into(),
188 y_label: "M [N m]".into(),
189 series: series("torque"),
190 }));
191 blocks.push(Block::Plot(Plot {
192 title: t("report-plot-speed"),
193 x_label: "t [s]".into(),
194 y_label: "n [1/min]".into(),
195 series: series("speed")
196 .into_iter()
197 .map(|(n, p, d)| (n, p.iter().map(|q| [q[0], q[1] * 60.0 / std::f64::consts::TAU]).collect(), d))
198 .collect(),
199 }));
200 let columns: Vec<Vec<f64>> = (0..signals.len()).map(|i| rows.iter().map(|r| r[i]).collect()).collect();
203 let rpm = 60.0 / std::f64::consts::TAU;
204 let in_rpm = |line: &[[f64; 2]]| line.iter().map(|p| [p[0] * rpm, p[1]]).collect::<Vec<_>>();
205 for (k, m) in motors.iter().enumerate() {
206 let drive = sim.control.drive_params_of(k);
207 let get = |name: &str| column(format!("motor.{}.{name}", m.id)).map(|c| columns[c].as_slice());
208 let (Some(speed), Some(torque)) = (get("speed"), get("torque")) else { continue };
209 let chart = charts::torque_speed(drive, charts::dc_link_of(drive, get("dc_link_voltage")));
210 let n = speed.len();
211 let mut series: Vec<(String, Vec<[f64; 2]>, bool)> = (0..4)
212 .map(|q| {
213 let points = (q * n / 4..(q + 1) * n / 4).map(|i| [speed[i] * rpm, torque[i]]).collect();
214 (format!("{}–{} %", q * 25, (q + 1) * 25), points, true)
215 })
216 .collect();
217 let [w, rms] = charts::rms_point(speed, torque);
218 series.push((t("charts-rms-point"), vec![[w * rpm, rms]], true));
219 for (key, lines) in
220 [("charts-peak", &chart.peak), ("charts-s1", &chart.s1), ("charts-voltage-limit", &chart.voltage)]
221 {
222 series.extend(lines.iter().map(|line| (t(key), in_rpm(line), false)));
223 }
224 if let Some(limit) = chart.current_limit {
225 let top = chart.peak[0].last().map_or(0.0, |p| p[0] * rpm);
226 for sign in [1.0, -1.0] {
227 series.push((t("charts-current-limit"), vec![[-top, sign * limit], [top, sign * limit]], false));
228 }
229 }
230 blocks.push(Block::Plot(Plot {
231 title: format!("{} · {} ({:.0} V)", motor_name(Some(k)), t("report-plot-curve"), chart.dc_voltage),
232 x_label: "n [1/min]".into(),
233 y_label: "M [N m]".into(),
234 series,
235 }));
236 }
237 if let Some(error) = charts::tool_error(&signals, &columns).filter(|e| !e.normal.is_empty()) {
238 let (unit, scale, first, second) = if error.place {
240 ("µm", 1e6, error.normal.as_slice(), Some(error.tangential.as_slice()))
241 } else {
242 ("mrad", 1e3, error.angle.as_slice(), None)
243 };
244 let scaled = |v: &[f64]| v.iter().zip(&error.time).map(|(v, t)| [*t, v * scale]).collect::<Vec<_>>();
245 let name = t(if error.place { "charts-normal" } else { "charts-angle-error" });
246 let mut series = vec![(name.clone(), scaled(first), false)];
247 series.extend(second.map(|v| (t("charts-tangential"), scaled(v), false)));
248 blocks.push(Block::Plot(Plot {
249 title: t("charts-tool-error"),
250 x_label: "t [s]".into(),
251 y_label: format!("e [{unit}]"),
252 series,
253 }));
254 let steps = charts::histogram(first, 40)
255 .iter()
256 .flat_map(|(low, high, n)| [[low * scale, *n as f64], [high * scale, *n as f64]])
257 .collect();
258 blocks.push(Block::Plot(Plot {
259 title: t("charts-histogram"),
260 x_label: format!("{name} [{unit}]"),
261 y_label: "n".into(),
262 series: vec![(name, steps, false)],
263 }));
264 }
265 for (k, m) in motors.iter().enumerate() {
266 let parts = charts::torque_parts(&signals, &columns, m.id);
267 if !parts.is_empty() {
268 let stacked = charts::stack(&parts.iter().map(|(_, v)| *v).collect::<Vec<_>>());
269 let series = parts
270 .iter()
271 .zip(&stacked)
272 .map(|((part, _), v)| {
273 let line = v.iter().zip(&columns[0]).map(|(v, t)| [*t, *v]).collect();
274 (format!("+ {}", t(&format!("quantity-torque-{part}"))), line, false)
275 })
276 .collect();
277 blocks.push(Block::Plot(Plot {
278 title: format!("{} · {}", motor_name(Some(k)), t("charts-torque-split")),
279 x_label: "t [s]".into(),
280 y_label: "M [N m]".into(),
281 series,
282 }));
283 }
284 let shares = charts::utilisation(sim.control.drive_params_of(k), &signals, &columns, m.id);
285 if !shares.is_empty() {
286 let series = shares
287 .iter()
288 .map(|(key, v)| {
289 (t(key), v.iter().zip(&columns[0]).map(|(v, t)| [*t, (v * 100.0).min(1e4)]).collect(), false)
290 })
291 .collect();
292 blocks.push(Block::Plot(Plot {
293 title: format!("{} · {}", motor_name(Some(k)), t("charts-utilisation")),
294 x_label: "t [s]".into(),
295 y_label: "[%]".into(),
296 series,
297 }));
298 }
299 }
300
301 blocks.push(Block::Heading(t("report-verdicts")));
302 blocks.push(Block::Text(t("report-verdicts-text")));
303 let head = ["report-check", "report-motor", "report-value", "report-limit", "report-margin", "report-result"]
304 .map(t)
305 .to_vec();
306 let result = |ok: bool| t(if ok { "report-ok" } else { "report-not-ok" });
307 let check = |b: &Band| {
308 let linear = b.verdict.motor.is_some_and(|k| sim.machine.motor_linear(k));
309 tr.tr(&check_key(b.verdict.check, linear)).to_string()
310 };
311 let verdict_rows = judged.iter().map(|b| {
312 let v = &b.verdict;
313 (
314 vec![
315 check(b),
316 motor_name(v.motor),
317 number(v.value),
318 number(v.limit),
319 margin(1.0 - utilisation(v)),
320 result(v.ok),
321 ],
322 !v.ok,
323 )
324 });
325 blocks.push(Block::Table(head, verdict_rows.collect()));
326 if bands {
327 blocks.push(Block::Heading(t("report-bands")));
328 blocks.push(Block::Text(tr.tr_arg("report-bands-text", &bounds(&resolved)?.len().to_string())));
329 let head = ["report-check", "report-motor", "report-low", "report-high", "report-limit", "report-worst-case"]
330 .map(t)
331 .to_vec();
332 let band_rows = judged.iter().map(|b| {
333 (
334 vec![
335 check(b),
336 motor_name(b.verdict.motor),
337 number(b.low),
338 number(b.high),
339 number(b.verdict.limit),
340 result(b.ok),
341 ],
342 !b.ok,
343 )
344 });
345 blocks.push(Block::Table(head, band_rows.collect()));
346 }
347
348 blocks.push(Block::Heading(t("report-inputs")));
349 blocks.push(Block::Text(t("report-inputs-text")));
350 let value = |path: &str, value: toml::Value| {
351 if path.starts_with("parts.") { named.get(path).map_or(String::new(), shown) } else { shown(&value) }
352 };
353 let inputs = resolved
354 .leaves()
355 .into_iter()
356 .filter(|(path, _)| path != "format_version")
357 .map(|(path, v)| (vec![path.clone(), value(&path, v), source_of(&path)], false));
358 blocks.push(Block::Table(vec![t("report-parameter"), t("report-value"), t("report-source")], inputs.collect()));
359
360 blocks.push(Block::Heading(t("report-sign-off")));
361 blocks.push(Block::Text(t("report-sign-off-text")));
362 let roles = ["report-prepared", "report-checked", "report-accepted"].map(t).to_vec();
363 blocks.push(Block::SignOff(
364 roles,
365 ["report-name", "report-company", "report-date", "report-signature"].map(t).to_vec(),
366 ));
367 Ok(Report { title: format!("{} – {}", t("report-title"), tr.tr(entry.key)), blocks, passed })
368}
369
370fn provenance<'a>(
373 entry: &MachineEntry,
374 text: &str,
375 named: &'a Config,
376 resolved: &'a Config,
377 tr: &'a Translations,
378) -> Result<impl Fn(&str) -> String + 'a, ConfigError> {
379 let (tags, file, from_parts) = (sources(text), Config::parse(text).ok(), catalog::resolve(entry, named)?);
380 Ok(move |path: &str| {
381 let (in_file, before, brought, used) = (
382 file.as_ref().and_then(|f| f.get(path).ok()),
383 named.get(path).ok(),
384 from_parts.get(path).ok(),
385 resolved.get(path).ok(),
386 );
387 let parts = path.starts_with("parts.");
389 if (!parts && used != brought) || (brought == before && before != in_file) || (parts && before != in_file) {
390 tr.tr("report-source-set").to_string()
391 } else if !parts && brought != before {
392 tr.tr("report-source-parts").to_string()
393 } else {
394 tags.get(path).cloned().unwrap_or_else(|| tr.tr("report-source-none").to_string())
395 }
396 })
397}
398
399fn label(path: &str, tr: &Translations) -> String {
401 let key = format!("param-{}", path.rsplit('.').next().unwrap_or(path));
402 if tr.has(&key) { format!("{} ({path})", tr.tr(&key)) } else { path.to_string() }
403}
404
405fn shown(value: &toml::Value) -> String {
406 value.as_str().map_or_else(|| value.to_string(), str::to_string)
407}
408
409fn number(value: f64) -> String {
411 let decimals = if value == 0.0 || !value.is_finite() { 0 } else { (3 - value.abs().log10().floor() as i32).max(0) };
412 format!("{value:.*}", decimals as usize)
413}
414
415fn margin(share: f64) -> String {
416 if share.is_finite() { format!("{:+.1} %", share * 100.0) } else { "–".into() }
417}
418
419fn today() -> String {
421 let days =
422 std::time::SystemTime::now().duration_since(std::time::UNIX_EPOCH).map_or(0, |d| d.as_secs() / 86_400) as i64;
423 let z = days + 719_468;
424 let (era, doe) = (z.div_euclid(146_097), z.rem_euclid(146_097));
425 let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
426 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
427 let mp = (5 * doy + 2) / 153;
428 let (d, m) = (doy - (153 * mp + 2) / 5 + 1, if mp < 10 { mp + 3 } else { mp - 9 });
429 format!("{:04}-{m:02}-{d:02}", yoe + era * 400 + i64::from(m <= 2))
430}
431
432const COLORS: [(f64, f64, f64); 6] = [
433 (0.16, 0.38, 0.72),
434 (0.85, 0.42, 0.10),
435 (0.20, 0.60, 0.30),
436 (0.55, 0.30, 0.65),
437 (0.45, 0.45, 0.45),
438 (0.45, 0.45, 0.45),
439];
440
441enum Mark {
444 Line(Vec<[f64; 2]>, (f64, f64, f64), f64),
445 Dot([f64; 2], (f64, f64, f64)),
446 Text([f64; 2], String, f64, f64),
447}
448
449pub fn peak_keeping(n: usize, point: impl Fn(usize) -> [f64; 2], buckets: usize) -> Vec<[f64; 2]> {
454 if n <= 2 * buckets {
455 return (0..n).map(point).collect();
456 }
457 let mut out = Vec::with_capacity(2 * buckets);
458 for b in 0..buckets {
459 let (from, to) = (b * n / buckets, (b + 1) * n / buckets);
460 let (mut low, mut high) = ((from, point(from)[1]), (from, point(from)[1]));
461 for i in from + 1..to {
462 let y = point(i)[1];
463 if y < low.1 || low.1.is_nan() {
465 low = (i, y);
466 }
467 if y > high.1 || high.1.is_nan() {
468 high = (i, y);
469 }
470 }
471 let (low, high) = (low.0, high.0);
472 out.push(point(low.min(high)));
473 if low != high {
474 out.push(point(low.max(high)));
475 }
476 }
477 out
478}
479
480fn tick_step(span: f64) -> f64 {
482 let raw = (span / 5.0).max(1e-12);
483 let power = 10f64.powf(raw.log10().floor());
484 [1.0, 2.0, 5.0, 10.0].into_iter().map(|f| f * power).find(|s| *s >= raw).unwrap_or(10.0 * power)
485}
486
487fn tick(value: f64, step: f64) -> String {
489 let decimals = (-step.log10().floor()).max(0.0) as usize;
490 format!("{:.*}", decimals, if value.abs() < step * 1e-6 { 0.0 } else { value })
492}
493
494fn marks(plot: &Plot, w: f64, h: f64) -> Vec<Mark> {
495 let (left, right, top, bottom) = (52.0, w - 10.0, 34.0, h - 40.0);
496 let all = || plot.series.iter().flat_map(|s| s.1.iter());
497 let range = |i: usize| {
498 let (lo, hi) = all().fold((f64::INFINITY, f64::NEG_INFINITY), |(lo, hi), p| (lo.min(p[i]), hi.max(p[i])));
499 if lo.is_finite() && hi > lo {
500 (lo, hi)
501 } else if lo.is_finite() {
502 (lo - 1.0, lo + 1.0)
503 } else {
504 (0.0, 1.0)
505 }
506 };
507 let ((x0, x1), (y0, y1)) = (range(0), range(1));
508 let (sx, sy) = (tick_step(x1 - x0), tick_step(y1 - y0));
509 let (x0, x1, y0, y1) =
510 ((x0 / sx).floor() * sx, (x1 / sx).ceil() * sx, (y0 / sy).floor() * sy, (y1 / sy).ceil() * sy);
511 let at = |p: &[f64; 2]| {
512 [left + (p[0] - x0) / (x1 - x0) * (right - left), bottom - (p[1] - y0) / (y1 - y0) * (bottom - top)]
513 };
514 let grey = (0.75, 0.75, 0.75);
515 let mut out = vec![Mark::Text([left, 12.0], plot.title.clone(), 10.0, 0.0)];
516 let mut x = x0;
517 while x <= x1 + sx * 1e-6 {
518 out.push(Mark::Line(vec![at(&[x, y0]), at(&[x, y1])], grey, 0.4));
519 out.push(Mark::Text([at(&[x, y0])[0], bottom + 12.0], tick(x, sx), 7.0, 0.5));
520 x += sx;
521 }
522 let mut y = y0;
523 while y <= y1 + sy * 1e-6 {
524 out.push(Mark::Line(vec![at(&[x0, y]), at(&[x1, y])], grey, 0.4));
525 out.push(Mark::Text([left - 4.0, at(&[x0, y])[1] + 2.5], tick(y, sy), 7.0, 1.0));
526 y += sy;
527 }
528 out.push(Mark::Text([(left + right) / 2.0, bottom + 24.0], plot.x_label.clone(), 8.0, 0.5));
529 out.push(Mark::Text([left, top - 6.0], plot.y_label.clone(), 8.0, 0.5));
530 let mut legend = left;
531 for (i, (name, points, dots)) in plot.series.iter().enumerate() {
532 let color = COLORS[i.min(COLORS.len() - 1)];
533 let shown: Vec<[f64; 2]> = if *dots {
536 points.iter().step_by((points.len() / 800).max(1)).map(at).collect()
537 } else {
538 peak_keeping(points.len(), |i| points[i], 400).iter().map(at).collect()
539 };
540 if *dots {
541 out.extend(shown.into_iter().map(|p| Mark::Dot(p, color)));
542 } else {
543 out.push(Mark::Line(shown, color, 1.0));
544 }
545 out.push(Mark::Line(vec![[legend, h - 6.0], [legend + 14.0, h - 6.0]], color, 2.0));
546 out.push(Mark::Text([legend + 18.0, h - 3.5], name.clone(), 7.0, 0.0));
547 legend += 30.0 + width(name, 7.0, false);
548 }
549 out
550}
551
552impl Plot {
553 pub fn svg(&self) -> String {
555 let plot = self;
556 let mut out = String::new();
557 let (w, h) = (720.0, 300.0);
558 _ = write!(
559 out,
560 "<svg viewBox=\"0 0 {w} {h}\" xmlns=\"http://www.w3.org/2000/svg\" font-family=\"Helvetica,Arial,sans-serif\">"
561 );
562 for mark in marks(plot, w, h) {
563 match mark {
564 Mark::Line(points, c, width) => {
565 let p: Vec<String> = points.iter().map(|p| format!("{:.1},{:.1}", p[0], p[1])).collect();
566 _ = write!(
567 out,
568 "<polyline fill=\"none\" stroke=\"{}\" stroke-width=\"{width}\" points=\"{}\"/>",
569 rgb(c),
570 p.join(" ")
571 );
572 }
573 Mark::Dot(p, c) => {
574 _ = write!(out, "<circle cx=\"{:.1}\" cy=\"{:.1}\" r=\"1\" fill=\"{}\"/>", p[0], p[1], rgb(c))
575 }
576 Mark::Text(p, text, size, anchor) => {
577 let anchor = if anchor == 0.0 {
578 "start"
579 } else if anchor == 1.0 {
580 "end"
581 } else {
582 "middle"
583 };
584 _ = write!(
585 out,
586 "<text x=\"{:.1}\" y=\"{:.1}\" font-size=\"{size}\" text-anchor=\"{anchor}\">{}</text>",
587 p[0],
588 p[1],
589 escape(&text)
590 );
591 }
592 }
593 }
594 out + "</svg>"
595 }
596}
597
598fn escape(text: &str) -> String {
599 text.replace('&', "&").replace('<', "<").replace('>', ">").replace('"', """)
600}
601
602fn rgb(c: (f64, f64, f64)) -> String {
603 format!("rgb({},{},{})", (c.0 * 255.0) as u8, (c.1 * 255.0) as u8, (c.2 * 255.0) as u8)
604}
605
606impl Report {
607 pub fn html(&self, lang: &str) -> String {
609 let mut out = format!(
610 "<!doctype html>\n<html lang=\"{lang}\"><head><meta charset=\"utf-8\"><title>{0}</title><style>\
611 @page{{size:A4;margin:18mm}} body{{font:13px/1.45 Helvetica,Arial,sans-serif;color:#111;max-width:960px;margin:24px auto;padding:0 16px}}\
612 h1{{font-size:22px}} h2{{font-size:16px;margin-top:28px;border-bottom:1px solid #999}} table{{border-collapse:collapse;width:100%;margin:8px 0}}\
613 th,td{{border:1px solid #bbb;padding:3px 6px;text-align:left;vertical-align:top}} th{{background:#eee}} tr.fail td{{background:#fbe3e3;color:#900}}\
614 svg{{width:100%;max-width:720px;display:block;margin:8px 0}} .sign{{display:grid;grid-template-columns:repeat(3,1fr);gap:16px}}\
615 .sign div{{border:1px solid #999;padding:8px}} .sign p{{margin:18px 0 0;border-bottom:1px solid #333;font-size:11px;color:#555}}\
616 tr{{break-inside:avoid}} .sign,svg{{break-inside:avoid}}</style></head><body>\n<h1>{0}</h1>\n",
617 escape(&self.title)
618 );
619 for block in &self.blocks {
620 match block {
621 Block::Heading(text) => _ = writeln!(out, "<h2>{}</h2>", escape(text)),
622 Block::Text(text) => _ = writeln!(out, "<p>{}</p>", escape(text)),
623 Block::Table(head, rows) => {
624 out += "<table><tr>";
625 head.iter().for_each(|h| _ = write!(out, "<th>{}</th>", escape(h)));
626 out += "</tr>\n";
627 for (cells, fail) in rows {
628 out += if *fail { "<tr class=\"fail\">" } else { "<tr>" };
629 cells.iter().for_each(|c| _ = write!(out, "<td>{}</td>", escape(c)));
630 out += "</tr>\n";
631 }
632 out += "</table>\n";
633 }
634 Block::Plot(plot) => out += &(plot.svg() + "\n"),
635 Block::SignOff(roles, fields) => {
636 out += "<div class=\"sign\">";
637 for role in roles {
638 _ = write!(out, "<div><b>{}</b>", escape(role));
639 fields.iter().for_each(|f| _ = write!(out, "<p>{}</p>", escape(f)));
640 out += "</div>";
641 }
642 out += "</div>\n";
643 }
644 }
645 }
646 out + "</body></html>\n"
647 }
648
649 pub fn pdf(&self) -> Vec<u8> {
651 let mut pdf = Pdf::new();
652 pdf.text(MARGIN, &self.title, 16.0, true);
653 pdf.y += 8.0;
654 for block in &self.blocks {
655 match block {
656 Block::Heading(text) => {
657 pdf.room(60.0);
658 pdf.y += 10.0;
659 pdf.text(MARGIN, text, 12.0, true);
660 pdf.rule(pdf.y + 2.0, 0.6);
661 pdf.y += 6.0;
662 }
663 Block::Text(text) => {
664 for line in wrap(text, WIDTH, 9.0, false) {
665 pdf.room(12.0);
666 pdf.text(MARGIN, &line, 9.0, false);
667 }
668 pdf.y += 4.0;
669 }
670 Block::Table(head, rows) => pdf.table(head, rows),
671 Block::Plot(plot) => {
672 let (w, h) = (WIDTH, 230.0);
673 pdf.room(h + 6.0);
674 let (x0, y0) = (MARGIN, pdf.y);
675 for mark in marks(plot, w, h) {
676 match mark {
677 Mark::Line(points, c, width) => {
678 pdf.line(&points.iter().map(|p| [x0 + p[0], y0 + p[1]]).collect::<Vec<_>>(), c, width)
679 }
680 Mark::Dot(p, c) => {
681 pdf.line(&[[x0 + p[0] - 0.6, y0 + p[1]], [x0 + p[0] + 0.6, y0 + p[1]]], c, 1.2)
682 }
683 Mark::Text(p, text, size, anchor) => pdf.text_at(
684 x0 + p[0] - anchor * width(&text, size, false),
685 y0 + p[1],
686 &text,
687 size,
688 false,
689 ),
690 }
691 }
692 pdf.y += h + 6.0;
693 }
694 Block::SignOff(roles, fields) => {
695 let column = WIDTH / roles.len() as f64;
696 pdf.room(40.0 + 30.0 * fields.len() as f64);
697 let top = pdf.y;
698 for (i, role) in roles.iter().enumerate() {
699 let x = MARGIN + i as f64 * column;
700 pdf.text_at(x, top + 12.0, role, 10.0, true);
701 for (j, field) in fields.iter().enumerate() {
702 let y = top + 46.0 + 30.0 * j as f64;
703 pdf.line(&[[x, y], [x + column - 14.0, y]], (0.2, 0.2, 0.2), 0.5);
704 pdf.text_at(x, y + 9.0, field, 7.0, false);
705 }
706 }
707 pdf.y = top + 46.0 + 30.0 * fields.len() as f64;
708 }
709 }
710 }
711 pdf.finish(&self.title)
712 }
713}
714
715const PAGE: (f64, f64) = (595.0, 842.0);
716const MARGIN: f64 = 40.0;
717const WIDTH: f64 = PAGE.0 - 2.0 * MARGIN;
718const BOTTOM: f64 = PAGE.1 - 50.0;
719
720const HELVETICA: [u16; 95] = [
722 278, 278, 355, 556, 556, 889, 667, 191, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556, 556, 556, 556, 556,
723 556, 556, 556, 278, 278, 584, 584, 584, 556, 1015, 667, 667, 722, 722, 667, 611, 778, 722, 278, 500, 667, 556, 833,
724 722, 778, 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 278, 278, 278, 469, 556, 333, 556, 556, 500, 556,
725 556, 278, 556, 556, 222, 222, 500, 222, 833, 556, 556, 556, 556, 333, 500, 278, 556, 500, 722, 500, 500, 500, 334,
726 260, 334, 584,
727];
728
729fn width(text: &str, size: f64, bold: bool) -> f64 {
732 let units: f64 =
733 text.chars().map(|c| HELVETICA.get((c as usize).wrapping_sub(32)).copied().unwrap_or(556) as f64).sum();
734 units * size / 1000.0 * if bold { 1.06 } else { 1.0 }
735}
736
737fn wrap(text: &str, room: f64, size: f64, bold: bool) -> Vec<String> {
739 let mut lines = vec![String::new()];
740 for word in text.split(' ') {
741 let last = lines.last_mut().unwrap();
742 let joined = if last.is_empty() { word.to_string() } else { format!("{last} {word}") };
743 if width(&joined, size, bold) <= room || last.is_empty() {
744 *last = joined;
745 } else {
746 lines.push(word.to_string());
747 }
748 while width(lines.last().unwrap(), size, bold) > room && lines.last().unwrap().chars().count() > 1 {
749 let long = lines.pop().unwrap();
750 let fit = (1..=long.chars().count())
751 .take_while(|&n| width(&long.chars().take(n).collect::<String>(), size, bold) <= room)
752 .last()
753 .unwrap_or(1);
754 lines.push(long.chars().take(fit).collect());
755 lines.push(long.chars().skip(fit).collect());
756 }
757 }
758 lines
759}
760
761fn pdf_string(text: &str) -> Vec<u8> {
764 let mut out = vec![b'('];
765 for c in text.chars() {
766 let byte = match c {
767 ' '..='~' | '\u{a0}'..='\u{ff}' => c as u8,
768 '–' => 0x96,
769 '—' => 0x97,
770 '‚' => 0x82,
771 '„' => 0x84,
772 '‘' => 0x91,
773 '’' => 0x92,
774 '“' => 0x93,
775 '”' => 0x94,
776 '•' => 0x95,
777 '…' => 0x85,
778 '€' => 0x80,
779 '−' => b'-',
780 _ => b'?',
781 };
782 if matches!(byte, b'(' | b')' | b'\\') {
783 out.push(b'\\');
784 }
785 out.push(byte);
786 }
787 out.push(b')');
788 out
789}
790
791struct Pdf {
793 pages: Vec<Vec<u8>>,
794 y: f64,
795}
796
797impl Pdf {
798 fn new() -> Self {
799 Pdf { pages: vec![Vec::new()], y: MARGIN }
800 }
801
802 fn room(&mut self, height: f64) {
804 if self.y + height > BOTTOM {
805 self.pages.push(Vec::new());
806 self.y = MARGIN;
807 }
808 }
809
810 fn page(&mut self) -> &mut Vec<u8> {
811 self.pages.last_mut().unwrap()
812 }
813
814 fn text_at(&mut self, x: f64, y: f64, text: &str, size: f64, bold: bool) {
815 let page = self.page();
816 _ = write!(Bytes(page), "BT /{} {size} Tf {x:.2} {:.2} Td ", if bold { "F2" } else { "F1" }, PAGE.1 - y);
817 page.extend(pdf_string(text));
818 page.extend(b" Tj ET\n");
819 }
820
821 fn text(&mut self, x: f64, text: &str, size: f64, bold: bool) {
823 self.y += size * 1.3;
824 self.text_at(x, self.y - size * 0.3, text, size, bold);
825 }
826
827 fn line(&mut self, points: &[[f64; 2]], c: (f64, f64, f64), width: f64) {
828 let Some(first) = points.first() else { return };
829 let page = self.page();
830 _ = write!(Bytes(page), "{width} w {} {} {} RG {:.2} {:.2} m", c.0, c.1, c.2, first[0], PAGE.1 - first[1]);
831 points[1..].iter().for_each(|p| _ = write!(Bytes(page), " {:.2} {:.2} l", p[0], PAGE.1 - p[1]));
832 page.extend(b" S\n");
833 }
834
835 fn rule(&mut self, y: f64, width: f64) {
836 self.line(&[[MARGIN, y], [MARGIN + WIDTH, y]], (0.5, 0.5, 0.5), width);
837 }
838
839 fn fill(&mut self, x: f64, y: f64, w: f64, h: f64, c: (f64, f64, f64)) {
840 _ = writeln!(
841 Bytes(self.page()),
842 "{} {} {} rg {x:.2} {:.2} {w:.2} {h:.2} re f 0 0 0 rg",
843 c.0,
844 c.1,
845 c.2,
846 PAGE.1 - y - h
847 );
848 }
849
850 fn table(&mut self, head: &[String], rows: &[(Vec<String>, bool)]) {
853 let (size, pad) = (7.5, 3.0);
854 let natural: Vec<f64> = (0..head.len())
855 .map(|i| {
856 std::iter::once(width(&head[i], size, true))
857 .chain(rows.iter().map(|r| width(&r.0[i], size, false)))
858 .fold(0.0, f64::max)
859 + 2.0 * pad
860 })
861 .collect();
862 let fair = WIDTH / head.len() as f64;
863 let narrow: f64 = natural.iter().filter(|w| **w <= fair).sum();
864 let wide: f64 = natural.iter().filter(|w| **w > fair).sum();
865 let scale = if narrow + wide <= WIDTH { 1.0 } else { (WIDTH - narrow) / wide };
866 let widths: Vec<f64> = natural.iter().map(|w| if *w <= fair { *w } else { w * scale }).collect();
867 let draw = |pdf: &mut Pdf, cells: &[String], bold: bool, shade: Option<(f64, f64, f64)>| {
868 let lines: Vec<Vec<String>> =
869 cells.iter().zip(&widths).map(|(c, w)| wrap(c, w - 2.0 * pad, size, bold)).collect();
870 let height = lines.iter().map(Vec::len).max().unwrap_or(1) as f64 * size * 1.25 + 2.0 * pad;
871 pdf.room(height);
872 let top = pdf.y;
873 if let Some(color) = shade {
874 pdf.fill(MARGIN, top, widths.iter().sum(), height, color);
875 }
876 let mut x = MARGIN;
877 for (cell, w) in lines.iter().zip(&widths) {
878 for (n, line) in cell.iter().enumerate() {
879 pdf.text_at(x + pad, top + pad + size * (1.0 + 1.25 * n as f64) - 1.0, line, size, bold);
880 }
881 x += w;
882 }
883 pdf.line(
884 &[[MARGIN, top + height], [MARGIN + widths.iter().sum::<f64>(), top + height]],
885 (0.7, 0.7, 0.7),
886 0.4,
887 );
888 pdf.y = top + height;
889 };
890 self.room(30.0);
891 draw(self, head, true, Some((0.92, 0.92, 0.92)));
892 for (cells, fail) in rows {
893 if self.y + 20.0 > BOTTOM {
894 self.room(BOTTOM);
895 draw(self, head, true, Some((0.92, 0.92, 0.92)));
896 }
897 draw(self, cells, false, fail.then_some((0.98, 0.88, 0.88)));
898 }
899 self.y += 6.0;
900 }
901
902 fn finish(mut self, title: &str) -> Vec<u8> {
904 let count = self.pages.len();
905 for n in 0..count {
906 let footer = format!("{title} – {} / {count}", n + 1);
907 let page = &mut self.pages[n];
908 _ = write!(Bytes(page), "BT /F1 7 Tf {MARGIN} 28 Td ");
909 page.extend(pdf_string(&footer));
910 page.extend(b" Tj ET\n");
911 }
912 let mut objects: Vec<Vec<u8>> = vec![
914 b"<< /Type /Catalog /Pages 2 0 R >>".to_vec(),
915 format!(
916 "<< /Type /Pages /Count {count} /Kids [{}] >>",
917 (0..count).map(|n| format!("{} 0 R", 5 + 2 * n)).collect::<Vec<_>>().join(" ")
918 )
919 .into_bytes(),
920 b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >>".to_vec(),
921 b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold /Encoding /WinAnsiEncoding >>".to_vec(),
922 ];
923 for (n, content) in self.pages.into_iter().enumerate() {
924 let page = format!(
925 "<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {} {}] /Resources << /Font << /F1 3 0 R /F2 4 0 R >> >> /Contents {} 0 R >>",
926 PAGE.0,
927 PAGE.1,
928 6 + 2 * n
929 );
930 objects.push(page.into_bytes());
931 let mut stream = format!("<< /Length {} >>\nstream\n", content.len()).into_bytes();
932 stream.extend(content);
933 stream.extend(b"\nendstream");
934 objects.push(stream);
935 }
936 let mut out = b"%PDF-1.4\n%\xe2\xe3\xcf\xd3\n".to_vec();
937 let mut offsets = Vec::new();
938 for (i, object) in objects.iter().enumerate() {
939 offsets.push(out.len());
940 out.extend(format!("{} 0 obj\n", i + 1).bytes());
941 out.extend(object);
942 out.extend(b"\nendobj\n");
943 }
944 let xref = out.len();
945 out.extend(format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).bytes());
946 offsets.iter().for_each(|o| out.extend(format!("{o:010} 00000 n \n").bytes()));
947 out.extend(
948 format!("trailer\n<< /Size {} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n", objects.len() + 1).bytes(),
949 );
950 out
951 }
952}
953
954struct Bytes<'a>(&'a mut Vec<u8>);
956
957impl std::fmt::Write for Bytes<'_> {
958 fn write_str(&mut self, s: &str) -> std::fmt::Result {
959 self.0.extend(s.as_bytes());
960 Ok(())
961 }
962}
963
964#[cfg(test)]
965mod tests {
966 use super::*;
967
968 #[test]
971 fn failing_check_ids_are_shown_by_their_labels() {
972 let tr = |lang| Translations::parse(crate::I18N.iter().find(|(l, _)| *l == lang).unwrap().1);
973 let (en, de) = (tr("en"), tr("de"));
974 let ids = "motor-speed, no-such-check, motor-speed";
976 assert_eq!(check_labels(ids, false, &en), "Motor speed, peak [rad/s]; no-such-check");
977 assert_eq!(check_labels(ids, true, &en), "Motor speed, peak [m/s]; no-such-check");
978 assert_eq!(check_labels("motor-speed", false, &de), "Motordrehzahl, Spitze [rad/s]");
979 }
980
981 #[test]
982 fn sources_follow_the_comments() {
983 let text = "format_version = 1
984# [estimate] all of these
985[mass]
986# [catalogue] from the data sheet
987a_kg = 1.0
988b_kg = 2.0
989
990c_kg = 3.0
991# [CAD] model.step: m=4
992d_kg = 4.0
993d2_kg = 4.5
994# a note without a tag
995e_kg = 5.0
996f_kg = 6.0 # [catalogue] at the end of the line
997# [catalogue] a line module; its efficiency [estimate]
998g = 0.9
999[belt]
1000f = 1
1001[thermal] # [estimate]
1002h = 2
1003[[cycle.segment]]
1004# [cad]
1005g = 1
1006";
1007 let s = sources(text);
1008 let get = |path: &str| s.get(path).map(String::as_str);
1009 assert_eq!(get("mass.a_kg"), Some("[catalogue]"));
1010 assert_eq!(get("mass.b_kg"), Some("[catalogue]"), "a tag holds for the keys right below it");
1011 assert_eq!(get("mass.c_kg"), Some("[estimate]"), "after a blank line the table's tag holds");
1012 assert_eq!(get("mass.d_kg"), Some("[cad]"));
1013 assert_eq!(get("mass.d2_kg"), Some("[estimate]"), "a [cad] line marks one key");
1014 assert_eq!(
1015 get("mass.e_kg"),
1016 Some("[estimate]"),
1017 "a comment without a tag ends the one above, the table's holds"
1018 );
1019 assert_eq!(get("mass.f_kg"), Some("[catalogue]"), "a tag at the end of the line");
1020 assert_eq!(get("mass.g"), Some("[catalogue] / [estimate]"));
1021 assert_eq!(get("belt.f"), None);
1022 assert_eq!(get("thermal.h"), Some("[estimate]"), "a tag after the header");
1023 assert_eq!(s.len(), 9, "nothing from the cycle's segments: {s:?}");
1024 }
1025
1026 #[test]
1027 fn dates_and_numbers() {
1028 assert_eq!(today().len(), 10);
1029 assert_eq!(number(0.012345), "0.01235");
1030 assert_eq!(margin(0.25), "+25.0 %");
1031 assert_eq!(margin(f64::INFINITY), "–");
1032 assert_eq!(tick_step(10.0), 2.0);
1033 assert_eq!(tick_step(0.7), 0.2);
1034 assert_eq!(
1035 (tick(0.5, 0.5), tick(2.0, 1.0), tick(-1e-17, 0.2), tick(0.4, 0.2)),
1036 ("0.5".into(), "2".into(), "0.0".into(), "0.4".into())
1037 );
1038 }
1039
1040 #[test]
1041 fn pdf_is_well_formed() {
1042 let rows: Vec<(Vec<String>, bool)> = (0..200)
1043 .map(|i| {
1044 (
1045 vec![
1046 format!(
1047 "row {i} (with brackets) and a long text that wraps over more than one line of its column"
1048 ),
1049 "1.0".into(),
1050 ],
1051 i == 3,
1052 )
1053 })
1054 .collect();
1055 let plot = Plot {
1056 title: "p".into(),
1057 x_label: "x".into(),
1058 y_label: "y".into(),
1059 series: vec![("a".into(), vec![[0.0, 1.0], [1.0, -2.0]], false), ("b".into(), vec![[0.5, 0.5]], true)],
1060 };
1061 let report = Report {
1062 title: "Größe – test".into(),
1063 blocks: vec![
1064 Block::Heading("h".into()),
1065 Block::Table(vec!["a".into(), "b".into()], rows),
1066 Block::Plot(plot),
1067 Block::SignOff(vec!["x".into()], vec!["Name".into()]),
1068 ],
1069 passed: true,
1070 };
1071 let pdf = report.pdf();
1072 let text: String = pdf.iter().map(|&b| if b.is_ascii() { b as char } else { '?' }).collect();
1074 assert!(text.starts_with("%PDF-1.4") && text.ends_with("%%EOF\n"));
1075 let xref: usize = text.rsplit("startxref\n").next().unwrap().lines().next().unwrap().parse().unwrap();
1077 let entries: Vec<usize> =
1078 text[xref..].lines().skip(3).take_while(|l| l.ends_with(" n ")).map(|l| l[..10].parse().unwrap()).collect();
1079 for (i, offset) in entries.iter().enumerate() {
1080 assert!(pdf[*offset..].starts_with(format!("{} 0 obj", i + 1).as_bytes()), "object {}", i + 1);
1081 }
1082 let pages = text.matches("/Type /Page ").count();
1083 assert!(pages >= 3, "200 wrapped rows take several pages: {pages}");
1084 assert!(text.contains(&format!("/Count {pages}")));
1085 for part in text.split("<< /Length ").skip(1) {
1087 let length: usize = part.split_whitespace().next().unwrap().parse().unwrap();
1088 let body = part.split_once("stream\n").unwrap().1;
1089 assert_eq!(&body.as_bytes()[length..length + 10], b"\nendstream");
1090 }
1091 assert!(pdf.windows(4).any(|w| w == b"Gr\xf6\xdf"), "German letters in WinAnsi");
1092 assert!(text.contains("\\(with brackets\\)"));
1093 let html = report.html("en");
1094 assert!(html.contains("<tr class=\"fail\">") && html.contains("<svg") && html.contains("Größe"));
1095 }
1096}