use k2f_core::Rect;
use pdf_writer::{Content, Name};
use std::collections::BTreeSet;
pub struct PageDraw {
pub page_w: f64,
pub page_h: f64,
pub content: Content,
pub notes: String,
pub fill_alphas: BTreeSet<u8>,
}
impl PageDraw {
pub fn new(page_w: f64, page_h: f64) -> Self {
Self {
page_w,
page_h,
content: Content::new(),
notes: String::new(),
fill_alphas: BTreeSet::new(),
}
}
pub fn push_fill_alpha(&mut self, a: u8) -> bool {
if a == 255 {
return false;
}
self.fill_alphas.insert(a);
let name = format!("ca{a}");
self.content.save_state();
self.content.set_parameters(Name(name.as_bytes()));
true
}
pub fn pop_fill_alpha(&mut self, pushed: bool) {
if pushed {
self.content.restore_state();
}
}
pub fn note_box(&mut self, rect: &Rect) {
self.notes.push_str(&format!(
"% k2f.b {:.3} {:.3} {:.3} {:.3}\n",
rect.x.as_f64_pt(),
rect.y.as_f64_pt(),
rect.width.as_f64_pt(),
rect.height.as_f64_pt()
));
}
pub fn note_glyph(&mut self, x: f64, y: f64, gid: u16) {
self.notes
.push_str(&format!("% k2f.g {x:.3} {y:.3} {gid}\n"));
}
pub fn note_decoration(&mut self, x0: f64, y: f64, x1: f64, thickness: f64) {
self.notes
.push_str(&format!("% k2f.d {x0:.3} {y:.3} {x1:.3} {thickness:.3}\n"));
}
pub fn note_image(&mut self, rect: &Rect) {
self.notes.push_str(&format!(
"% k2f.i {:.3} {:.3} {:.3} {:.3}\n",
rect.x.as_f64_pt(),
rect.y.as_f64_pt(),
rect.width.as_f64_pt(),
rect.height.as_f64_pt()
));
}
pub fn finish(self) -> Vec<u8> {
let mut out = self.notes.into_bytes();
out.extend_from_slice(self.content.finish().as_ref());
out
}
}
pub fn parse_notes(content: &[u8]) -> (Vec<[f64; 4]>, Vec<(f64, f64, u16)>, Vec<[f64; 4]>) {
let text = String::from_utf8_lossy(content);
let mut boxes = Vec::new();
let mut glyphs = Vec::new();
let mut images = Vec::new();
for line in text.lines() {
let line = line.trim();
if let Some(rest) = line.strip_prefix("% k2f.b ") {
if let Some(v) = four(rest) {
boxes.push(v);
}
} else if let Some(rest) = line.strip_prefix("% k2f.g ") {
let p: Vec<&str> = rest.split_whitespace().collect();
if p.len() == 3 {
if let (Ok(x), Ok(y), Ok(g)) = (p[0].parse(), p[1].parse(), p[2].parse()) {
glyphs.push((x, y, g));
}
}
} else if let Some(rest) = line.strip_prefix("% k2f.i ") {
if let Some(v) = four(rest) {
images.push(v);
}
}
}
(boxes, glyphs, images)
}
fn four(s: &str) -> Option<[f64; 4]> {
let p: Vec<&str> = s.split_whitespace().collect();
if p.len() != 4 {
return None;
}
Some([
p[0].parse().ok()?,
p[1].parse().ok()?,
p[2].parse().ok()?,
p[3].parse().ok()?,
])
}