use std::borrow::Cow;
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::fmt::Write as _;
use std::hash::{Hash, Hasher};
use std::io::Write;
use flate2::Compression;
use flate2::write::ZlibEncoder;
use super::PdfOptions;
use super::font::{FaceId, FaceRef, Fonts, word_device_paint, word_device_track};
pub(crate) enum Op {
Text {
face: FaceRef,
size: f32,
x: f32,
y: f32,
glyphs: Vec<u16>,
color: [f32; 3],
text: String,
hscale: f32,
hidden: bool,
},
Line {
x1: f32,
y1: f32,
x2: f32,
y2: f32,
width: f32,
color: [f32; 3],
},
FillRect {
x: f32,
y: f32,
w: f32,
h: f32,
color: [f32; 3],
},
StrokeRect {
x: f32,
y: f32,
w: f32,
h: f32,
width: f32,
color: [f32; 3],
},
FillPoly {
points: Vec<(f32, f32)>,
color: [f32; 3],
},
StrokePoly {
points: Vec<(f32, f32)>,
width: f32,
color: [f32; 3],
},
FillPath {
contours: Vec<Vec<(f32, f32)>>,
color: [f32; 3],
even_odd: bool,
},
StrokePath {
subpaths: Vec<(Vec<(f32, f32)>, bool)>,
width: f32,
color: [f32; 3],
},
Cubic {
start: (f32, f32),
segments: Vec<[(f32, f32); 3]>,
width: f32,
color: [f32; 3],
},
Jpeg {
x: f32,
y: f32,
dw: f32,
dh: f32,
width: u32,
height: u32,
bytes: Vec<u8>,
components: u8,
crop: Option<[f32; 4]>,
rotate_deg: f32,
oval: bool,
},
Rgb {
x: f32,
y: f32,
dw: f32,
dh: f32,
width: u32,
height: u32,
bytes: Vec<u8>,
alpha: Option<Vec<u8>>,
crop: Option<[f32; 4]>,
rotate_deg: f32,
oval: bool,
},
Pin(bool),
Watermark {
face: FaceRef,
size: f32,
x: f32,
y: f32,
glyphs: Vec<u16>,
color: [f32; 3],
text: String,
rotate_deg: f32,
},
}
#[derive(Clone)]
pub(crate) struct PdfComment {
pub id: String,
pub x: f32,
pub y: f32,
pub w: f32,
pub h: f32,
pub top: f32,
pub bottom: f32,
pub contents: String,
pub author: String,
pub initials: String,
pub label: String,
pub color: [f32; 3],
pub resolved: bool,
}
pub(crate) struct CommentTint {
pub id: String,
pub x: f32,
pub y: f32,
pub w: f32,
pub h: f32,
}
pub(crate) struct Page {
pub ops: Vec<Op>,
pub width: f32,
pub height: f32,
pub comments: Vec<PdfComment>,
pub tints: Vec<CommentTint>,
pub markup_pane: bool,
pub margin_r: f32,
pub vertical: bool,
pub changed: bool,
pub number: usize,
pub chrome_changed: bool,
pub section: u32,
}
impl Page {
pub(crate) fn new(width: f32, height: f32) -> Self {
Self {
ops: Vec::new(),
width,
height,
comments: Vec::new(),
tints: Vec::new(),
markup_pane: false,
margin_r: 0.0,
vertical: false,
changed: false,
number: 0,
chrome_changed: false,
section: 0,
}
}
}
#[derive(Clone, Copy)]
pub(crate) struct MarkupChrome {
pub(crate) gx: f32,
pub(crate) gy: f32,
pub(crate) gw: f32,
pub(crate) gh: f32,
pub(crate) k: f32,
pub(crate) tx: f32,
pub(crate) ty: f32,
}
const MARKUP_PANE_W: f32 = 257.3;
const MARKUP_PANE_GAP: f32 = 9.15;
const MARKUP_FIT_INSET: f32 = 8.64;
const MARKUP_FIT_SPAN: f32 = 265.68;
const MARKUP_FIT_DROP: f32 = 0.54;
const MARKUP_PANE_TABLE: &[(u32, u32, u32, u32, u32)] = &[
(2480, 3508, 189, 215, 494),
(2480, 3508, 236, 218, 476),
(2480, 3508, 300, 223, 452),
(2480, 3508, 319, 224, 444),
(2480, 3508, 354, 226, 430),
(2480, 3508, 374, 228, 422),
(2480, 3508, 501, 237, 367),
(2550, 3300, 225, 219, 443),
(2550, 3300, 295, 224, 417),
(2550, 3300, 300, 224, 416),
(2550, 3300, 375, 229, 388),
(2550, 3300, 450, 235, 358),
(2479, 3508, 302, 223, 451),
(3508, 2480, 300, 241, 244),
];
pub(crate) fn markup_chrome(width: f32, height: f32, margin_r: f32) -> Option<MarkupChrome> {
let span = width - margin_r + MARKUP_PANE_GAP + MARKUP_PANE_W;
if span <= 0.0 {
return None;
}
let px = |pt: f32| (pt * 300.0 / 72.0).round() as u32;
let known = MARKUP_PANE_TABLE
.iter()
.find(|row| row.0 == px(width) && row.1 == px(height) && row.2 == px(margin_r));
let exact = (width - MARKUP_FIT_INSET) / (width - margin_r + MARKUP_FIT_SPAN);
let k = known.map_or((exact * 300.0).floor() / 300.0, |row| row.3 as f32 / 300.0);
let tx = 0.96;
let gh = height * k;
let top = known.map_or(
((height * (1.0 - exact) / 2.0 + MARKUP_FIT_DROP) / 0.24).floor() * 0.24,
|row| row.4 as f32 * 0.24,
);
let ty = height - top - gh;
Some(MarkupChrome {
gx: tx + (width - margin_r + MARKUP_PANE_GAP) * k,
gy: ty,
gw: MARKUP_PANE_W * k,
gh,
k,
tx,
ty,
})
}
impl Op {
pub(crate) fn shift_y(&mut self, dy: f32) {
match self {
Op::Text { y, .. }
| Op::FillRect { y, .. }
| Op::StrokeRect { y, .. }
| Op::Jpeg { y, .. }
| Op::Rgb { y, .. }
| Op::Watermark { y, .. } => *y += dy,
Op::Line { y1, y2, .. } => {
*y1 += dy;
*y2 += dy;
}
Op::FillPoly { points, .. } | Op::StrokePoly { points, .. } => {
points.iter_mut().for_each(|p| p.1 += dy);
}
Op::FillPath { contours, .. } => contours.iter_mut().flatten().for_each(|p| p.1 += dy),
Op::StrokePath { subpaths, .. } => subpaths
.iter_mut()
.flat_map(|(pts, _)| pts.iter_mut())
.for_each(|p| p.1 += dy),
Op::Cubic {
start, segments, ..
} => {
start.1 += dy;
segments.iter_mut().flatten().for_each(|p| p.1 += dy);
}
Op::Pin(_) => {}
}
}
pub(crate) fn text(
face: impl Into<FaceRef>,
size: f32,
x: f32,
y: f32,
glyphs: Vec<u16>,
color: [f32; 3],
text: impl Into<String>,
) -> Self {
Self::Text {
face: face.into(),
size,
x,
y,
glyphs,
color,
text: text.into(),
hscale: 1.0,
hidden: false,
}
}
pub(crate) fn hidden(mut self) -> Self {
if let Self::Text { hidden, .. } = &mut self {
*hidden = true;
}
self
}
pub(crate) fn scaled(mut self, scale: f32) -> Self {
if let Self::Text { hscale, .. } = &mut self {
*hscale = scale;
}
self
}
}
pub(crate) fn emit<P: std::borrow::Borrow<Page>>(
fonts: &Fonts,
pages: &[P],
options: PdfOptions,
) -> Vec<u8> {
let pages: Vec<&Page> = pages.iter().map(std::borrow::Borrow::borrow).collect();
let pages = pages.as_slice();
let used: Vec<FaceRef> = {
let mut seen = Vec::new();
for page in pages {
for op in &page.ops {
if let Op::Text { face, .. } | Op::Watermark { face, .. } = op
&& !seen.contains(face)
{
seen.push(*face);
}
}
}
if seen.is_empty() {
seen.push(FaceRef::Catalogue(FaceId::CarlitoRegular));
}
seen
};
let mut objs: Vec<Vec<u8>> = vec![Vec::new(), Vec::new(), Vec::new()];
let mut simple_need = Vec::new();
let mut cid_need = Vec::new();
let mut encodings: Vec<Vec<Option<Vec<u8>>>> = Vec::with_capacity(pages.len());
for page in pages {
let mut page_enc: Vec<Option<Vec<u8>>> = Vec::with_capacity(page.ops.len());
for op in &page.ops {
let mut enc = None;
if let Op::Text {
face, glyphs, text, ..
}
| Op::Watermark {
face, glyphs, text, ..
} = op
{
let cmap_match = text
.chars()
.zip(glyphs.iter())
.all(|(ch, &gid)| fonts.get(*face).glyph(ch) == gid);
if text.chars().count() == glyphs.len() && cmap_match {
enc = winansi_bytes(text);
}
if enc.is_some() {
if !simple_need.contains(face) {
simple_need.push(*face);
}
} else if !cid_need.contains(face) {
cid_need.push(*face);
}
}
page_enc.push(enc);
}
encodings.push(page_enc);
}
if simple_need.is_empty() && cid_need.is_empty() {
cid_need.push(FaceRef::Catalogue(FaceId::CarlitoRegular));
}
let mut simple_obj = FaceObjIds::new();
let mut cid_obj = FaceObjIds::new();
let mut taken: Vec<String> = Vec::new();
for face_id in &used {
let face = fonts.get(*face_id);
let want_simple = simple_need.contains(face_id);
let want_cid = cid_need.contains(face_id);
if !want_simple && !want_cid {
continue;
}
let file_id = objs.len() + 1;
let used_gids = face_used_glyphs(face, *face_id, pages);
let program = subset_keep_gids(face.bytes(), &used_gids);
objs.push(font_file_obj(
program.as_deref().unwrap_or(face.bytes()),
true,
));
let desc_id = objs.len() + 1;
objs.push(font_descriptor_obj(face, file_id));
if want_simple {
let id = objs.len() + 1;
objs.push(simple_ttf_obj(face, desc_id));
let name = uniquify(face.pdf_name(), &mut taken);
simple_obj.insert(*face_id, id, name);
}
if want_cid {
let cid_id = objs.len() + 1;
objs.push(cid_font_obj(face, desc_id, &used_gids));
let cmap_id = objs.len() + 1;
objs.push(to_unicode_obj(
&face_unicode_map(face, *face_id, pages),
options.compress,
));
let type0_id = objs.len() + 1;
objs.push(type0_font_obj(face, cid_id, cmap_id));
let base = if want_simple {
format!("{}CID", face.pdf_name())
} else {
face.pdf_name().to_string()
};
let name = uniquify(&base, &mut taken);
cid_obj.insert(*face_id, type0_id, name);
}
}
let mut image_objs: HashMap<u64, Vec<usize>> = HashMap::new();
let mut intern = |objs: &mut Vec<Vec<u8>>, obj: Vec<u8>| -> usize {
let mut h = std::collections::hash_map::DefaultHasher::new();
obj.hash(&mut h);
let ids = image_objs.entry(h.finish()).or_default();
if let Some(&id) = ids.iter().find(|&&id| objs[id - 1] == obj) {
return id;
}
objs.push(obj);
ids.push(objs.len());
objs.len()
};
type RawImage<'p> = (u32, u32, &'p [u8], Option<&'p [u8]>);
let mut rgb_ids: HashMap<u64, Vec<(RawImage<'_>, usize)>> = HashMap::new();
let mut page_ids = Vec::new();
for (page_idx, page) in pages.iter().enumerate() {
let page_enc = &encodings[page_idx];
let mut xobjects = String::new();
let mut img_n = 0usize;
let mut has_watermark = false;
for op in &page.ops {
match op {
Op::Jpeg {
width,
height,
bytes,
components,
..
} => {
img_n += 1;
let id = intern(&mut objs, jpeg_xobject(*width, *height, bytes, *components));
let _ = write!(xobjects, "/Im{img_n} {id} 0 R ");
}
Op::Rgb {
width,
height,
bytes,
alpha,
..
} => {
img_n += 1;
let raw: RawImage<'_> = (*width, *height, bytes, alpha.as_deref());
let mut h = std::collections::hash_map::DefaultHasher::new();
raw.hash(&mut h);
let seen = rgb_ids.entry(h.finish()).or_default();
let id = match seen.iter().find(|(r, _)| *r == raw) {
Some((_, id)) => *id,
None => {
let smask = alpha.as_ref().map(|plane| {
intern(&mut objs, gray_xobject(*width, *height, plane, true))
});
let id =
intern(&mut objs, rgb_xobject(*width, *height, bytes, true, smask));
seen.push((raw, id));
id
}
};
let _ = write!(xobjects, "/Im{img_n} {id} 0 R ");
}
Op::Watermark { .. } => has_watermark = true,
_ => {}
}
}
let mut stream = String::new();
let markup = page
.markup_pane
.then(|| markup_chrome(page.width, page.height, page.margin_r))
.flatten();
if page.vertical {
let _ = writeln!(stream, "q 0 -1 1 0 0 {:.2} cm", page.width);
}
if let Some(m) = markup {
let _ = writeln!(
stream,
"0.949 0.949 0.949 rg {x:.2} {y:.2} {w:.2} {h:.2} re f\n\
q {k:.4} 0 0 {k:.4} {tx:.2} {ty:.2} cm",
x = m.gx,
y = m.gy,
w = m.gw,
h = m.gh,
k = m.k,
tx = m.tx,
ty = m.ty,
);
}
let res_for = |face: FaceRef, winansi: bool| -> Option<(usize, &str)> {
if winansi {
simple_obj.get(face).or_else(|| cid_obj.get(face))
} else {
cid_obj.get(face).or_else(|| simple_obj.get(face))
}
};
let mut page_faces: Vec<(usize, &str)> = Vec::new();
for (op_idx, op) in page.ops.iter().enumerate() {
let (Op::Text { face, glyphs, .. } | Op::Watermark { face, glyphs, .. }) = op else {
continue;
};
if glyphs.is_empty() {
continue;
}
if let Some(entry) = res_for(*face, page_enc[op_idx].is_some())
&& !page_faces.iter().any(|(_, name)| *name == entry.1)
{
page_faces.push(entry);
}
}
let mut font_res = String::new();
for (obj_id, name) in &page_faces {
let _ = write!(font_res, "/{name} {obj_id} 0 R ");
}
let mut img_counter = 0usize;
let mut open_text: Option<(String, i64, i64)> = None;
let mut last_state: Option<(String, TextStateBits, String)> = None;
for (op_idx, op) in page.ops.iter().enumerate() {
let plain_text = matches!(op, Op::Text { .. }) && !page.vertical;
if !plain_text && open_text.take().is_some() {
stream.push_str("ET\n");
}
match op {
Op::Text {
face,
size,
x,
y,
glyphs,
color,
text,
hscale,
hidden,
} => {
if *hidden {
if open_text.take().is_some() {
stream.push_str("ET\n");
}
let encoded = page_enc[op_idx].as_deref();
let Some((_, name)) = res_for(*face, encoded.is_some()) else {
continue;
};
let show = Show {
lit: encoded.map_or(Lit::Glyphs(glyphs), Lit::Bytes),
actual: Some(text),
};
let _ = writeln!(
stream,
"q BT /{name} {size:.2} Tf 3 Tr {x:.2} {y:.2} Td {show} ET Q"
);
continue;
}
if page.vertical
&& text.chars().any(stands_upright)
&& text.chars().count() == glyphs.len()
&& let Some((_, name)) = res_for(*face, false)
{
let f = fonts.get(*face);
let (r, g, b) = (color[0], color[1], color[2]);
let squeeze = if (*hscale - 1.0).abs() > 0.001 {
format!("{:.4} 0 0 1 0 0 cm ", *hscale)
} else {
String::new()
};
let mut gx = *x;
for (ch, gid) in text.chars().zip(glyphs.iter()) {
let adv = f.advance_pt(ch, *size) * *hscale;
let mut utf8 = [0; 4];
let show = Show::new(
f,
std::slice::from_ref(gid),
None,
ch.encode_utf8(&mut utf8),
);
if stands_upright(ch) {
let (cx, cy) = (gx + adv / 2.0, *y + 0.38 * size);
let lift = if matches!(ch, '、' | '。' | ',' | '.') {
0.55 * size
} else {
0.0
};
let _ = writeln!(
stream,
"q 1 0 0 1 {cx:.2} {cy:.2} cm {squeeze}0 1 -1 0 0 0 cm BT /{name} {size:.2} Tf \
{r:.3} {g:.3} {b:.3} rg {ox:.2} {oy:.2} Td {show} ET Q",
ox = lift - adv / 2.0,
oy = lift - 0.38 * size,
);
} else if squeeze.is_empty() {
let _ = writeln!(
stream,
"BT /{name} {size:.2} Tf {r:.3} {g:.3} {b:.3} rg {gx:.2} {y:.2} Td {show} ET",
);
} else {
let _ = writeln!(
stream,
"q 1 0 0 1 {gx:.2} {y:.2} cm {squeeze}BT /{name} {size:.2} Tf \
{r:.3} {g:.3} {b:.3} rg 0 0 Td {show} ET Q",
);
}
gx += adv;
}
continue;
}
if glyphs.is_empty() {
continue;
}
let encoded = page_enc[op_idx].as_deref();
let Some((_, name)) = res_for(*face, encoded.is_some()) else {
continue;
};
let show = Show::new(fonts.get(*face), glyphs, encoded, text);
let (r, g, b) = (color[0], color[1], color[2]);
let sx = *hscale;
if (word_device_paint(*size).is_some() || (sx - 1.0).abs() > 0.001)
&& open_text.take().is_some()
{
stream.push_str("ET\n");
}
if let Some((ppem, tc)) = word_device_paint(*size) {
let down = page.height - *y;
let y = &(page.height - ((down / 0.24) + 0.5).floor() * 0.24);
let a = if (sx - 1.0).abs() > 0.001 {
format!("{:.4}", 0.24 * sx)
} else {
"0.24".into()
};
let _ = writeln!(
stream,
"q {a} 0 0 0.24 {x:.2} {y:.2} cm BT /{name} {ppem:.0} Tf {r:.3} {g:.3} {b:.3} rg {tc:.4} Tc 0 0 Td {show} ET Q",
);
} else if (sx - 1.0).abs() > 0.001 {
let _ = writeln!(
stream,
"q {sx:.4} 0 0 1 {x:.2} {y:.2} cm BT /{name} {size:.2} Tf {r:.3} {g:.3} {b:.3} rg 0 0 Td {show} ET Q",
);
} else {
let tc = word_device_track(*size);
let tc_op = if tc.abs() > 0.00005 {
format!("{tc:.5} Tc ")
} else {
String::new()
};
let bits = (
size.to_bits(),
[r.to_bits(), g.to_bits(), b.to_bits()],
tc.to_bits(),
);
let state = match &last_state {
Some((seen_name, seen, text)) if seen_name == name && *seen == bits => {
text.clone()
}
_ => {
let text =
format!("/{name} {size:.2} Tf {r:.3} {g:.3} {b:.3} rg {tc_op}");
last_state = Some((name.to_string(), bits, text.clone()));
text
}
};
let (hx, hy) = (hundredths(*x), hundredths(*y));
match open_text.as_mut() {
Some((open, px, py)) if *open == state => {
push_hundredths(&mut stream, hx - *px);
stream.push(' ');
push_hundredths(&mut stream, hy - *py);
let _ = writeln!(stream, " Td {show}");
(*px, *py) = (hx, hy);
}
_ => {
if open_text.take().is_some() {
stream.push_str("ET\n");
}
let _ = writeln!(stream, "BT {state}{x:.2} {y:.2} Td {show}");
open_text = Some((state, hx, hy));
}
}
}
}
Op::Watermark {
face,
size,
x,
y,
glyphs,
color,
text,
rotate_deg,
} => {
if glyphs.is_empty() {
continue;
}
let rad = rotate_deg.to_radians();
let (sin, cos) = (rad.sin(), rad.cos());
let width = fonts.get(*face).width_pt(text, *size);
let dx = -width / 2.0;
let dy = -size * 0.35;
let encoded = page_enc[op_idx].as_deref();
let show = Show::new(fonts.get(*face), glyphs, encoded, text);
let Some((_, name)) = res_for(*face, encoded.is_some()) else {
continue;
};
let _ = writeln!(
stream,
"q /WmGs gs 1 0 0 1 {x:.2} {y:.2} cm {cos:.4} {sin:.4} {nsin:.4} {cos:.4} 0 0 cm \
BT /{name} {size:.2} Tf {r:.3} {g:.3} {b:.3} rg {dx:.2} {dy:.2} Td {show} ET Q",
nsin = -sin,
r = color[0],
g = color[1],
b = color[2],
);
}
Op::Pin(_) => {}
Op::Line {
x1,
y1,
x2,
y2,
width,
color,
} => {
let _ = writeln!(
stream,
"{w:.2} w {r:.3} {g:.3} {b:.3} RG {x1:.2} {y1:.2} m {x2:.2} {y2:.2} l S",
w = width,
r = color[0],
g = color[1],
b = color[2],
);
}
Op::FillRect { x, y, w, h, color } => {
let _ = writeln!(
stream,
"{r:.3} {g:.3} {b:.3} rg {x:.2} {y:.2} {w:.2} {h:.2} re f",
r = color[0],
g = color[1],
b = color[2],
);
}
Op::StrokeRect {
x,
y,
w,
h,
width,
color,
} => {
let _ = writeln!(
stream,
"{lw:.2} w {r:.3} {g:.3} {b:.3} RG {x:.2} {y:.2} {w:.2} {h:.2} re S",
lw = width,
r = color[0],
g = color[1],
b = color[2],
);
}
Op::FillPoly { points, color } => {
if let Some((x0, y0)) = points.first() {
let _ = write!(
stream,
"{r:.3} {g:.3} {b:.3} rg {x0:.2} {y0:.2} m",
r = color[0],
g = color[1],
b = color[2],
);
for (x, y) in points.iter().skip(1) {
let _ = write!(stream, " {x:.2} {y:.2} l");
}
stream.push_str(" h f\n");
}
}
Op::FillPath {
contours,
color,
even_odd,
} => {
let mut body = String::new();
for c in contours.iter().filter(|c| c.len() >= 2) {
for (i, (x, y)) in c.iter().enumerate() {
let _ =
write!(body, " {x:.2} {y:.2} {}", if i == 0 { 'm' } else { 'l' });
}
body.push_str(" h");
}
if !body.is_empty() {
let _ = writeln!(
stream,
"{r:.3} {g:.3} {b:.3} rg{body} {op}",
r = color[0],
g = color[1],
b = color[2],
op = if *even_odd { "f*" } else { "f" },
);
}
}
Op::StrokePath {
subpaths,
width,
color,
} => {
let mut body = String::new();
for (pts, closed) in subpaths.iter().filter(|(p, _)| p.len() >= 2) {
for (i, (x, y)) in pts.iter().enumerate() {
let _ =
write!(body, " {x:.2} {y:.2} {}", if i == 0 { 'm' } else { 'l' });
}
if *closed {
body.push_str(" h");
}
}
if !body.is_empty() {
let _ = writeln!(
stream,
"{w:.2} w {r:.3} {g:.3} {b:.3} RG{body} S",
w = width,
r = color[0],
g = color[1],
b = color[2],
);
}
}
Op::StrokePoly {
points,
width,
color,
} => {
if let Some((x0, y0)) = points.first() {
let _ = write!(
stream,
"{w:.2} w {r:.3} {g:.3} {b:.3} RG {x0:.2} {y0:.2} m",
w = width,
r = color[0],
g = color[1],
b = color[2],
);
for (x, y) in points.iter().skip(1) {
let _ = write!(stream, " {x:.2} {y:.2} l");
}
stream.push_str(" h S\n");
}
}
Op::Cubic {
start,
segments,
width,
color,
} => {
let _ = write!(
stream,
"{w:.2} w {r:.3} {g:.3} {b:.3} RG {x:.2} {y:.2} m",
w = width,
r = color[0],
g = color[1],
b = color[2],
x = start.0,
y = start.1,
);
for [(c1x, c1y), (c2x, c2y), (ex, ey)] in segments {
let _ = write!(
stream,
" {c1x:.2} {c1y:.2} {c2x:.2} {c2y:.2} {ex:.2} {ey:.2} c"
);
}
stream.push_str(" S\n");
}
Op::Jpeg {
x,
y,
dw,
dh,
crop,
rotate_deg,
oval,
..
}
| Op::Rgb {
x,
y,
dw,
dh,
crop,
rotate_deg,
oval,
..
} => {
img_counter += 1;
stream.push_str(&paint_picture(
[*x, *y, *dw, *dh],
*crop,
img_counter,
*rotate_deg,
*oval,
));
}
}
}
if open_text.take().is_some() {
stream.push_str("ET\n");
}
if markup.is_some() {
stream.push_str("Q\n");
}
if page.vertical {
stream.push_str("Q\n");
}
let content_id = objs.len() + 1;
objs.push(stream_object(&stream, options.compress));
let mut annot_refs = String::new();
let sticky: &[PdfComment] = if options.comment_notes {
&page.comments
} else {
&[]
};
for note in sticky {
let id = objs.len() + 1;
let scaled = markup.map(|m| PdfComment {
x: m.k * note.x + m.tx,
y: m.k * note.y + m.ty,
w: note.w * m.k,
h: note.h * m.k,
..note.clone()
});
let note = scaled.as_ref().unwrap_or(note);
let turned = page.vertical.then(|| PdfComment {
x: note.y,
y: page.width - note.x - note.w,
w: note.h,
h: note.w,
..note.clone()
});
objs.push(text_annot_obj(turned.as_ref().unwrap_or(note)));
let _ = write!(annot_refs, "{id} 0 R ");
}
let annots = if annot_refs.is_empty() {
String::new()
} else {
format!(" /Annots [{annot_refs}]")
};
let page_id = objs.len() + 1;
page_ids.push(page_id);
let ext_gstate = if has_watermark {
" /ExtGState << /WmGs << /Type /ExtGState /ca 0.5 >> >>"
} else {
""
};
objs.push(
format!(
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {w:.2} {h:.2}] \
/Contents {content_id} 0 R \
/Resources << /Font << {font_res} >> /XObject << {xobjects} >>{ext_gstate} >>{annots} >>",
w = if page.vertical { page.height } else { page.width },
h = if page.vertical { page.width } else { page.height },
)
.into_bytes(),
);
}
objs[0] = b"<< /Type /Catalog /Pages 2 0 R >>".to_vec();
let kids = page_ids
.iter()
.map(|id| format!("{id} 0 R"))
.collect::<Vec<_>>()
.join(" ");
objs[1] = format!(
"<< /Type /Pages /Kids [{kids}] /Count {n} >>",
n = page_ids.len()
)
.into_bytes();
objs[2] = b"<< /Producer (jubarte) /Creator (jubarte) >>".to_vec();
finalize_pdf(&objs)
}
fn uniquify(base: &str, taken: &mut Vec<String>) -> String {
let mut name = base.to_string();
let mut n = 1u32;
while taken.contains(&name) {
n += 1;
name = format!("{base}-{n}");
}
taken.push(name.clone());
name
}
struct FaceObjIds {
items: Vec<(FaceRef, usize, String)>,
}
impl FaceObjIds {
fn new() -> Self {
Self { items: Vec::new() }
}
fn insert(&mut self, k: FaceRef, obj_id: usize, res_name: String) {
self.items.push((k, obj_id, res_name));
}
fn get(&self, k: FaceRef) -> Option<(usize, &str)> {
self.items
.iter()
.find(|(id, _, _)| *id == k)
.map(|(_, obj_id, name)| (*obj_id, name.as_str()))
}
}
fn face_used_glyphs(face: &super::font::Face, id: FaceRef, pages: &[&Page]) -> BTreeSet<u16> {
let parsed = ttf_parser::Face::parse(face.bytes(), 0).ok();
let mut used = BTreeSet::from([0u16]);
for page in pages {
for op in &page.ops {
if let Op::Text {
face, glyphs, text, ..
}
| Op::Watermark {
face, glyphs, text, ..
} = op
&& *face == id
{
used.extend(glyphs.iter().copied());
if let Some(parsed) = &parsed {
used.extend(
text.chars()
.filter_map(|c| parsed.glyph_index(c))
.map(|g| g.0),
);
}
}
}
}
used
}
const SUBSET_TABLES: &[&[u8; 4]] = &[
b"OS/2", b"cmap", b"cvt ", b"fpgm", b"glyf", b"head", b"hhea", b"hmtx", b"loca", b"maxp",
b"name", b"post", b"prep",
];
fn subset_keep_gids(ttf: &[u8], used: &BTreeSet<u16>) -> Option<Vec<u8>> {
let u16_at = |b: &[u8], at: usize| -> Option<u16> {
b.get(at..at + 2).map(|x| u16::from_be_bytes([x[0], x[1]]))
};
let u32_at = |b: &[u8], at: usize| -> Option<u32> {
b.get(at..at + 4)
.map(|x| u32::from_be_bytes([x[0], x[1], x[2], x[3]]))
};
let dir = if ttf.get(..4)? == b"ttcf" {
usize::try_from(u32_at(ttf, 12)?).ok()?
} else {
0
};
let num_tables = usize::from(u16_at(ttf, dir + 4)?);
let mut tables: Vec<([u8; 4], &[u8])> = Vec::with_capacity(num_tables);
for t in 0..num_tables {
let rec = dir + 12 + 16 * t;
let tag: [u8; 4] = ttf.get(rec..rec + 4)?.try_into().ok()?;
let offset = usize::try_from(u32_at(ttf, rec + 8)?).ok()?;
let length = usize::try_from(u32_at(ttf, rec + 12)?).ok()?;
tables.push((tag, ttf.get(offset..offset + length)?));
}
let table = |tag: &[u8; 4]| tables.iter().find(|(t, _)| t == tag).map(|(_, d)| *d);
let head = table(b"head")?;
let glyf = table(b"glyf")?;
let loca = table(b"loca")?;
let num_glyphs = usize::from(u16_at(table(b"maxp")?, 4)?);
let long = u16_at(head, 50)? != 0;
let offset_of = |g: usize| -> Option<usize> {
if long {
usize::try_from(u32_at(loca, 4 * g)?).ok()
} else {
Some(usize::from(u16_at(loca, 2 * g)?) * 2)
}
};
let glyph = |g: usize| -> Option<&[u8]> { glyf.get(offset_of(g)?..offset_of(g + 1)?) };
let mut keep: BTreeSet<usize> = BTreeSet::new();
let mut stack: Vec<usize> = used.iter().map(|g| usize::from(*g)).collect();
while let Some(g) = stack.pop() {
if g >= num_glyphs || !keep.insert(g) {
continue;
}
let data = glyph(g)?;
if data.len() < 10 || i16::from_be_bytes([data[0], data[1]]) >= 0 {
continue;
}
let mut at = 10;
loop {
let flags = u16_at(data, at)?;
stack.push(usize::from(u16_at(data, at + 2)?));
at += 4 + if flags & 0x0001 != 0 { 4 } else { 2 };
at += if flags & 0x0008 != 0 {
2
} else if flags & 0x0040 != 0 {
4
} else if flags & 0x0080 != 0 {
8
} else {
0
};
if flags & 0x0020 == 0 {
break;
}
}
}
let mut new_glyf: Vec<u8> = Vec::new();
let mut new_loca: Vec<u8> = Vec::with_capacity(4 * (num_glyphs + 1));
for g in 0..num_glyphs {
new_loca.extend_from_slice(&u32::try_from(new_glyf.len()).ok()?.to_be_bytes());
if keep.contains(&g) {
new_glyf.extend_from_slice(glyph(g)?);
while !new_glyf.len().is_multiple_of(4) {
new_glyf.push(0);
}
}
}
new_loca.extend_from_slice(&u32::try_from(new_glyf.len()).ok()?.to_be_bytes());
let mut new_head = head.to_vec();
new_head.get_mut(8..12)?.copy_from_slice(&[0; 4]);
new_head
.get_mut(50..52)?
.copy_from_slice(&1u16.to_be_bytes());
let mut new_hmtx = table(b"hmtx")?.to_vec();
let long_metrics = usize::from(u16_at(table(b"hhea")?, 34)?);
for g in (0..num_glyphs).filter(|g| !keep.contains(g)) {
let (at, len) = if g < long_metrics {
(4 * g, 4)
} else {
(4 * long_metrics + 2 * (g - long_metrics), 2)
};
if let Some(entry) = new_hmtx.get_mut(at..at + len) {
entry.fill(0);
}
}
let parsed = ttf_parser::Face::parse(ttf, 0).ok();
let mut new_cmap = parsed.as_ref().and_then(|f| subset_cmap(f, &keep));
let mut new_name = parsed.as_ref().and_then(postscript_name_table);
let mut new_post = table(b"post").and_then(|p| p.get(..32)).map(|p| {
let mut p = p.to_vec();
p[..4].copy_from_slice(&0x0003_0000u32.to_be_bytes());
p
});
let mut out_tables: Vec<([u8; 4], Cow<'_, [u8]>)> = Vec::new();
for (tag, data) in &tables {
if !SUBSET_TABLES.contains(&tag) {
continue;
}
let data: Cow<'_, [u8]> = match tag {
b"glyf" => Cow::Owned(std::mem::take(&mut new_glyf)),
b"loca" => Cow::Owned(std::mem::take(&mut new_loca)),
b"head" => Cow::Owned(std::mem::take(&mut new_head)),
b"hmtx" => Cow::Owned(std::mem::take(&mut new_hmtx)),
b"post" => new_post.take().map_or(Cow::Borrowed(*data), Cow::Owned),
b"cmap" => new_cmap.take().map_or(Cow::Borrowed(*data), Cow::Owned),
b"name" => new_name.take().map_or(Cow::Borrowed(*data), Cow::Owned),
_ => Cow::Borrowed(*data),
};
out_tables.push((*tag, data));
}
out_tables.sort_by_key(|a| a.0);
Some(write_sfnt(u32_at(ttf, dir)?, &out_tables))
}
fn hundredths(v: f32) -> i64 {
if v.abs() < 1.0e7 {
return (f64::from(v) * 100.0).round_ties_even() as i64;
}
let printed = format!("{v:.2}");
let (whole, frac) = printed.split_once('.').unwrap_or((&printed, "0"));
let negative = whole.starts_with('-');
let magnitude = whole.trim_start_matches('-').parse::<i64>().unwrap_or(0) * 100
+ frac.parse::<i64>().unwrap_or(0);
if negative { -magnitude } else { magnitude }
}
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
fn fmt_hundredths(h: i64) -> String {
let mut out = String::new();
push_hundredths(&mut out, h);
out
}
fn push_hundredths(out: &mut String, h: i64) {
if h < 0 {
out.push('-');
}
let (whole, frac) = (h.unsigned_abs() / 100, h.unsigned_abs() % 100);
let _ = write!(out, "{whole}");
if frac != 0 {
out.push('.');
out.push(char::from(b'0' + (frac / 10) as u8));
if frac % 10 != 0 {
out.push(char::from(b'0' + (frac % 10) as u8));
}
}
}
type TextStateBits = (u32, [u32; 3], u32);
struct Show<'a> {
lit: Lit<'a>,
actual: Option<&'a str>,
}
enum Lit<'a> {
Glyphs(&'a [u16]),
Bytes(&'a [u8]),
}
impl<'a> Show<'a> {
fn new(
face: &super::font::Face,
glyphs: &'a [u16],
encoded: Option<&'a [u8]>,
text: &'a str,
) -> Self {
if let Some(bytes) = encoded {
return Self {
lit: Lit::Bytes(bytes),
actual: None,
};
}
let notdef = glyphs.contains(&0) && text.chars().any(|c| !c.is_whitespace());
let stood_in = || {
text.chars()
.any(|c| matches!(c, '\u{210E}' | '\u{1D400}'..='\u{1D7FF}') && face.glyph(c) == 0)
};
Self {
lit: Lit::Glyphs(glyphs),
actual: (notdef || stood_in()).then_some(text),
}
}
}
impl std::fmt::Display for Show<'_> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
if let Some(text) = self.actual {
write!(f, "/Span <</ActualText {}>> BDC ", pdf_text_string(text))?;
}
match self.lit {
Lit::Glyphs(glyphs) => {
const HEX: &[u8; 16] = b"0123456789ABCDEF";
f.write_char('<')?;
for g in glyphs {
for shift in [12, 8, 4, 0] {
f.write_char(char::from(HEX[usize::from((g >> shift) & 0xF)]))?;
}
}
f.write_str("> Tj")?;
}
Lit::Bytes(bytes) => write!(f, "{} Tj", pdf_literal(bytes))?,
}
if self.actual.is_some() {
f.write_str(" EMC")?;
}
Ok(())
}
}
fn subset_cmap(face: &ttf_parser::Face<'_>, keep: &BTreeSet<usize>) -> Option<Vec<u8>> {
let mut map: BTreeMap<u16, u16> = BTreeMap::new();
let mut unicode = false;
for sub in face.tables().cmap?.subtables {
if !sub.is_unicode() {
continue;
}
unicode = true;
sub.codepoints(|cp| {
if let (Ok(cp), Some(g)) = (u16::try_from(cp), sub.glyph_index(cp))
&& cp != 0xFFFF
&& keep.contains(&usize::from(g.0))
{
map.entry(cp).or_insert(g.0);
}
});
}
if !unicode {
return None;
}
let mut segs: Vec<(u16, u16, u16)> = Vec::new();
for (&cp, &g) in &map {
let delta = g.wrapping_sub(cp);
match segs.last_mut() {
Some((_, end, d)) if *end + 1 == cp && *d == delta => *end = cp,
_ => segs.push((cp, cp, delta)),
}
}
segs.push((0xFFFF, 0xFFFF, 1));
let n = u16::try_from(segs.len()).ok()?;
let pow = 1u16 << (15 - n.leading_zeros());
let mut sub: Vec<u8> = Vec::new();
for v in [
4,
16 + 8 * n,
0,
2 * n,
2 * pow,
pow.trailing_zeros() as u16,
2 * (n - pow),
] {
sub.extend_from_slice(&v.to_be_bytes());
}
segs.iter()
.for_each(|s| sub.extend_from_slice(&s.1.to_be_bytes()));
sub.extend_from_slice(&[0, 0]);
segs.iter()
.for_each(|s| sub.extend_from_slice(&s.0.to_be_bytes()));
segs.iter()
.for_each(|s| sub.extend_from_slice(&s.2.to_be_bytes()));
segs.iter().for_each(|_| sub.extend_from_slice(&[0, 0]));
let mut out = vec![0, 0, 0, 1, 0, 3, 0, 1, 0, 0, 0, 12];
out.extend_from_slice(&sub);
Some(out)
}
fn postscript_name_table(face: &ttf_parser::Face<'_>) -> Option<Vec<u8>> {
let ps = face
.names()
.into_iter()
.filter(|n| n.name_id == ttf_parser::name_id::POST_SCRIPT_NAME)
.find_map(|n| n.to_string())?;
let utf16: Vec<u8> = ps.encode_utf16().flat_map(u16::to_be_bytes).collect();
let len = u16::try_from(utf16.len()).ok()?;
let mut out = Vec::with_capacity(18 + utf16.len());
for v in [
0u16,
1,
18,
3,
1,
0x0409,
ttf_parser::name_id::POST_SCRIPT_NAME,
len,
0,
] {
out.extend_from_slice(&v.to_be_bytes());
}
out.extend_from_slice(&utf16);
Some(out)
}
fn write_sfnt(version: u32, tables: &[([u8; 4], Cow<'_, [u8]>)]) -> Vec<u8> {
let checksum = |data: &[u8]| -> u32 {
data.chunks(4).fold(0u32, |sum, c| {
let mut w = [0u8; 4];
w[..c.len()].copy_from_slice(c);
sum.wrapping_add(u32::from_be_bytes(w))
})
};
let n = u16::try_from(tables.len()).unwrap_or(u16::MAX);
let mut pow = 1u16;
let mut log = 0u16;
while pow * 2 <= n {
pow *= 2;
log += 1;
}
let mut out = Vec::new();
out.extend_from_slice(&version.to_be_bytes());
out.extend_from_slice(&n.to_be_bytes());
out.extend_from_slice(&(pow * 16).to_be_bytes());
out.extend_from_slice(&log.to_be_bytes());
out.extend_from_slice(&(n * 16 - pow * 16).to_be_bytes());
let mut offset = 12 + 16 * tables.len();
let mut body: Vec<u8> = Vec::new();
for (tag, data) in tables {
out.extend_from_slice(tag);
out.extend_from_slice(&checksum(data).to_be_bytes());
out.extend_from_slice(&u32::try_from(offset).unwrap_or(0).to_be_bytes());
out.extend_from_slice(&u32::try_from(data.len()).unwrap_or(0).to_be_bytes());
body.extend_from_slice(data);
while !body.len().is_multiple_of(4) {
body.push(0);
}
offset = 12 + 16 * tables.len() + body.len();
}
out.extend_from_slice(&body);
out
}
fn font_file_obj(ttf: &[u8], compress: bool) -> Vec<u8> {
let raw_len = ttf.len();
let (bytes, filter) = deflate(ttf, compress);
let mut out = format!(
"<< /Length {} /Length1 {raw_len}{filter} >>\nstream\n",
bytes.len()
)
.into_bytes();
out.extend_from_slice(&bytes);
out.extend_from_slice(b"\nendstream");
out
}
fn font_descriptor_obj(face: &super::font::Face, file_id: usize) -> Vec<u8> {
let name = face.pdf_name();
let [a, b, c, d] = face.pdf_bbox_1000();
let ascent = face.pdf_ascent_1000();
let descent = face.pdf_descent_1000();
format!(
"<< /Type /FontDescriptor /FontName /{name} /Flags 32 \
/FontBBox [{a} {b} {c} {d}] /ItalicAngle 0 \
/Ascent {ascent} /Descent {descent} /CapHeight {ascent} /StemV 80 \
/FontFile2 {file_id} 0 R >>"
)
.into_bytes()
}
fn simple_ttf_obj(face: &super::font::Face, desc_id: usize) -> Vec<u8> {
let name = face.pdf_name();
let widths: Vec<String> = (32u8..=255)
.map(|b| face.width_1000(winansi_char(b)).to_string())
.collect();
format!(
"<< /Type /Font /Subtype /TrueType /BaseFont /{name} \
/FirstChar 32 /LastChar 255 /Widths [{}] \
/Encoding /WinAnsiEncoding /FontDescriptor {desc_id} 0 R >>",
widths.join(" ")
)
.into_bytes()
}
fn cid_font_obj(face: &super::font::Face, desc_id: usize, used: &BTreeSet<u16>) -> Vec<u8> {
let name = face.pdf_name();
let w_list = cid_widths(&face.pdf_widths_1000(), used);
format!(
"<< /Type /Font /Subtype /CIDFontType2 /BaseFont /{name} \
/CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) /Supplement 0 >> \
/FontDescriptor {desc_id} 0 R /DW 500 /W [{w_list}] /CIDToGIDMap /Identity >>"
)
.into_bytes()
}
fn cid_widths(widths: &[i32], used: &BTreeSet<u16>) -> String {
let mut out = String::new();
let mut prev: Option<u16> = None;
for &g in used {
let Some(w) = widths.get(usize::from(g)) else {
continue;
};
if prev.is_some_and(|p| p + 1 == g) {
let _ = write!(out, " {w}");
} else {
if prev.is_some() {
out.push_str("] ");
}
let _ = write!(out, "{g} [{w}");
}
prev = Some(g);
}
if prev.is_some() {
out.push(']');
}
out
}
fn type0_font_obj(face: &super::font::Face, cid_id: usize, cmap_id: usize) -> Vec<u8> {
let name = face.pdf_name();
format!(
"<< /Type /Font /Subtype /Type0 /BaseFont /{name} /Encoding /Identity-H \
/DescendantFonts [{cid_id} 0 R] /ToUnicode {cmap_id} 0 R >>"
)
.into_bytes()
}
fn face_unicode_map(
face: &super::font::Face,
id: FaceRef,
pages: &[&Page],
) -> BTreeMap<u16, String> {
let parsed = ttf_parser::Face::parse(face.bytes(), 0).ok();
let symbol_encoded = parsed
.as_ref()
.and_then(|p| p.tables().cmap)
.is_some_and(|cmap| {
cmap.subtables
.into_iter()
.any(|t| t.platform_id == ttf_parser::PlatformId::Windows && t.encoding_id == 0)
});
let read = |c: char| read_back(face, symbol_encoded, c);
let mut map = BTreeMap::new();
let mut zipped = BTreeMap::new();
let mut painted = BTreeSet::new();
for page in pages {
for op in &page.ops {
if let Op::Text {
face, glyphs, text, ..
}
| Op::Watermark {
face, glyphs, text, ..
} = op
&& *face == id
{
painted.extend(glyphs.iter().copied());
for c in text.chars() {
let shown = read(c);
let stood_in = |p: &ttf_parser::Face| {
(!symbol_encoded).then(|| p.glyph_index(shown)).flatten()
};
if let Some(g) = parsed
.as_ref()
.and_then(|p| p.glyph_index(c).or_else(|| stood_in(p)))
{
map.entry(g.0).or_insert_with(|| shown.to_string());
}
}
if glyphs.len() == text.chars().count() {
for (&g, c) in glyphs.iter().zip(text.chars()) {
zipped.entry(g).or_insert_with(|| read(c).to_string());
}
} else if let [g] = glyphs[..]
&& !text.is_empty()
{
zipped
.entry(g)
.or_insert_with(|| text.chars().map(read).collect());
}
}
}
}
for (g, c) in zipped {
map.entry(g).or_insert(c);
}
map.retain(|g, _| *g != 0 && painted.contains(g));
map
}
fn read_back(face: &super::font::Face, symbol_encoded: bool, c: char) -> char {
if symbol_encoded {
symbol_font_text(c, face.pdf_name().starts_with("Symbol"))
} else {
face.symbol_stand_in(c).unwrap_or(c)
}
}
fn symbol_font_text(c: char, symbol: bool) -> char {
let code = u32::from(c);
if !(0xF020..=0xF0FF).contains(&code) {
return c;
}
let low = code - 0xF000;
let text = match low {
0x6D if symbol => 0xB5,
0xA4 if symbol => 0x2044,
0xA6 if symbol => 0x192,
0xB7 if symbol => 0x2022,
0xB8 if symbol => 0xF7,
0xBC if symbol => 0x2026,
0xD8 if symbol => 0xAC,
_ => low,
};
char::from_u32(text).unwrap_or(c)
}
fn to_unicode_obj(map: &BTreeMap<u16, String>, compress: bool) -> Vec<u8> {
let mut cmap = String::from(
"/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n\
/CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def\n\
/CMapName /Adobe-Identity-UCS def\n/CMapType 2 def\n\
1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n",
);
let entries: Vec<(&u16, &String)> = map.iter().collect();
for chunk in entries.chunks(100) {
let _ = writeln!(cmap, "{} beginbfchar", chunk.len());
for (g, text) in chunk {
let _ = write!(cmap, "<{g:04X}> <");
for u in text.encode_utf16() {
let _ = write!(cmap, "{u:04X}");
}
cmap.push_str(">\n");
}
cmap.push_str("endbfchar\n");
}
cmap.push_str("endcmap\nCMapName currentdict /CMap defineresource pop\nend\nend");
let (bytes, filter) = deflate(cmap.as_bytes(), compress);
let mut out = format!("<< /Length {}{filter} >>\nstream\n", bytes.len()).into_bytes();
out.extend_from_slice(&bytes);
out.extend_from_slice(b"\nendstream");
out
}
fn jpeg_xobject(width: u32, height: u32, bytes: &[u8], components: u8) -> Vec<u8> {
let (colorspace, decode) = match components {
1 => ("/DeviceGray", ""),
3 => ("/DeviceRGB", ""),
4 => ("/DeviceCMYK", " /Decode [1 0 1 0 1 0 1 0]"),
_ => ("/DeviceRGB", ""),
};
let mut out = format!(
"<< /Type /XObject /Subtype /Image /Width {width} /Height {height} \
/ColorSpace {colorspace} /BitsPerComponent 8 /Filter /DCTDecode{decode} \
/Length {} >>\nstream\n",
bytes.len()
)
.into_bytes();
out.extend_from_slice(bytes);
out.extend_from_slice(b"\nendstream");
out
}
fn rgb_xobject(
width: u32,
height: u32,
bytes: &[u8],
compress: bool,
smask: Option<usize>,
) -> Vec<u8> {
let (bytes, filter) = deflate(bytes, compress);
let smask_e = smask
.map(|id| format!(" /SMask {id} 0 R"))
.unwrap_or_default();
let mut out = format!(
"<< /Type /XObject /Subtype /Image /Width {width} /Height {height} \
/ColorSpace /DeviceRGB /BitsPerComponent 8{filter}{smask_e} \
/Length {} >>\nstream\n",
bytes.len()
)
.into_bytes();
out.extend_from_slice(&bytes);
out.extend_from_slice(b"\nendstream");
out
}
fn gray_xobject(width: u32, height: u32, bytes: &[u8], compress: bool) -> Vec<u8> {
let (bytes, filter) = deflate(bytes, compress);
let mut out = format!(
"<< /Type /XObject /Subtype /Image /Width {width} /Height {height} \
/ColorSpace /DeviceGray /BitsPerComponent 8{filter} \
/Length {} >>\nstream\n",
bytes.len()
)
.into_bytes();
out.extend_from_slice(&bytes);
out.extend_from_slice(b"\nendstream");
out
}
fn ellipse_path(x: f32, y: f32, w: f32, h: f32) -> String {
const K: f32 = 0.552_284_8;
let (rx, ry) = (w * 0.5, h * 0.5);
let (cx, cy) = (x + rx, y + ry);
let (kx, ky) = (rx * K, ry * K);
format!(
"{:.2} {cy:.2} m {:.2} {:.2} {:.2} {:.2} {cx:.2} {:.2} c \
{:.2} {:.2} {:.2} {:.2} {:.2} {cy:.2} c \
{:.2} {:.2} {:.2} {:.2} {cx:.2} {:.2} c \
{:.2} {:.2} {:.2} {:.2} {:.2} {cy:.2} c h",
cx + rx,
cx + rx,
cy + ky,
cx + kx,
cy + ry,
cy + ry,
cx - kx,
cy + ry,
cx - rx,
cy + ky,
cx - rx,
cx - rx,
cy - ky,
cx - kx,
cy - ry,
cy - ry,
cx + kx,
cy - ry,
cx + rx,
cy - ky,
cx + rx,
)
}
fn paint_image(
x: f32,
y: f32,
dw: f32,
dh: f32,
crop: Option<[f32; 4]>,
n: usize,
rotate_deg: f32,
) -> String {
let inner = match crop {
Some([l, t, r, b]) if l.abs() + r.abs() + t.abs() + b.abs() > 0.001 => {
let fw = (1.0 - l - r).max(0.001);
let fh = (1.0 - t - b).max(0.001);
let sx = dw / fw;
let sy = dh / fh;
let x0 = x - sx * l;
let y0 = y - sy * b;
format!(
"q {x:.2} {y:.2} {dw:.2} {dh:.2} re W n {sx:.2} 0 0 {sy:.2} {x0:.2} {y0:.2} cm /Im{n} Do Q\n"
)
}
_ => format!("q {dw:.2} 0 0 {dh:.2} {x:.2} {y:.2} cm /Im{n} Do Q\n"),
};
rotate_about_centre(x, y, dw, dh, rotate_deg, &inner)
}
fn paint_picture(
[x, y, dw, dh]: [f32; 4],
crop: Option<[f32; 4]>,
n: usize,
rotate_deg: f32,
oval: bool,
) -> String {
if !oval {
return paint_image(x, y, dw, dh, crop, n, rotate_deg);
}
let clipped = format!(
"q {} W n {}Q\n",
ellipse_path(x, y, dw, dh),
paint_image(x, y, dw, dh, crop, n, 0.0)
);
rotate_about_centre(x, y, dw, dh, rotate_deg, &clipped)
}
fn rotate_about_centre(x: f32, y: f32, dw: f32, dh: f32, rotate_deg: f32, inner: &str) -> String {
if rotate_deg.abs() < 0.05 {
return inner.to_string();
}
let cx = x + dw * 0.5;
let cy = y + dh * 0.5;
let rad = rotate_deg.to_radians();
let mut cos = rad.cos();
let mut sin = rad.sin();
if cos.abs() < 1e-4 {
cos = 0.0;
}
if sin.abs() < 1e-4 {
sin = 0.0;
}
format!(
"q 1 0 0 1 {cx:.2} {cy:.2} cm {cos:.4} {sin:.4} {nsin:.4} {cos:.4} 0 0 cm \
1 0 0 1 {ncx:.2} {ncy:.2} cm {inner}Q\n",
nsin = -sin,
ncx = -cx,
ncy = -cy,
)
}
fn text_annot_obj(note: &PdfComment) -> Vec<u8> {
let x2 = note.x + note.w.max(12.0);
let y2 = note.y + note.h.max(12.0);
let contents = pdf_text_string(¬e.contents);
let author = pdf_text_string(¬e.author);
format!(
"<< /Type /Annot /Subtype /Text /Rect [{x:.2} {y:.2} {x2:.2} {y2:.2}] \
/Contents {contents} /T {author} /Name /Comment /F 0 /C [1 0.92 0.4] >>",
x = note.x,
y = note.y,
)
.into_bytes()
}
fn deflate(raw: &[u8], compress: bool) -> (Cow<'_, [u8]>, &'static str) {
if !compress {
return (Cow::Borrowed(raw), "");
}
let mut enc = ZlibEncoder::new(Vec::new(), Compression::default());
match enc.write_all(raw).and_then(|()| enc.finish()) {
Ok(packed) => (Cow::Owned(packed), " /Filter /FlateDecode"),
Err(_) => (Cow::Borrowed(raw), ""),
}
}
fn stream_object(ops: &str, compress: bool) -> Vec<u8> {
let (bytes, filter) = deflate(ops.as_bytes(), compress);
let mut out = format!("<< /Length {}{filter} >>\nstream\n", bytes.len()).into_bytes();
out.extend_from_slice(&bytes);
out.extend_from_slice(b"\nendstream");
out
}
fn winansi_byte(ch: char) -> Option<u8> {
match ch as u32 {
0x20..=0x7E | 0xA0..=0xFF => Some(ch as u8),
0x2011 => Some(b'-'),
0x0152 => Some(0x8C),
0x0153 => Some(0x9C),
0x0160 => Some(0x8A),
0x0161 => Some(0x9A),
0x0178 => Some(0x9F),
0x017D => Some(0x8E),
0x017E => Some(0x9E),
0x0192 => Some(0x83),
0x02C6 => Some(0x88),
0x02DC => Some(0x98),
0x2013 => Some(0x96),
0x2014 => Some(0x97),
0x2018 => Some(0x91),
0x2019 => Some(0x92),
0x201A => Some(0x82),
0x201C => Some(0x93),
0x201D => Some(0x94),
0x201E => Some(0x84),
0x2020 => Some(0x86),
0x2021 => Some(0x87),
0x2022 => Some(0x95),
0x2026 => Some(0x85),
0x2030 => Some(0x89),
0x2039 => Some(0x8B),
0x203A => Some(0x9B),
0x20AC => Some(0x80),
0x2122 => Some(0x99),
_ => None,
}
}
fn winansi_char(byte: u8) -> char {
match byte {
0x80 => '\u{20AC}',
0x82 => '\u{201A}',
0x83 => '\u{0192}',
0x84 => '\u{201E}',
0x85 => '\u{2026}',
0x86 => '\u{2020}',
0x87 => '\u{2021}',
0x88 => '\u{02C6}',
0x89 => '\u{2030}',
0x8A => '\u{0160}',
0x8B => '\u{2039}',
0x8C => '\u{0152}',
0x8E => '\u{017D}',
0x91 => '\u{2018}',
0x92 => '\u{2019}',
0x93 => '\u{201C}',
0x94 => '\u{201D}',
0x95 => '\u{2022}',
0x96 => '\u{2013}',
0x97 => '\u{2014}',
0x98 => '\u{02DC}',
0x99 => '\u{2122}',
0x9A => '\u{0161}',
0x9B => '\u{203A}',
0x9C => '\u{0153}',
0x9E => '\u{017E}',
0x9F => '\u{0178}',
0x20..=0x7E | 0xA0..=0xFF => char::from(byte),
_ => ' ',
}
}
fn winansi_bytes(text: &str) -> Option<Vec<u8>> {
if text.is_empty() {
return None;
}
text.chars().map(winansi_byte).collect()
}
fn pdf_text_string(text: &str) -> String {
if text.is_ascii() {
return pdf_literal(text.as_bytes());
}
let mut out = String::from("<FEFF");
for unit in text.encode_utf16() {
let _ = write!(out, "{unit:04X}");
}
out.push('>');
out
}
fn pdf_literal(bytes: &[u8]) -> String {
let mut out = String::from("(");
for &b in bytes {
match b {
b'(' | b')' | b'\\' => {
out.push('\\');
out.push(char::from(b));
}
32..=126 => out.push(char::from(b)),
_ => {
let _ = write!(out, "\\{b:03o}");
}
}
}
out.push(')');
out
}
fn finalize_pdf(objects: &[Vec<u8>]) -> Vec<u8> {
let mut out = Vec::from(b"%PDF-1.4\n%\xE2\xE3\xCF\xD3\n");
let mut offsets = Vec::with_capacity(objects.len());
for (idx, obj) in objects.iter().enumerate() {
offsets.push(out.len());
out.extend_from_slice(format!("{} 0 obj\n", idx + 1).as_bytes());
out.extend_from_slice(obj);
if !obj.ends_with(b"\n") {
out.push(b'\n');
}
out.extend_from_slice(b"endobj\n");
}
let xref_at = out.len();
out.extend_from_slice(format!("xref\n0 {}\n", objects.len() + 1).as_bytes());
out.extend_from_slice(b"0000000000 65535 f \n");
for offset in offsets {
out.extend_from_slice(format!("{offset:010} 00000 n \n").as_bytes());
}
out.extend_from_slice(
format!(
"trailer\n<< /Size {size} /Root 1 0 R /Info 3 0 R >>\nstartxref\n{xref_at}\n%%EOF\n",
size = objects.len() + 1,
)
.as_bytes(),
);
out
}
fn stands_upright(c: char) -> bool {
let cjk = matches!(
c,
'\u{3000}'..='\u{9FFF}' | '\u{F900}'..='\u{FAFF}' | '\u{FF00}'..='\u{FFEF}' | '\u{20000}'..='\u{2FA1F}'
);
cjk && !matches!(
c,
'〈' | '〉'
| '《'
| '》'
| '「'
| '」'
| '『'
| '』'
| '【'
| '】'
| '〔'
| '〕'
| '〖'
| '〗'
| '〘'
| '〙'
| '〚'
| '〛'
| '('
| ')'
| '['
| ']'
| '{'
| '}'
| 'ー'
| '〜'
| '~'
| '-'
| '='
| '\u{3000}'
)
}
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod tests {
use super::uniquify;
#[test]
fn markup_page_sits_where_the_exact_fit_centres_it() {
let chrome = |w: f32, h: f32, mr: f32| super::markup_chrome(w, h, mr).expect("chrome");
for (w, h, mr, k300, top) in [
(612.0, 792.0, 72.0, 224.0, 99.84),
(612.0, 792.0, 54.0, 219.0, 106.32),
(612.0, 792.0, 70.9, 224.0, 100.08),
(612.0, 792.0, 90.0, 229.0, 93.12),
(612.0, 792.0, 108.0, 235.0, 85.92),
(595.2, 841.92, 45.35, 215.0, 118.56),
(595.2, 841.92, 56.7, 218.0, 114.24),
(595.2, 841.92, 72.0, 223.0, 108.48),
(595.2, 841.92, 76.55, 224.0, 106.56),
(595.2, 841.92, 85.05, 226.0, 103.2),
(595.2, 841.92, 89.85, 228.0, 101.28),
(595.2, 841.92, 120.25, 237.0, 88.08),
(595.0, 842.0, 72.45, 223.0, 108.24),
(841.92, 595.2, 72.0, 241.0, 58.56),
] {
let c = chrome(w, h, mr);
assert!(
((c.k * 300.0) - k300).abs() < 0.01,
"{w}x{h} mr {mr}: k {} not {k300}/300",
c.k * 300.0
);
assert!(
(h - c.gy - c.gh - top).abs() < 0.01,
"{w}x{h} mr {mr}: page top {} not {top}",
h - c.gy - c.gh
);
}
let c = chrome(612.0, 792.0, 79.2);
let exact = (612.0 - 8.64) / (612.0 - 79.2 + 265.68);
assert!(((c.k * 300.0) - (exact * 300.0_f32).floor()).abs() < 0.01);
let centre = 792.0 * (1.0 - exact) / 2.0;
let top = 792.0 - c.gy - c.gh;
assert!(
(top / 0.24 - (top / 0.24).round()).abs() < 0.01,
"on the grid"
);
assert!(
top > centre && top < centre + 0.6,
"top {top} near {centre}"
);
}
#[test]
fn a_stood_in_symbol_code_reads_back_as_the_character_painted() {
use super::super::font::{Face, FaceId};
let symbol = Face::bundled(FaceId::Symbol);
assert_eq!(super::read_back(&symbol, false, '\u{F0B7}'), '•');
assert_eq!(super::read_back(&symbol, false, 'a'), 'a');
let sans = Face::bundled(FaceId::SansRegular);
assert_eq!(super::read_back(&sans, false, '\u{F0A7}'), '▪');
assert_eq!(super::read_back(&sans, false, '\u{2011}'), '\u{2011}');
}
#[test]
fn a_stood_in_symbol_code_reads_back_in_a_run_shaped_to_another_count() {
use super::super::font::{Face, FaceId};
use super::{Op, Page};
let sans = Face::bundled(FaceId::SansRegular);
let (a, square) = (sans.glyph('a'), sans.glyph('\u{F0A7}'));
assert_ne!(square, 0);
let mut page = Page::new(612.0, 792.0);
page.ops.push(Op::Text {
face: FaceId::SansRegular.into(),
size: 11.0,
x: 72.0,
y: 72.0,
glyphs: vec![a, square, square],
color: [0.0; 3],
text: "a\u{F0A7}".to_string(),
hscale: 1.0,
hidden: false,
});
let map = super::face_unicode_map(&sans, FaceId::SansRegular.into(), &[&page]);
assert_eq!(map.get(&square).map(String::as_str), Some("▪"));
assert_eq!(map.get(&a).map(String::as_str), Some("a"));
}
#[test]
fn symbol_font_text_reads_back_as_word_writes_it() {
let read =
|c: u32, symbol: bool| super::symbol_font_text(char::from_u32(c).unwrap(), symbol);
assert_eq!(read(0xF0B7, true), '\u{2022}');
assert_eq!(read(0xF0B8, true), '\u{F7}');
assert_eq!(read(0xF06D, true), '\u{B5}');
assert_eq!(read(0xF0A4, true), '\u{2044}');
assert_eq!(read(0xF0A6, true), '\u{192}');
assert_eq!(read(0xF0BC, true), '\u{2026}');
assert_eq!(read(0xF0D8, true), '\u{AC}');
assert_eq!(read(0xF061, true), 'a');
assert_eq!(read(0xF0B4, true), '\u{B4}');
assert_eq!(read(0xF0A7, false), '\u{A7}');
assert_eq!(read(0xF0B7, false), '\u{B7}');
assert_eq!(read(0x2022, true), '\u{2022}');
assert_eq!(read(0xF100, true), '\u{F100}');
}
#[test]
fn a_comment_on_a_vertical_page_turns_with_its_text() {
let fonts = super::Fonts::new();
let mut page = super::Page::new(595.2, 841.92);
page.vertical = true;
page.comments.push(super::PdfComment {
id: "0".into(),
x: 100.0,
y: 700.0,
w: 20.0,
h: 14.0,
top: 690.0,
bottom: 703.0,
contents: "note".into(),
author: "A".into(),
initials: "A".into(),
label: "1".into(),
color: [0.0; 3],
resolved: false,
});
let options = crate::convert::PdfOptions {
comment_notes: true,
..crate::convert::PdfOptions::default()
};
let pdf = super::emit(&fonts, &[page], options);
let hay = String::from_utf8_lossy(&pdf);
assert!(
hay.contains("/Rect [700.00 475.20 714.00 495.20]"),
"{}",
hay.lines()
.find(|l| l.contains("/Rect"))
.unwrap_or_default()
);
}
#[test]
fn subset_keeps_ids_and_used_outlines_only() {
let bytes = super::FaceId::CarlitoRegular.bytes();
let full = ttf_parser::Face::parse(bytes, 0).expect("Carlito");
let a = full.glyph_index('A').expect("A").0;
let b = full.glyph_index('B').expect("B").0;
let e_acute = full.glyph_index('É').expect("Eacute").0;
let e = full.glyph_index('E').expect("E").0;
let used = std::collections::BTreeSet::from([0u16, a, e_acute]);
let program = super::subset_keep_gids(bytes, &used).expect("glyf face subsets");
assert!(
program.len() < bytes.len() / 3,
"{} vs {}",
program.len(),
bytes.len()
);
let sub = ttf_parser::Face::parse(&program, 0).expect("subset parses");
assert_eq!(
sub.number_of_glyphs(),
full.number_of_glyphs(),
"ids never move"
);
assert_eq!(sub.glyph_index('A').map(|g| g.0), Some(a), "cmap kept");
let bbox = |f: &ttf_parser::Face<'_>, g: u16| f.glyph_bounding_box(ttf_parser::GlyphId(g));
assert_eq!(bbox(&sub, a), bbox(&full, a), "used outline kept");
assert!(bbox(&sub, b).is_none(), "unused outline emptied");
assert_eq!(bbox(&sub, e_acute), bbox(&full, e_acute));
assert_eq!(
bbox(&sub, e),
bbox(&full, e),
"a composite keeps its components"
);
}
#[test]
fn subset_drops_glyph_names_and_unused_metrics() {
let bytes = super::FaceId::CarlitoRegular.bytes();
let full = ttf_parser::Face::parse(bytes, 0).expect("Carlito");
let a = full.glyph_index('A').expect("A").0;
let b = full.glyph_index('B').expect("B").0;
let used = std::collections::BTreeSet::from([0u16, a]);
let program = super::subset_keep_gids(bytes, &used).expect("glyf face subsets");
let sub = ttf_parser::Face::parse(&program, 0).expect("subset parses");
let raw = sub
.raw_face()
.table(ttf_parser::Tag::from_bytes(b"post"))
.expect("post");
assert_eq!(raw.len(), 32, "post format 3 header only");
assert_eq!(&raw[..4], &[0, 3, 0, 0]);
let adv = |f: &ttf_parser::Face<'_>, g: u16| f.glyph_hor_advance(ttf_parser::GlyphId(g));
assert_eq!(adv(&sub, a), adv(&full, a), "used metrics kept");
assert_eq!(adv(&sub, b), Some(0), "unused metrics zeroed");
assert_eq!(sub.number_of_glyphs(), full.number_of_glyphs());
}
#[test]
fn cid_widths_list_only_the_used_glyph_runs() {
let widths: Vec<i32> = (0..40_000).map(|g| 500 + g % 7).collect();
let used = std::collections::BTreeSet::from([0u16, 3, 4, 5, 30_000]);
assert_eq!(
super::cid_widths(&widths, &used),
"0 [500] 3 [503 504 505] 30000 [505]"
);
}
#[test]
fn relative_moves_round_trip_the_printed_hundredths() {
for (v, h, shown) in [
(730.4, 73040, "730.4"),
(-0.05, -5, "-0.05"),
(6.0, 600, "6"),
(-12.5, -1250, "-12.5"),
(0.07, 7, "0.07"),
] {
assert_eq!(super::hundredths(v), h, "{v}");
assert_eq!(super::fmt_hundredths(h), shown);
}
}
#[test]
fn a_collections_first_face_subsets_to_a_plain_font() {
let single = super::FaceId::CarlitoRegular.bytes();
let num_tables = usize::from(u16::from_be_bytes([single[4], single[5]]));
let mut shifted = single.to_vec();
for t in 0..num_tables {
let at = 12 + 16 * t + 8;
let off = u32::from_be_bytes(shifted[at..at + 4].try_into().expect("offset"));
shifted[at..at + 4].copy_from_slice(&(off + 16).to_be_bytes());
}
let mut ttc = b"ttcf\x00\x01\x00\x00\x00\x00\x00\x01\x00\x00\x00\x10".to_vec();
ttc.extend_from_slice(&shifted);
let full = ttf_parser::Face::parse(&ttc, 0).expect("collection parses");
let a = full.glyph_index('A').expect("A").0;
let used = std::collections::BTreeSet::from([0u16, a]);
let program = super::subset_keep_gids(&ttc, &used).expect("collection face subsets");
assert_ne!(&program[..4], b"ttcf", "a plain sfnt");
assert!(program.len() < single.len() / 3);
let sub = ttf_parser::Face::parse(&program, 0).expect("subset parses");
assert_eq!(sub.glyph_index('A').map(|g| g.0), Some(a));
}
#[test]
fn subset_cmap_and_name_keep_only_what_the_pdf_uses() {
let bytes = super::FaceId::CarlitoRegular.bytes();
let full = ttf_parser::Face::parse(bytes, 0).expect("Carlito");
let a = full.glyph_index('A').expect("A").0;
let used = std::collections::BTreeSet::from([0u16, a]);
let program = super::subset_keep_gids(bytes, &used).expect("glyf face subsets");
let sub = ttf_parser::Face::parse(&program, 0).expect("subset parses");
let len = |tag: &[u8; 4]| {
sub.raw_face()
.table(ttf_parser::Tag::from_bytes(tag))
.map_or(0, <[u8]>::len)
};
assert!(len(b"cmap") < 200, "cmap {}", len(b"cmap"));
assert!(len(b"name") < 200, "name {}", len(b"name"));
assert_eq!(sub.glyph_index('A').map(|g| g.0), Some(a));
assert_eq!(sub.glyph_index('B'), None, "unused characters unmapped");
let ps = |f: &ttf_parser::Face<'_>| {
f.names()
.into_iter()
.filter(|n| n.name_id == ttf_parser::name_id::POST_SCRIPT_NAME)
.find_map(|n| n.to_string())
};
assert_eq!(ps(&sub), ps(&full));
}
#[test]
fn colliding_font_names_get_distinct_resource_names() {
let mut taken = Vec::new();
let first = uniquify("Foo-Bar", &mut taken);
let second = uniquify("Foo-Bar", &mut taken);
let third = uniquify("Foo-Bar", &mut taken);
assert_eq!(first, "Foo-Bar", "first claimant keeps the readable name");
assert_ne!(first, second);
assert_ne!(second, third);
assert_ne!(first, third);
assert_eq!(second, "Foo-Bar-2");
assert_eq!(third, "Foo-Bar-3");
}
#[test]
fn non_ascii_annotation_text_is_utf16be_with_a_bom() {
assert_eq!(super::pdf_text_string("José"), "<FEFF004A006F007300E9>");
assert_eq!(super::pdf_text_string("東京"), "<FEFF67714EAC>");
assert_eq!(super::pdf_text_string("\u{1F600}"), "<FEFFD83DDE00>");
}
#[test]
fn ascii_annotation_text_stays_a_literal_string() {
assert_eq!(super::pdf_text_string("Reviewer"), "(Reviewer)");
assert_eq!(super::pdf_text_string("a (b) c"), "(a \\(b\\) c)");
}
#[test]
fn uniquify_skips_a_name_already_claimed_verbatim() {
let mut taken = Vec::new();
assert_eq!(uniquify("Sans", &mut taken), "Sans");
assert_eq!(uniquify("Sans-2", &mut taken), "Sans-2");
assert_eq!(uniquify("Sans", &mut taken), "Sans-3");
}
mod regression_tests {
use super::super::{ellipse_path, paint_image, paint_picture, stands_upright};
#[test]
fn negative_crop_insets_the_image_inside_its_clipping_box() {
let ops = paint_image(
10.0,
20.0,
100.0,
60.0,
Some([-0.5, 0.0, -0.5, 0.0]),
3,
0.0,
);
assert!(ops.contains("10.00 20.00 100.00 60.00 re W n"), "{ops}");
assert!(
ops.contains("50.00 0 0 60.00 35.00 20.00 cm /Im3 Do"),
"{ops}"
);
}
#[test]
fn opposing_crop_offsets_do_not_cancel_the_crop_transform() {
let ops = paint_image(
10.0,
20.0,
100.0,
60.0,
Some([0.25, 0.0, -0.25, 0.0]),
1,
0.0,
);
assert!(ops.contains("re W n"), "{ops}");
assert!(ops.contains("100.00 0 0 60.00 -15.00 20.00 cm"), "{ops}");
}
#[test]
fn a_rotated_oval_picture_turns_its_clip_with_the_image() {
let drawn = paint_picture([10.0, 20.0, 80.0, 40.0], None, 1, 90.0, true);
let turn = drawn.find(" 0 0 cm 1 0 0 1 ").expect("rotation");
let clip = drawn.find(" W n ").expect("oval clip");
assert!(turn < clip, "the clip sits inside the rotation: {drawn}");
assert_eq!(
paint_picture([10.0, 20.0, 80.0, 40.0], None, 1, 0.0, true),
format!(
"q {} W n {}Q\n",
ellipse_path(10.0, 20.0, 80.0, 40.0),
paint_image(10.0, 20.0, 80.0, 40.0, None, 1, 0.0)
),
"an unrotated oval keeps its output"
);
}
#[test]
fn ellipse_path_closes_at_the_four_box_extremes() {
let path = ellipse_path(10.0, 20.0, 80.0, 40.0);
assert!(path.starts_with("90.00 40.00 m "), "{path}");
assert!(path.ends_with("90.00 40.00 c h"), "{path}");
assert_eq!(path.split_whitespace().filter(|t| *t == "c").count(), 4);
for end in ["50.00 60.00 c", "10.00 40.00 c", "50.00 20.00 c"] {
assert!(path.contains(end), "{path}");
}
}
#[test]
fn vertical_text_keeps_ideographs_upright_but_turns_brackets_and_latin() {
for c in ['漢', 'あ', 'カ', 'A', '1', '\u{20000}', '\u{2FA1F}'] {
assert!(stands_upright(c), "{c}");
}
for c in [
'A',
'1',
' ',
'\u{3000}',
'「',
'」',
'(',
')',
'ー',
'~',
'-',
'\u{2FA20}',
] {
assert!(!stands_upright(c), "{c}");
}
}
}
}
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod residual_byte_and_geometry_contract_tests {
use super::*;
use std::io::Read;
fn bundled_fonts() -> Fonts<'static> {
let mut fonts = Fonts::new();
fonts.insert_embedded(
"PDFContractCarlito",
false,
false,
FaceId::CarlitoRegular.bytes(),
);
fonts.insert_embedded("PDFContractMono", false, false, FaceId::MonoRegular.bytes());
fonts
}
fn stream(object: &[u8]) -> Vec<u8> {
let at = object.windows(8).position(|w| w == b"\nstream\n").unwrap() + 8;
let dictionary = std::str::from_utf8(&object[..at]).unwrap();
let length = dictionary
.split("/Length ")
.nth(1)
.unwrap()
.split_whitespace()
.next()
.unwrap()
.parse::<usize>()
.unwrap();
let payload = &object[at..at + length];
assert_eq!(&object[at + length..], b"\nendstream");
if dictionary.contains("/FlateDecode") {
let mut out = Vec::new();
flate2::read::ZlibDecoder::new(payload)
.read_to_end(&mut out)
.unwrap();
out
} else {
payload.to_vec()
}
}
#[test]
fn large_signed_coordinates_and_sparse_cid_widths_have_exact_serialized_values() {
for (coordinate, expected) in [
(10_000_000.0, 1_000_000_000),
(-10_000_000.0, -1_000_000_000),
(10_000_001.0, 1_000_000_100),
] {
assert_eq!(hundredths(coordinate), expected);
}
assert_eq!(
cid_widths(&[500, 600, 700, 800], &BTreeSet::from([1, 2, 3, 99])),
"1 [600 700 800]"
);
assert_eq!(cid_widths(&[500], &BTreeSet::from([99])), ""); assert_eq!(cid_widths(&[], &BTreeSet::new()), "");
let show = Show {
lit: Lit::Glyphs(&[0, 10, 65535]),
actual: None,
};
assert_eq!(show.to_string(), "<0000000AFFFF> Tj");
}
#[test]
fn text_string_encodings_preserve_ascii_controls_unicode_and_winansi_boundaries() {
assert_eq!(pdf_text_string("(a)\\\n\t"), "(\\(a\\)\\\\\\012\\011)");
assert_eq!(pdf_text_string("😀漢"), "<FEFFD83DDE006F22>");
assert_eq!(winansi_bytes(""), None);
assert_eq!(winansi_bytes("漢"), None);
assert_eq!(
winansi_bytes("A\u{2011}€ŒœŠšŸŽžƒˆ˜–—‘’‚“”„†‡•…‰‹›™"),
Some(vec![
65, 45, 128, 140, 156, 138, 154, 159, 142, 158, 131, 136, 152, 150, 151, 145, 146,
130, 147, 148, 132, 134, 135, 149, 133, 137, 139, 155, 153
])
);
for byte in [0, 0x81, 0x8D, 0x8F, 0x90, 0x9D] {
assert_eq!(winansi_char(byte), ' ');
}
}
#[test]
fn unicode_cmap_chunks_preserve_every_cid_and_utf16_surrogate_exactly() {
let mut map = BTreeMap::new();
for g in 1..=101 {
map.insert(g, "A".into());
}
map.insert(102, "😀漢".into());
let before = map.clone();
for compress in [false, true] {
let decoded = String::from_utf8(stream(&to_unicode_obj(&map, compress))).unwrap();
assert!(decoded.contains("100 beginbfchar\n<0001> <0041>\n"));
assert!(decoded.contains("<0064> <0041>\nendbfchar\n2 beginbfchar\n<0065> <0041>\n<0066> <D83DDE006F22>\nendbfchar\n"));
assert_eq!(decoded.matches("> <").count(), 103); assert!(
decoded
.ends_with("endcmap\nCMapName currentdict /CMap defineresource pop\nend\nend")
);
}
assert_eq!(map, before);
}
#[test]
fn image_xobjects_keep_literal_color_spaces_masks_and_lossless_samples() {
let samples = [0, 1, 127, 128, 254, 255];
for compress in [false, true] {
for mask in [None, Some(7)] {
let object = rgb_xobject(2, 1, &samples, compress, mask);
assert_eq!(stream(&object), samples);
let dictionary = String::from_utf8_lossy(
&object[..object.windows(8).position(|w| w == b"\nstream\n").unwrap()],
);
assert!(
dictionary
.contains("/Width 2 /Height 1 /ColorSpace /DeviceRGB /BitsPerComponent 8")
);
assert_eq!(dictionary.contains("/SMask 7 0 R"), mask.is_some());
}
assert_eq!(stream(&gray_xobject(6, 1, &samples, compress)), samples);
assert_eq!(stream(&font_file_obj(&samples, compress)), samples);
assert_eq!(stream(&stream_object("q\nQ\n", compress)), b"q\nQ\n");
}
for (components, color, decode) in [
(1, "/DeviceGray", false),
(3, "/DeviceRGB", false),
(4, "/DeviceCMYK", true),
(2, "/DeviceRGB", false),
] {
let object = jpeg_xobject(2, 1, &samples, components);
assert_eq!(stream(&object), samples);
let dict = String::from_utf8_lossy(
&object[..object.windows(8).position(|w| w == b"\nstream\n").unwrap()],
);
assert!(dict.contains(color));
assert_eq!(dict.contains("/Decode [1 0 1 0 1 0 1 0]"), decode);
}
}
#[test]
fn image_rotation_keeps_cardinal_matrices_and_subthreshold_rotation_is_identity() {
let literal = "owned\n";
for degrees in [-0.01, 0.0, 0.01] {
assert_eq!(
rotate_about_centre(10.0, 20.0, 80.0, 40.0, degrees, literal),
literal
);
}
for (degrees, matrix) in [
(90.0, "0.0000 1.0000 -1.0000 0.0000"),
(180.0, "-1.0000 0.0000 -0.0000 -1.0000"),
(-90.0, "0.0000 -1.0000 1.0000 0.0000"),
] {
assert_eq!(
rotate_about_centre(10.0, 20.0, 80.0, 40.0, degrees, literal),
format!(
"q 1 0 0 1 50.00 40.00 cm {matrix} 0 0 cm 1 0 0 1 -50.00 -40.00 cm owned\nQ\n"
)
);
}
for crop in [None, Some([0.0; 4]), Some([0.0001; 4])] {
assert_eq!(
paint_image(10.0, 20.0, 80.0, 40.0, crop, 3, 0.0),
"q 80.00 0 0 40.00 10.00 20.00 cm /Im3 Do Q\n"
);
}
}
#[test]
fn glyph_usage_and_unicode_maps_keep_face_ownership_and_ignore_nonpainting_source() {
let fonts = bundled_fonts();
let a = FaceRef::Embedded(0);
let b = FaceRef::Embedded(1);
let fa = fonts.get(a);
let fb = fonts.get(b);
let ag = fa.glyphs("A");
let bg = fb.glyphs("B");
let mut page = Page::new(40.0, 40.0);
page.ops = vec![
Op::text(a, 10.0, 1.0, 10.0, ag.clone(), [0.0; 3], "A"),
Op::text(b, 10.0, 1.0, 20.0, bg, [0.0; 3], "B"),
Op::text(a, 10.0, 1.0, 30.0, vec![], [0.0; 3], "not painted"),
Op::Pin(true),
Op::Pin(false),
];
let map = face_unicode_map(fa, a, &[&page]);
assert_eq!(map, BTreeMap::from([(ag[0], "A".into())]));
let mut page = Page::new(40.0, 40.0);
page.ops = vec![Op::text(a, 10.0, 1.0, 10.0, ag.clone(), [0.0; 3], "A")];
assert_eq!(
face_used_glyphs(fa, a, &[&page]),
BTreeSet::from([0, ag[0]])
);
}
#[test]
fn subset_declines_corrupt_sfnt_directory_but_keeps_valid_empty_and_out_of_range_usage() {
let original = FaceId::CarlitoRegular.bytes();
let full = ttf_parser::Face::parse(original, 0).unwrap();
let gid = full.glyph_index('A').unwrap();
for used in [BTreeSet::new(), BTreeSet::from([gid.0, u16::MAX])] {
let sub = subset_keep_gids(original, &used).unwrap();
let parsed = ttf_parser::Face::parse(&sub, 0).unwrap();
assert_eq!(parsed.number_of_glyphs(), full.number_of_glyphs());
if used.contains(&gid.0) {
assert_eq!(parsed.glyph_bounding_box(gid), full.glyph_bounding_box(gid));
} else {
assert!(parsed.glyph_bounding_box(gid).is_none());
}
}
for bytes in [original[..3].to_vec(), original[..12].to_vec(), {
let mut b = original.to_vec();
b[20..24].copy_from_slice(&u32::MAX.to_be_bytes());
b
}] {
let before = bytes.clone();
assert!(subset_keep_gids(&bytes, &BTreeSet::from([gid.0])).is_none());
assert_eq!(bytes, before);
}
let mut missing = original.to_vec();
let tables = u16::from_be_bytes(missing[4..6].try_into().unwrap()) as usize;
let rec = (0..tables)
.map(|i| 12 + 16 * i)
.find(|&i| &missing[i..i + 4] == b"glyf")
.unwrap();
missing[rec..rec + 4].copy_from_slice(b"BAD!");
assert!(subset_keep_gids(&missing, &BTreeSet::from([gid.0])).is_none());
}
#[test]
fn pdf_cross_reference_offsets_point_to_exact_unmodified_binary_object_boundaries() {
let objects = vec![
b"<< /Type /Catalog >>\n".to_vec(),
b"binary\0\xff".to_vec(),
b"<< /Producer (test) >>".to_vec(),
];
let before = objects.clone();
let bytes = finalize_pdf(&objects);
let xref = bytes.windows(5).position(|w| w == b"xref\n").unwrap();
let tail = std::str::from_utf8(&bytes[xref..]).unwrap();
assert!(tail.starts_with("xref\n0 4\n0000000000 65535 f \n"));
for (i, row) in tail.lines().skip(3).take(3).enumerate() {
let offset: usize = row[..10].parse().unwrap();
let head = format!("{} 0 obj\n", i + 1);
assert_eq!(&bytes[offset..offset + head.len()], head.as_bytes());
assert_eq!(
&bytes[offset + head.len()..offset + head.len() + objects[i].len()],
objects[i]
);
}
assert!(tail.ends_with(&format!("startxref\n{xref}\n%%EOF\n")));
assert_eq!(objects, before);
}
#[test]
fn authored_width_scales_close_text_objects_without_leaking_into_following_glyphs() {
let fonts = bundled_fonts();
let face = fonts.resolve("PDFContractMono", false, false);
let raw = ttf_parser::Face::parse(FaceId::MonoRegular.bytes(), 0).unwrap();
for (size, ppem, tracking) in [
(10.0, None, ""),
(11.04, Some(46), "-0.0015"),
(16.08, Some(67), "-0.0018"),
] {
for scale in [0.5, 1.0, 1.5] {
let mut page = Page::new(200.0, 300.0);
for (c, x, sx) in [('A', 10.0, 1.0), ('B', 20.0, scale), ('C', 30.0, 1.0)] {
page.ops.push(
Op::text(
face,
size,
x,
200.0,
vec![raw.glyph_index(c).unwrap().0],
[1.0, 0.0, 0.0],
c.to_string(),
)
.scaled(sx),
);
}
let signature = |page: &Page| {
page.ops
.iter()
.map(|op| match op {
Op::Text {
face,
size,
x,
y,
glyphs,
color,
text,
hscale,
..
} => (
*face,
*size,
*x,
*y,
glyphs.clone(),
*color,
text.clone(),
*hscale,
),
_ => panic!(
"source owns only text operations: {:?}",
std::mem::discriminant(op)
),
})
.collect::<Vec<_>>()
};
let original = signature(&page);
for compress in [false, true] {
let pdf = emit(
&fonts,
std::slice::from_ref(&page),
PdfOptions {
compress,
..PdfOptions::default()
},
);
let xref = pdf.windows(6).rposition(|w| w == b"\nxref\n").unwrap() + 1;
let tail = std::str::from_utf8(&pdf[xref..]).unwrap();
let count = tail
.lines()
.nth(1)
.unwrap()
.split_whitespace()
.nth(1)
.unwrap()
.parse::<usize>()
.unwrap();
let offsets = tail
.lines()
.skip(3)
.take(count - 1)
.map(|row| row[..10].parse::<usize>().unwrap())
.collect::<Vec<_>>();
let mut contents = Vec::new();
for (i, &at) in offsets.iter().enumerate() {
let end = offsets.get(i + 1).copied().unwrap_or(xref);
let prefix = format!("{} 0 obj\n", i + 1);
let object = pdf[at..end]
.strip_prefix(prefix.as_bytes())
.unwrap()
.strip_suffix(b"\nendobj\n")
.unwrap();
if object.windows(8).any(|w| w == b"\nstream\n") {
let decoded = stream(object);
if decoded.windows(3).any(|w| w == b" Tj") {
contents.push(String::from_utf8(decoded).unwrap());
}
}
}
assert_eq!(contents.len(), 1);
let content = &contents[0];
assert_eq!(content.matches(" Tj").count(), 3);
if let Some(ppem) = ppem {
for (c, x, a) in [
('A', 10, "0.24".to_string()),
('B', 20, format!("{:.4}", 0.24 * scale)),
('C', 30, "0.24".to_string()),
] {
let a = if c == 'B' && scale == 1.0 {
"0.24".to_string()
} else {
a
};
assert!(content.contains(&format!("q {a} 0 0 0.24 {x}.00 199.92 cm BT /LiberationMono {ppem} Tf 1.000 0.000 0.000 rg {tracking} Tc 0 0 Td ({c}) Tj ET Q")), "size={size}, scale={scale}, content={content}");
}
} else if scale == 1.0 {
assert!(content.contains("BT /LiberationMono 10.00 Tf 1.000 0.000 0.000 rg 10.00 200.00 Td (A) Tj\n10 0 Td (B) Tj\n10 0 Td (C) Tj\nET\n"), "{content}");
} else {
assert!(
content.contains("10.00 200.00 Td (A) Tj\nET\n"),
"{content}"
);
assert!(content.contains(&format!("q {scale:.4} 0 0 1 20.00 200.00 cm BT /LiberationMono 10.00 Tf 1.000 0.000 0.000 rg 0 0 Td (B) Tj ET Q\n")), "{content}");
assert!(content.contains("BT /LiberationMono 10.00 Tf 1.000 0.000 0.000 rg 30.00 200.00 Td (C) Tj\nET\n"), "{content}");
}
assert_eq!(signature(&page), original);
}
}
}
}
#[test]
fn notdef_runs_carry_their_text_as_actual_text() {
let fonts = bundled_fonts();
let face = fonts.resolve("PDFContractSans", false, false);
let raw = ttf_parser::Face::parse(fonts.get(face).bytes(), 0).unwrap();
assert!(raw.glyph_index('研').is_none());
let mut page = Page::new(200.0, 300.0);
page.ops.push(Op::text(
face,
10.0,
10.0,
200.0,
vec![0, 0],
[0.0, 0.0, 0.0],
"研究".to_string(),
));
page.ops.push(Op::text(
face,
10.0,
40.0,
200.0,
vec![raw.glyph_index('A').unwrap().0],
[0.0, 0.0, 0.0],
"A".to_string(),
));
page.ops.push(
Op::text(
face,
10.0,
10.0,
220.0,
vec![0],
[0.0, 0.0, 0.0],
"研".to_string(),
)
.hidden(),
);
let pdf = emit(&fonts, std::slice::from_ref(&page), PdfOptions::default());
let pdf = String::from_utf8_lossy(&pdf);
assert!(
pdf.contains("/Span <</ActualText <FEFF78147A76>>> BDC <00000000> Tj EMC"),
"{pdf}"
);
assert!(
pdf.contains(
"Tf 3 Tr 10.00 220.00 Td /Span <</ActualText <FEFF7814>>> BDC <0000> Tj EMC ET Q"
),
"{pdf}"
);
assert_eq!(pdf.matches("/ActualText").count(), 2, "{pdf}");
let a = raw.glyph_index('a').unwrap().0;
let mut page = Page::new(200.0, 300.0);
page.ops.push(Op::text(
face,
10.0,
10.0,
200.0,
vec![a],
[0.0, 0.0, 0.0],
"\u{1D44E}".to_string(),
));
let pdf = emit(&fonts, std::slice::from_ref(&page), PdfOptions::default());
let pdf = String::from_utf8_lossy(&pdf);
assert!(
pdf.contains(&format!(
"/Span <</ActualText <FEFFD835DC4E>>> BDC <{a:04X}> Tj EMC"
)),
"{pdf}"
);
}
#[test]
fn repeated_image_objects_share_only_identical_encoded_samples_and_alpha_owners() {
let mut jpeg = Vec::new();
image::codecs::jpeg::JpegEncoder::new_with_quality(&mut jpeg, 90)
.encode(
&[0, 0, 0, 127, 64, 32, 255, 255, 255],
3,
1,
image::ExtendedColorType::Rgb8,
)
.unwrap();
let jpeg_before = jpeg.clone();
let pixels_a = vec![0, 1, 127, 128, 254, 255];
let pixels_b = vec![255, 254, 128, 127, 1, 0];
let alpha = vec![64, 192];
let mut pages = Vec::new();
for page_number in 1..=2 {
let mut page = Page::new(200.0, 300.0);
page.number = page_number;
for x in [10.0, 50.0] {
page.ops.push(Op::Jpeg {
x,
y: 20.0,
dw: 30.0,
dh: 10.0,
width: 3,
height: 1,
bytes: jpeg.clone(),
components: 3,
crop: None,
rotate_deg: 0.0,
oval: false,
});
}
for (x, pixels) in [(90.0, &pixels_a), (130.0, &pixels_b)] {
page.ops.push(Op::Rgb {
x,
y: 20.0,
dw: 30.0,
dh: 10.0,
width: 2,
height: 1,
bytes: pixels.clone(),
alpha: Some(alpha.clone()),
crop: None,
rotate_deg: 0.0,
oval: false,
});
}
pages.push(page);
}
for compress in [false, true] {
let bytes = emit(
&bundled_fonts(),
&pages,
PdfOptions {
compress,
..PdfOptions::default()
},
);
let xref = bytes.windows(6).rposition(|w| w == b"\nxref\n").unwrap() + 1;
let tail = std::str::from_utf8(&bytes[xref..]).unwrap();
let count: usize = tail
.lines()
.nth(1)
.unwrap()
.split_whitespace()
.nth(1)
.unwrap()
.parse()
.unwrap();
let offsets = tail
.lines()
.skip(3)
.take(count - 1)
.map(|row| row[..10].parse::<usize>().unwrap())
.collect::<Vec<_>>();
let mut objects = Vec::new();
for (i, &start) in offsets.iter().enumerate() {
let end = offsets.get(i + 1).copied().unwrap_or(xref);
let head = format!("{} 0 obj\n", i + 1);
assert_eq!(&bytes[start..start + head.len()], head.as_bytes());
let complete = &bytes[start + head.len()..end];
objects.push(complete.strip_suffix(b"\nendobj\n").unwrap());
}
let image_ids = objects
.iter()
.enumerate()
.filter(|(_, obj)| obj.windows(15).any(|w| w == b"/Subtype /Image"))
.map(|(i, _)| i + 1)
.collect::<Vec<_>>();
assert_eq!(
image_ids.len(),
4,
"one shared JPEG, one shared mask, two distinct RGB samples"
);
let mut resources = Vec::new();
let mut paints = Vec::new();
for object in &objects {
let dictionary = String::from_utf8_lossy(object);
if dictionary.contains("/Type /Page ") {
let mut ids = Vec::new();
for name in ["Im1", "Im2", "Im3", "Im4"] {
ids.push(
dictionary
.split(&format!("/{name} "))
.nth(1)
.unwrap()
.split_whitespace()
.next()
.unwrap()
.parse::<usize>()
.unwrap(),
);
}
assert_eq!(ids[0], ids[1]);
assert_ne!(ids[0], ids[2]);
assert_ne!(ids[2], ids[3]);
resources.push(ids);
}
if dictionary.contains("\nstream\n")
&& !dictionary.contains("/Subtype /Image")
&& !dictionary.contains("/Length1 ")
&& !dictionary.contains("/CMap")
{
let decoded = stream(object);
if decoded.windows(4).any(|w| w == b"/Im1") {
paints.push(String::from_utf8(decoded).unwrap());
}
}
}
assert_eq!(resources.len(), 2);
assert_eq!(resources[0], resources[1]);
let ids = &resources[0];
assert_eq!(stream(objects[ids[0] - 1]), jpeg);
assert_eq!(stream(objects[ids[2] - 1]), pixels_a);
assert_eq!(stream(objects[ids[3] - 1]), pixels_b);
let mask_id = |object: &[u8]| {
String::from_utf8_lossy(object)
.split("/SMask ")
.nth(1)
.unwrap()
.split_whitespace()
.next()
.unwrap()
.parse::<usize>()
.unwrap()
};
let mask_a = mask_id(objects[ids[2] - 1]);
let mask_b = mask_id(objects[ids[3] - 1]);
assert_eq!(mask_a, mask_b);
assert_eq!(stream(objects[mask_a - 1]), alpha);
assert_eq!(paints.len(), 2);
for paint in paints {
for (n, x) in [(1, 10), (2, 50), (3, 90), (4, 130)] {
assert!(
paint.contains(&format!("q 30.00 0 0 10.00 {x}.00 20.00 cm /Im{n} Do Q\n"))
);
}
assert_eq!(paint.matches(" Do Q\n").count(), 4);
}
}
assert_eq!(jpeg, jpeg_before);
for page in pages {
for (i, op) in page.ops.iter().enumerate() {
match op {
Op::Jpeg { bytes, .. } => assert_eq!(bytes, &jpeg),
Op::Rgb {
bytes,
alpha: plane,
..
} => {
assert_eq!(bytes, if i == 2 { &pixels_a } else { &pixels_b });
assert_eq!(plane.as_ref(), Some(&alpha));
}
_ => panic!("authored image operation changed"),
}
}
}
}
}
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod symbol_text_branch_tests {
use super::*;
#[test]
fn symbol_face_codes_read_as_their_latin_text() {
let symbol = |low: u32| symbol_font_text(char::from_u32(0xF000 + low).unwrap(), true);
for (low, want) in [
(0x6D, 'µ'),
(0xA4, '⁄'),
(0xA6, 'ƒ'),
(0xB7, '•'),
(0xB8, '÷'),
(0xBC, '…'),
(0xD8, '¬'),
(0x41, 'A'),
] {
assert_eq!(symbol(low), want, "{low:#x}");
}
for low in [0x6D, 0xA4, 0xA6, 0xB7, 0xB8, 0xBC, 0xD8] {
let c = char::from_u32(0xF000 + low).unwrap();
assert_eq!(symbol_font_text(c, false), char::from_u32(low).unwrap());
}
assert_eq!(symbol_font_text('x', true), 'x');
}
}
#[cfg(test)]
#[cfg_attr(all(coverage_nightly, test), coverage(off))]
mod chrome_branch_tests {
use super::*;
#[test]
fn the_markup_pane_needs_room_and_falls_back_off_the_table() {
assert!(markup_chrome(100.0, 800.0, 10_000.0).is_none());
let pt = |px: f32| px * 72.0 / 300.0;
let listed = markup_chrome(pt(2480.0), pt(3508.0), pt(300.0)).unwrap();
assert!((listed.k - 223.0 / 300.0).abs() < 1e-6, "{}", listed.k);
let unlisted = markup_chrome(pt(2480.0), pt(3508.0), pt(417.0)).unwrap();
assert!(unlisted.k > 0.0 && unlisted.k < 1.0);
assert!(
(unlisted.k * 300.0).fract().abs() < 1e-3,
"floored to a 300th"
);
}
#[test]
fn hiding_and_scaling_leave_non_text_ops_alone() {
let line = Op::Line {
x1: 0.0,
y1: 0.0,
x2: 1.0,
y2: 1.0,
width: 0.5,
color: [0.0; 3],
};
let Op::Line { x2, width, .. } = line.hidden().scaled(2.0) else {
panic!("a line stays a line");
};
assert_eq!((x2, width), (1.0, 0.5));
}
}