use ab_glyph::{Font, FontRef};
use std::collections::BTreeMap;
use std::fmt::Write;
use crisol_core::color::Rgba;
use crisol_plot_core::transform::{ScreenPoint, ScreenRect};
use crate::scene::{Anchor, Prim};
use crate::text;
const KAPPA: f32 = 0.552_284_8;
pub(crate) fn render(scene: &crate::layout::Scene, width: u32, height: u32) -> Result<Vec<u8>, crate::RenderError> {
let font = text::font()?;
let mut content = String::new();
content.push_str("1 J 1 j\n");
let mut glyphs: BTreeMap<u16, u16> = BTreeMap::new();
for prim in &scene.prims {
write_prim(&mut content, prim, height as f32, &font, &mut glyphs);
}
let widths = widths(&font, &glyphs);
let font_bytes = text::font_bytes();
let mut pdf = Pdf::new();
pdf.object("<< /Type /Catalog /Pages 2 0 R >>");
pdf.object("<< /Type /Pages /Kids [3 0 R] /Count 1 >>");
pdf.object(&format!(
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {width} {height}] /Resources << /Font << /F1 4 0 R >> >> /Contents 8 0 R >>"
));
pdf.object(
"<< /Type /Font /Subtype /Type0 /BaseFont /DejaVuSans /Encoding /Identity-H /DescendantFonts [5 0 R] >>",
);
pdf.object(&format!(
"<< /Type /Font /Subtype /CIDFontType2 /BaseFont /DejaVuSans /CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) /Supplement 0 >> /FontDescriptor 6 0 R /DW 1000 /W [{widths}] >>"
));
pdf.object(
"<< /Type /FontDescriptor /FontName /DejaVuSans /Flags 32 /FontBBox [-1024 -1024 2048 2048] /ItalicAngle 0 /Ascent 928 /Descent -236 /CapHeight 700 /StemV 80 /FontFile2 7 0 R >>",
);
pdf.stream(font_bytes, "<< /Length1 {length} >>");
pdf.stream(content.as_bytes(), "");
pdf.finish()
}
fn widths(font: &FontRef<'_>, glyphs: &BTreeMap<u16, u16>) -> String {
let units = font.units_per_em().unwrap_or(2048.0);
let mut out = String::new();
for glyph in glyphs.keys() {
let advance = font.h_advance_unscaled(ab_glyph::GlyphId(*glyph));
let _ = write!(out, "{glyph} [{}] ", (advance * 1000.0 / units).round() as i64);
}
out
}
fn prim_is_finite(prim: &Prim) -> bool {
match prim {
Prim::Rect { rect, .. } => [rect.left(), rect.top(), rect.width(), rect.height()]
.iter()
.all(|value| value.is_finite()),
Prim::Line { points, width, .. } => {
width.is_finite() && points.iter().all(|point| point.x.is_finite() && point.y.is_finite())
}
Prim::Polygon { points, .. } => points.iter().all(|point| point.x.is_finite() && point.y.is_finite()),
Prim::Circle { center, radius, .. } => center.x.is_finite() && center.y.is_finite() && radius.is_finite(),
Prim::Text { pos, size, .. } => pos.x.is_finite() && pos.y.is_finite() && size.is_finite(),
}
}
fn write_prim(out: &mut String, prim: &Prim, page_height: f32, font: &FontRef<'_>, glyphs: &mut BTreeMap<u16, u16>) {
if !prim_is_finite(prim) {
return;
}
match prim {
Prim::Rect { rect, fill, stroke } => {
if !fill.is_transparent() {
fill_color(out, *fill);
write_rect(out, *rect, page_height);
out.push_str("f\n");
}
if let Some((width, color)) = stroke {
stroke_color(out, *color);
let _ = writeln!(out, "{width:.2} w");
write_rect(out, *rect, page_height);
out.push_str("S\n");
}
}
Prim::Line { points, width, color } => {
if points.len() < 2 || color.is_transparent() {
return;
}
stroke_color(out, *color);
let _ = writeln!(out, "{width:.2} w");
path(out, points, page_height, false);
out.push_str("S\n");
}
Prim::Polygon { points, fill, stroke } => {
if points.len() >= 3 && !fill.is_transparent() {
fill_color(out, *fill);
path(out, points, page_height, true);
out.push_str("f\n");
}
if let Some((width, color)) = stroke {
stroke_color(out, *color);
let _ = writeln!(out, "{width:.2} w");
path(out, points, page_height, true);
out.push_str("S\n");
}
}
Prim::Circle {
center,
radius,
fill,
stroke,
} => {
if *radius <= 0.0 {
return;
}
let path = circle(*center, *radius, page_height);
if !fill.is_transparent() {
fill_color(out, *fill);
out.push_str(&path);
out.push_str("f\n");
}
if let Some((width, color)) = stroke {
stroke_color(out, *color);
let _ = writeln!(out, "{width:.2} w");
out.push_str(&path);
out.push_str("S\n");
}
}
Prim::Text {
pos,
text,
size,
color,
anchor,
} => {
if text.is_empty() || color.is_transparent() {
return;
}
let width = text::width(font, text, *size);
let x = match anchor {
Anchor::Left => pos.x,
Anchor::Center => pos.x - width * 0.5,
Anchor::Right => pos.x - width,
};
let baseline = page_height - (pos.y + text::ascent(font, *size));
fill_color(out, *color);
let _ = write!(out, "BT /F1 {size:.2} Tf {x:.2} {baseline:.2} Td <");
for character in text.chars() {
let glyph = font.glyph_id(character).0;
glyphs.insert(glyph, glyph);
let _ = write!(out, "{glyph:04x}");
}
out.push_str("> Tj ET\n");
}
}
}
fn fill_color(out: &mut String, color: Rgba) {
let [r, g, b, a] = color.to_array();
let _ = writeln!(
out,
"{:.4} {:.4} {:.4} rg",
f32::from(channel(r, a)) / 255.0,
f32::from(channel(g, a)) / 255.0,
f32::from(channel(b, a)) / 255.0
);
}
fn stroke_color(out: &mut String, color: Rgba) {
let [r, g, b, a] = color.to_array();
let _ = writeln!(
out,
"{:.4} {:.4} {:.4} RG",
f32::from(channel(r, a)) / 255.0,
f32::from(channel(g, a)) / 255.0,
f32::from(channel(b, a)) / 255.0
);
}
fn channel(value: u8, alpha: u8) -> u8 {
if alpha == 0 {
0
} else {
((u16::from(value) * 255 + u16::from(alpha) / 2) / u16::from(alpha)).min(255) as u8
}
}
fn path(out: &mut String, points: &[ScreenPoint], page_height: f32, close: bool) {
for (index, point) in points.iter().enumerate() {
let _ = write!(
out,
"{:.2} {:.2} {}",
point.x,
page_height - point.y,
if index == 0 { "m" } else { "l" }
);
out.push('\n');
}
if close {
out.push_str("h\n");
}
}
fn write_rect(out: &mut String, rect: ScreenRect, page_height: f32) {
let _ = writeln!(
out,
"{:.2} {:.2} {:.2} {:.2} re",
rect.left(),
page_height - rect.bottom(),
rect.width(),
rect.height()
);
}
fn circle(center: ScreenPoint, radius: f32, page_height: f32) -> String {
let x = center.x;
let y = page_height - center.y;
let r = radius;
let c = KAPPA * r;
format!(
"{:.2} {:.2} m\n{:.2} {:.2} {:.2} {:.2} {:.2} {:.2} c\n{:.2} {:.2} {:.2} {:.2} {:.2} {:.2} c\n{:.2} {:.2} {:.2} {:.2} {:.2} {:.2} c\n{:.2} {:.2} {:.2} {:.2} {:.2} {:.2} c\nh\n",
x + r,
y,
x + r,
y + c,
x + c,
y + r,
x,
y + r,
x - c,
y + r,
x - r,
y + c,
x - r,
y,
x - r,
y - c,
x - c,
y - r,
x,
y - r,
x + c,
y - r,
x + r,
y - c,
x + r,
y
)
}
struct Pdf {
out: Vec<u8>,
offsets: Vec<usize>,
}
impl Pdf {
fn new() -> Self {
Self {
out: b"%PDF-1.4\n%\xe2\xe3\xcf\xd3\n".to_vec(),
offsets: Vec::new(),
}
}
fn object(&mut self, body: &str) {
let number = self.offsets.len() + 1;
self.offsets.push(self.out.len());
self.out
.extend_from_slice(format!("{number} 0 obj\n{body}\nendobj\n").as_bytes());
}
fn stream(&mut self, body: &[u8], extra: &str) {
let number = self.offsets.len() + 1;
self.offsets.push(self.out.len());
let length = body.len();
let extra = extra.replace("{length}", &length.to_string());
let dictionary = if extra.is_empty() {
format!("<< /Length {length} >>")
} else {
format!("<< /Length {length} {extra} >>")
};
self.out
.extend_from_slice(format!("{number} 0 obj\n{dictionary}\nstream\n").as_bytes());
self.out.extend_from_slice(body);
self.out.extend_from_slice(b"\nendstream\nendobj\n");
}
fn finish(mut self) -> Result<Vec<u8>, crate::RenderError> {
let xref = self.out.len();
let count = self.offsets.len() + 1;
let mut table = format!("xref\n0 {count}\n0000000000 65535 f \n");
for offset in &self.offsets {
let _ = writeln!(table, "{offset:010} 00000 n ");
}
self.out.extend_from_slice(table.as_bytes());
let trailer = format!("trailer\n<< /Size {count} /Root 1 0 R >>\nstartxref\n{xref}\n%%EOF\n");
self.out.extend_from_slice(trailer.as_bytes());
Ok(self.out)
}
}