use super::{
details::SheetDetails,
diagram::{CutViews, DiagramImage},
layout::SheetLayout,
};
use indicatrix::{
geometry::meet_solver::{Block, SolvedTier},
optics::materials::GemMaterial,
};
use indicatrix_cut_core::{ConcaveRowInfo, CutSheetRow, Design, format_sheet_indices};
use std::fmt::Write as _;
const BASE64_ALPHABET: &[u8; 64] =
b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
#[must_use]
pub(super) fn base64_encode(data: &[u8]) -> String {
let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
for chunk in data.chunks(3) {
let b0 = u32::from(chunk[0]);
let b1 = chunk.get(1).copied().map_or(0, u32::from);
let b2 = chunk.get(2).copied().map_or(0, u32::from);
let n = (b0 << 16) | (b1 << 8) | b2;
out.push(BASE64_ALPHABET[((n >> 18) & 0x3f) as usize] as char);
out.push(BASE64_ALPHABET[((n >> 12) & 0x3f) as usize] as char);
out.push(if chunk.len() > 1 {
BASE64_ALPHABET[((n >> 6) & 0x3f) as usize] as char
} else {
'='
});
out.push(if chunk.len() > 2 {
BASE64_ALPHABET[(n & 0x3f) as usize] as char
} else {
'='
});
}
out
}
fn png_data_uri(image: &DiagramImage) -> String {
format!("data:image/png;base64,{}", base64_encode(&image.png_bytes))
}
pub(super) fn html_escape(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
match c {
'&' => out.push_str("&"),
'<' => out.push_str("<"),
'>' => out.push_str(">"),
'"' => out.push_str("""),
'\'' => out.push_str("'"),
_ => out.push(c),
}
}
out
}
#[derive(Clone, Copy)]
enum ViewsBlock<'a> {
Missing,
Single(&'a DiagramImage),
Four(&'a CutViews),
}
#[must_use]
pub fn cutting_sheet_html(
design: &Design,
solved: &[SolvedTier],
diagram: Option<&DiagramImage>,
custom: &[GemMaterial],
) -> String {
let layout = SheetLayout::build(design, solved, custom, &SheetDetails::from_design(design));
build_html(
&layout,
diagram.map_or(ViewsBlock::Missing, ViewsBlock::Single),
)
}
#[must_use]
pub fn cutting_sheet_html_with(
design: &Design,
solved: &[SolvedTier],
views: Option<&CutViews>,
custom: &[GemMaterial],
details: &SheetDetails,
) -> String {
let layout = SheetLayout::build(design, solved, custom, details);
build_html(&layout, views.map_or(ViewsBlock::Missing, ViewsBlock::Four))
}
fn build_html(layout: &SheetLayout, views: ViewsBlock<'_>) -> String {
let has_concave = layout.sheet.rows.iter().any(|row| row.concave.is_some());
let mut out = HTML_HEAD.replacen("{TITLE}", &html_escape(layout.heading()), 1);
if has_concave {
out = out.replacen("</style>", CONCAVE_STYLE, 1);
}
push_header(&mut out, layout);
push_facet_data(&mut out, layout);
push_size_data(&mut out, layout);
push_design_data(&mut out, layout);
push_views(&mut out, views);
push_comments(&mut out, layout);
let columns = TierTableColumns {
show_mm: layout.girdle_diameter_mm.is_some(),
show_cheater: layout.has_cheater_column(),
banded: has_concave,
};
for (heading, rows) in [
("Pavilion", layout.pavilion_rows()),
("Crown", layout.crown_rows()),
] {
push_section(&mut out, heading, &rows, columns, layout);
}
out.push_str(HTML_TAIL);
out
}
fn push_header(out: &mut String, layout: &SheetLayout) {
let _ = writeln!(out, "<h1>{}</h1>", html_escape(layout.heading()));
let details = &layout.details;
for (class, text) in [
("subtitle", details.subtitle.trim().to_string()),
(
"byline",
if details.author.trim().is_empty() {
String::new()
} else {
format!("by {}", details.author.trim())
},
),
("date", details.date_text.trim().to_string()),
] {
if !text.is_empty() {
let _ = writeln!(out, "<p class=\"{class}\">{}</p>", html_escape(&text));
}
}
}
fn push_facet_data(out: &mut String, layout: &SheetLayout) {
let facets = &layout.facets;
out.push_str("<h2>Facet Data</h2>\n<table class=\"data facets\">\n");
out.push_str("<tr><th></th><th>Tiers</th><th>Facets</th></tr>\n");
for (name, tiers, count) in [
(
"Pavilion",
facets.pavilion.tiers.to_string(),
facets.pavilion.facets.to_string(),
),
(
"Girdle",
facets.girdle.tiers.to_string(),
facets.girdle.facets.to_string(),
),
(
"Crown",
facets.crown_tiers_text(),
facets.crown_facets_text(),
),
(
"Total",
facets.total_tiers().to_string(),
facets.total_facets().to_string(),
),
] {
let _ = writeln!(
out,
"<tr><td class=\"label\">{name}</td><td>{tiers}</td><td>{count}</td></tr>"
);
}
out.push_str("</table>\n");
}
fn push_size_data(out: &mut String, layout: &SheetLayout) {
out.push_str("<h2>Size Data</h2>\n<table class=\"data sizes\">\n<tr>");
let cells = layout.sizes.cells();
for (label, _) in &cells {
let _ = write!(out, "<th>{label}</th>");
}
out.push_str("</tr>\n<tr>");
for (_, value) in &cells {
let _ = write!(out, "<td>{value}</td>");
}
out.push_str("</tr>\n</table>\n");
}
fn push_design_data(out: &mut String, layout: &SheetLayout) {
out.push_str("<h2>Design Data</h2>\n<table class=\"meta\">\n");
for (label, value) in layout.design_data.iter().chain(&layout.extras) {
push_meta_row(out, label, value);
}
out.push_str("</table>\n");
}
fn push_meta_row(out: &mut String, label: &str, value: &str) {
let _ = writeln!(
out,
"<tr><td class=\"label\">{}</td><td>{}</td></tr>",
html_escape(label),
html_escape(value)
);
}
fn push_views(out: &mut String, views: ViewsBlock<'_>) {
out.push_str("<h2>Views</h2>\n");
match views {
ViewsBlock::Four(views) => {
out.push_str("<div class=\"views\">\n");
for (label, image) in [
("down +Z", &views.top),
("down +X", &views.side),
("down -Y", &views.end),
("down -Z", &views.bottom),
] {
let _ = writeln!(
out,
"<figure><img src=\"{}\" width=\"{}\" height=\"{}\" alt=\"{label}\">\
<figcaption>{label}</figcaption></figure>",
png_data_uri(image),
image.width,
image.height
);
}
out.push_str("</div>\n");
}
ViewsBlock::Single(image) => {
let _ = writeln!(
out,
"<div class=\"diagram\"><img src=\"{}\" width=\"{}\" height=\"{}\" \
alt=\"2D faceting diagram\"></div>",
png_data_uri(image),
image.width,
image.height
);
}
ViewsBlock::Missing => out.push_str(
"<p class=\"diagram-missing\">Diagram unavailable: this design does not \
currently close to a solid.</p>\n",
),
}
}
fn push_comments(out: &mut String, layout: &SheetLayout) {
if layout.details.comments.is_empty() {
return;
}
out.push_str("<h2>Comments</h2>\n<ul class=\"comments\">\n");
for comment in &layout.details.comments {
let _ = writeln!(out, "<li>{}</li>", html_escape(comment));
}
out.push_str("</ul>\n");
}
#[derive(Clone, Copy)]
struct TierTableColumns {
show_mm: bool,
show_cheater: bool,
banded: bool,
}
impl TierTableColumns {
fn width(self) -> usize {
6 + usize::from(self.show_mm) + usize::from(self.show_cheater)
}
}
fn push_section(
out: &mut String,
heading: &str,
rows: &[(&CutSheetRow, Block)],
columns: TierTableColumns,
layout: &SheetLayout,
) {
if rows.is_empty() {
return;
}
let _ = writeln!(out, "<section class=\"cut-section\">\n<h2>{heading}</h2>");
out.push_str("<table class=\"tiers\">\n<thead><tr>");
out.push_str(
"<th>#</th><th>Label</th><th>Angle</th><th>Indices</th><th>Instruction</th><th>Mast</th>",
);
if columns.show_mm {
out.push_str("<th>Mast (mm)</th>");
}
if columns.show_cheater {
out.push_str("<th>Cheater</th>");
}
out.push_str("</tr></thead>\n");
if columns.banded {
for (position, &(row, _)) in rows.iter().enumerate() {
let stripe = if position % 2 == 0 {
"band-a"
} else {
"band-b"
};
let _ = writeln!(out, "<tbody class=\"{stripe}\">");
push_tier_row(out, row, columns, layout.mm_per_unit);
if let Some(concave) = &row.concave {
push_tool_row(out, concave, columns, layout.girdle_diameter_mm);
}
out.push_str("</tbody>\n");
}
} else {
out.push_str("<tbody>\n");
for &(row, _) in rows {
push_tier_row(out, row, columns, layout.mm_per_unit);
}
out.push_str("</tbody>\n");
}
out.push_str("</table>\n</section>\n");
}
fn push_tool_row(
out: &mut String,
concave: &ConcaveRowInfo,
columns: TierTableColumns,
girdle_diameter_mm: Option<f64>,
) {
let [code, theta, displacement, details] = concave.second_line_fields();
out.push_str("<tr class=\"tool\"><td></td>");
let _ = write!(out, "<td>{}</td>", html_escape(&code));
let _ = write!(out, "<td>{}</td>", html_escape(&theta));
let mut displacement_cell = html_escape(&displacement);
let mut details_cell = html_escape(&details);
if let Some(width_mm) = girdle_diameter_mm {
let [x, y, z] = concave.displacement.map(|ratio| ratio * width_mm);
let _ = write!(
displacement_cell,
" <span class=\"mm\">({x:.2}, {y:.2}, {z:.2} mm)</span>"
);
let _ = write!(
details_cell,
" <span class=\"mm\">(D = {:.2} mm)</span>",
concave.diameter_ratio * width_mm
);
}
let _ = write!(out, "<td>{displacement_cell}</td>");
let _ = write!(
out,
"<td colspan=\"{}\">{details_cell}</td>",
columns.width() - 4
);
out.push_str("</tr>\n");
}
fn push_tier_row(
out: &mut String,
row: &CutSheetRow,
columns: TierTableColumns,
mm_per_unit: Option<f64>,
) {
out.push_str("<tr>");
let _ = write!(out, "<td>{}</td>", row.sequence);
let _ = write!(out, "<td>{}</td>", html_escape(row.label()));
let _ = write!(out, "<td>{:.2}°</td>", row.angle_deg.abs());
let _ = write!(out, "<td>{}</td>", format_sheet_indices(&row.indices));
let _ = write!(out, "<td>{}</td>", html_escape(&row.instruction()));
let has_mast = row.concave.is_none();
let mast = if has_mast {
format!("{:.4}", row.mast)
} else {
"-".to_string()
};
let _ = write!(out, "<td>{mast}</td>");
if columns.show_mm {
let cell = mm_per_unit.filter(|_| has_mast).map_or_else(
|| "-".to_string(),
|scale| format!("{:.4}", row.mast * scale),
);
let _ = write!(out, "<td>{cell}</td>");
}
if columns.show_cheater {
let cell = row
.cheater_offset_deg
.map_or_else(|| "-".to_string(), |deg| format!("{deg:+.2}°"));
let _ = write!(out, "<td>{cell}</td>");
}
out.push_str("</tr>\n");
}
const HTML_HEAD: &str = r#"<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>{TITLE}</title>
<style>
:root { color-scheme: light; }
* { box-sizing: border-box; }
body {
font-family: Arial, Helvetica, sans-serif;
background: #ffffff;
color: #111111;
margin: 24px;
}
h1 { font-size: 22px; margin: 0 0 6px; }
h2 {
font-size: 15px;
margin: 16px 0 6px;
break-after: avoid;
page-break-after: avoid;
}
p.subtitle, p.byline, p.date { margin: 0 0 3px; font-size: 13px; }
table.meta { border-collapse: collapse; margin-bottom: 8px; }
table.meta td { padding: 2px 12px 2px 0; font-size: 13px; vertical-align: top; }
table.meta td.label { font-weight: 700; color: #333333; white-space: nowrap; }
table.data { border-collapse: collapse; margin-bottom: 8px; }
table.data th, table.data td {
border: 1px solid #999999;
padding: 3px 10px;
font-size: 12px;
text-align: left;
}
table.data th { background: #eeeeee; }
table.data td.label { font-weight: 700; }
.views { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }
.views figure { margin: 0; text-align: center; break-inside: avoid; page-break-inside: avoid; }
.views img { width: 100%; height: auto; }
.views figcaption { font-size: 12px; font-weight: 700; margin-top: 2px; }
.diagram { text-align: center; margin: 8px 0 20px; }
.diagram img { max-width: 100%; height: auto; }
.diagram-missing { color: #b91c1c; font-style: italic; }
ul.comments { font-size: 13px; margin: 0 0 8px; padding-left: 18px; }
section.cut-section { break-inside: avoid; page-break-inside: avoid; }
table.tiers { border-collapse: collapse; width: 100%; font-size: 12px; }
table.tiers th, table.tiers td {
border: 1px solid #999999;
padding: 4px 6px;
text-align: left;
}
table.tiers thead { background: #eeeeee; }
table.tiers tr { page-break-inside: avoid; break-inside: avoid; }
@page { size: A4; margin: 14mm; }
@media print {
body { margin: 0; background: #ffffff; }
table.tiers thead { display: table-header-group; }
.diagram, .views { break-inside: avoid; page-break-inside: avoid; }
}
</style>
</head>
<body>
"#;
const CONCAVE_STYLE: &str = r" tbody.band-b { background: #f4f4f4; }
tbody { page-break-inside: avoid; break-inside: avoid; }
tr.tool td { border-top: none; color: #333333; font-style: italic; }
tr.tool span.mm { color: #666666; }
</style>";
const HTML_TAIL: &str = "</body>\n</html>\n";