use f_office_fonts::{FontDb, FontId};
use f_office_paint::testing::{
CARLITO, carlito, encoded, encoded_with_profile, image_item, page, pt, rect, zero_png,
};
use f_office_paint::{
self as paint, Clip, DisplayList, Glyph, GlyphRun, GradientItem, GradientStop, Group,
GroupClip, ImageFault, ImageFormat, Item, Orientation, Page, Painted, PathCommand, PathItem,
Rect, Rgb,
};
use f_office_units::Length;
use hayro::hayro_interpret::font::GlyphRun as ShownRun;
use hayro::hayro_interpret::hayro_cmap::BfString;
use hayro::hayro_interpret::pattern::Pattern;
use hayro::hayro_interpret::shading::ShadingType;
use hayro::hayro_interpret::{
BlendMode, ClipPath, Context, Device, DrawMode, DrawProps, FillRule, Image, ImageDrawProps,
InterpreterCache, InterpreterSettings, Paint, SoftMask, interpret_page,
};
use hayro::hayro_syntax::object::dict::keys::MEDIA_BOX;
use hayro::hayro_syntax::object::{Array, ObjectIdentifier};
use hayro::hayro_syntax::{Filter, Pdf};
use hayro::kurbo::{Affine, BezPath, Join, Point, Rect as Area, Shape};
use super::{Error, Warning, write_pdf as write_warned};
const POINT: i64 = Length::UNITS_PER_POINT;
const RED: Rgb = Rgb { r: 200, g: 0, b: 0 };
const TEAL: Rgb = Rgb {
r: 10,
g: 120,
b: 130,
};
fn write_pdf(list: &DisplayList, fonts: &FontDb) -> Result<Vec<u8>, Error> {
write_warned(list, fonts).map(|written| written.value)
}
#[derive(Clone, Copy)]
struct Placement {
x: i64,
y: i64,
extra: i64,
rise: i64,
}
impl Placement {
fn at(x: i64, y: i64) -> Self {
Self {
x,
y,
extra: 0,
rise: 0,
}
}
}
fn run(fonts: &FontDb, font: FontId, text: &str, size: Length, color: Rgb, at: Placement) -> Item {
let units_per_em = i64::from(fonts.metrics(font).unwrap().units_per_em);
let mut x = at.x;
let mut glyphs = Vec::new();
for (index, (start, ch)) in text.char_indices().enumerate() {
let id = fonts.glyph_id(font, ch).unwrap();
let rise = if index % 2 == 1 { at.rise } else { 0 };
glyphs.push(Glyph {
id,
x: Length::from_units(x),
y: Length::from_units(at.y - rise),
text_start: u32::try_from(start).unwrap(),
text_end: u32::try_from(start + ch.len_utf8()).unwrap(),
});
let advance = i64::from(fonts.advance(font, id).unwrap());
x += advance * size.units() / units_per_em + at.extra;
}
Item::Glyphs(GlyphRun {
font,
size,
color,
text: text.to_owned(),
glyphs,
outline: None,
filled: true,
effect: false,
turn: None,
})
}
fn sample(fonts: &FontDb, font: FontId) -> DisplayList {
let size = |units| Length::from_units(units);
let first = Page::new(
pt(612),
pt(792),
Orientation::Portrait,
vec![
run(
fonts,
font,
"Hello, PDF world!",
pt(12),
Rgb::BLACK,
Placement::at(1_828_813, 1_841_517),
),
Item::Rect(Rect {
x: size(1_828_813),
y: size(1_900_000),
width: pt(80),
height: size(12_700),
color: Rgb::BLACK,
}),
run(
fonts,
font,
"Justified text, with spaces.",
size(266_700),
RED,
Placement {
extra: 4_321,
..Placement::at(1_828_813, 2_500_133)
},
),
run(
fonts,
font,
"x2y3",
pt(11),
TEAL,
Placement {
rise: 76_200,
..Placement::at(2_000_000, 3_000_000)
},
),
],
);
let second = Page::new(
size(7_620_127),
pt(200),
Orientation::Portrait,
vec![
rect(10, 10, 100, 30, TEAL),
run(
fonts,
font,
"Ünïcödé €",
pt(24),
Rgb::BLACK,
Placement::at(pt(20).units(), pt(100).units()),
),
run(
fonts,
font,
"Z",
pt(30),
RED,
Placement::at(pt(200).units(), pt(150).units()),
),
],
);
DisplayList::new(vec![first, second])
}
#[derive(Clone, Debug, PartialEq)]
struct Shown {
text: String,
x: f64,
y: f64,
color: [u8; 4],
}
#[derive(Clone, Debug, PartialEq)]
struct Filled {
bounds: [f64; 4],
color: [u8; 4],
even_odd: bool,
}
#[derive(Clone, Debug, PartialEq)]
struct Shaded {
axis: (Point, Point),
extend: [bool; 2],
colors: Vec<[u8; 3]>,
}
impl Shaded {
fn of(paint: &Paint<'_>) -> Option<Self> {
let Paint::Pattern(pattern) = paint else {
return None;
};
let Pattern::Shading(shading) = &**pattern else {
return None;
};
let ShadingType::RadialAxial {
coords,
domain,
function,
extend,
axial: true,
} = &*shading.shading.shading_type
else {
return None;
};
let [x0, y0, x1, y1, ..] = coords.map(f64::from);
let axis = (
shading.matrix * Point::new(x0, y0),
shading.matrix * Point::new(x1, y1),
);
let colors = (0..=20_u8)
.map(|step| {
let input = domain[0] + f32::from(step) / 20.0 * (domain[1] - domain[0]);
let mut out = [0.0_f32; 3];
function.eval(&[input], &mut out).unwrap();
#[expect(clippy::cast_possible_truncation, clippy::cast_sign_loss)]
out.map(|value| (value * 255.0).round().clamp(0.0, 255.0) as u8)
})
.collect();
Some(Self {
axis,
extend: *extend,
colors,
})
}
}
#[derive(Default)]
struct Reader {
size: (f32, f32),
shown: Vec<Shown>,
leans: Vec<f64>,
stroked: Vec<([u8; 4], f32, Join)>,
filled: Vec<Filled>,
shaded: Vec<Shaded>,
drawn: Vec<Drawn>,
clips: Vec<Area>,
opacities: Vec<f32>,
}
#[derive(Clone, Debug, PartialEq)]
struct Drawn {
bounds: [f64; 4],
clip: Option<[f64; 4]>,
pixels: (u32, u32),
jpeg: Option<Vec<u8>>,
object: ObjectIdentifier,
opacity: f32,
sample: Option<([u8; 3], u8)>,
sides: [f64; 2],
turn: [f64; 4],
}
fn corners(area: Area) -> [f64; 4] {
[area.x0, area.y0, area.x1, area.y1]
}
fn color_of(paint: &Paint<'_>) -> [u8; 4] {
match paint {
Paint::Color(color) => color.to_rgba().to_rgba8(),
Paint::Pattern(_) => [0; 4],
}
}
impl<'a> Device<'a> for Reader {
fn draw_glyph_run(&mut self, run: &ShownRun<'_, 'a>, props: DrawProps<'a>, mode: &DrawMode) {
let color = color_of(&props.paint);
if let DrawMode::Stroke(stroke) = mode {
self.stroked
.push((color, stroke.line_width, stroke.line_join));
return;
}
self.leans.extend(run.glyphs().iter().map(|glyph| {
let [_, _, c, d, _, _] = (props.transform * glyph.transform()).as_coeffs();
c / -d
}));
self.shown.extend(run.glyphs().iter().map(|glyph| {
let origin = props.transform * glyph.transform() * Point::ORIGIN;
let text = match glyph.as_unicode() {
Some(BfString::Char(ch)) => ch.to_string(),
Some(BfString::String(text)) => text,
None => String::from("\u{fffd}"),
};
Shown {
text,
x: origin.x,
y: origin.y,
color,
}
}));
}
fn pop_transparency_group(&mut self) {
self.opacities.pop();
}
fn draw_path(&mut self, path: &BezPath, props: DrawProps<'a>, mode: &DrawMode) {
let area = (props.transform * path.clone()).bounding_box();
self.shaded.extend(Shaded::of(&props.paint));
self.filled.push(Filled {
bounds: [area.x0, area.y0, area.x1, area.y1],
color: color_of(&props.paint),
even_odd: matches!(mode, DrawMode::Fill(FillRule::EvenOdd)),
});
}
fn draw_image(&mut self, image: Image<'a, '_>, props: ImageDrawProps<'a>) {
let Image::Raster(raster) = &image else {
return;
};
let pixels = (image.width(), image.height());
let whole = Area::new(0.0, 0.0, f64::from(pixels.0), f64::from(pixels.1));
let stream = raster.stream();
let jpeg = (stream.filters().as_slice() == [Filter::DctDecode])
.then(|| stream.raw_data().into_owned());
let mut sample = None;
raster.with_rgba(
|data, alpha| {
use hayro::hayro_interpret::ImageData;
let color = match data {
ImageData::Rgb(rgb) => rgb.data.get(..3).and_then(|v| v.try_into().ok()),
ImageData::Luma(luma) => luma.data.first().map(|&v| [v; 3]),
};
let alpha = alpha.and_then(|a| a.data.first().copied()).unwrap_or(255);
sample = color.map(|color| (color, alpha));
},
None,
);
let origin = props.transform * Point::ORIGIN;
let row = props.transform * Point::new(f64::from(pixels.0), 0.0) - origin;
let column = props.transform * Point::new(0.0, f64::from(pixels.1)) - origin;
let sides = [row.hypot(), column.hypot()];
let turn = [
row.x / sides[0],
row.y / sides[0],
column.x / sides[1],
column.y / sides[1],
];
self.drawn.push(Drawn {
sides,
turn,
bounds: corners((props.transform * whole.to_path(0.1)).bounding_box()),
clip: self
.clips
.iter()
.copied()
.reduce(|a, b| a.intersect(b))
.map(corners),
pixels,
jpeg,
object: stream.obj_id(),
opacity: self.opacities.iter().product(),
sample,
});
}
fn push_clip_path(&mut self, clip: &ClipPath) {
self.clips.push(clip.path.bounding_box());
}
fn pop_clip(&mut self) {
self.clips.pop();
}
fn push_transparency_group(&mut self, opacity: f32, _: Option<SoftMask<'a>>, _: BlendMode) {
self.opacities.push(opacity);
}
}
fn read(pdf: &[u8]) -> Vec<Reader> {
let pdf = Pdf::new(pdf.to_vec()).unwrap();
let cache = InterpreterCache::new();
let settings = InterpreterSettings::default();
let mut pages = Vec::new();
for page in pdf.pages().iter() {
let size = page.render_dimensions();
let bounds = Area::new(0.0, 0.0, f64::from(size.0), f64::from(size.1));
let media = page.raw().get::<Array<'_>>(MEDIA_BOX).unwrap();
let top = media.iter::<f64>().nth(3).unwrap();
let transform = Affine::new([1.0, 0.0, 0.0, -1.0, 0.0, top]);
let mut context = Context::new(transform, bounds, &cache, page.xref(), settings.clone());
let mut reader = Reader {
size,
..Reader::default()
};
interpret_page(page, &mut context, &mut reader);
pages.push(reader);
}
pages
}
fn points(length: Length) -> f64 {
f64::from(i32::try_from(length.units()).unwrap()) / per_point()
}
fn per_point() -> f64 {
f64::from(i32::try_from(POINT).unwrap())
}
fn same_place(points: f64, expected: f64) -> bool {
((points - expected) * per_point()).abs() < 0.5
}
fn expected(page: &Page) -> Vec<Shown> {
let runs = page.painted().into_iter().filter_map(|item| match item {
Painted::Glyphs(run) => Some(run),
Painted::Rect(_)
| Painted::Path(_)
| Painted::Gradient(_)
| Painted::Image(_)
| Painted::ClipStart(_)
| Painted::ClipEnd => None,
});
let mut shown = Vec::new();
for run in runs {
let color = [run.color.r, run.color.g, run.color.b, 255];
shown.extend(run.glyphs.iter().map(|glyph| Shown {
text: run.glyph_text(glyph).unwrap().to_owned(),
x: points(glyph.x),
y: points(glyph.y),
color,
}));
}
shown
}
fn largest_position_error(list: &DisplayList, pdf: &[u8]) -> f64 {
let read = read(pdf);
assert_eq!(read.len(), list.pages().len());
let mut largest: f64 = 0.0;
for (read, page) in read.iter().zip(list.pages()) {
let expected = expected(page);
assert_eq!(read.shown.len(), expected.len());
for (shown, expected) in read.shown.iter().zip(&expected) {
largest = largest.max((shown.x - expected.x).hypot(shown.y - expected.y));
}
}
largest * per_point()
}
#[test]
fn writes_one_page_of_the_same_size_for_each_page() {
let (fonts, font) = carlito().unwrap();
let list = sample(&fonts, font);
let pdf = write_pdf(&list, &fonts).unwrap();
let sizes: Vec<(f32, f32)> = read(&pdf).into_iter().map(|page| page.size).collect();
assert_eq!(sizes.len(), list.pages().len());
for (size, page) in sizes.iter().zip(list.pages()) {
assert!(
(f64::from(size.0) - points(page.width())).abs() < 0.000_1,
"{size:?}"
);
assert!(
(f64::from(size.1) - points(page.height())).abs() < 0.000_1,
"{size:?}"
);
}
assert_eq!(sizes, [(612.0, 792.0), (300.005, 200.0)]);
}
#[test]
fn places_each_glyph_at_its_display_list_origin() {
let (fonts, font) = carlito().unwrap();
let list = sample(&fonts, font);
let pdf = write_pdf(&list, &fonts).unwrap();
let error = largest_position_error(&list, &pdf);
assert!(error < 0.5, "{error}");
}
fn operators(pdf: &[u8], name: &[u8]) -> usize {
let pdf = Pdf::new(pdf.to_vec()).unwrap();
pdf.objects()
.into_iter()
.filter_map(hayro::hayro_syntax::object::Object::into_stream)
.filter_map(|stream| stream.decoded().ok())
.map(|content| {
content
.split(u8::is_ascii_whitespace)
.filter(|word| word.starts_with(name))
.count()
})
.sum()
}
#[test]
fn writes_a_run_as_one_text_object_with_each_glyph_at_its_own_half_emu() {
let (fonts, font) = carlito().unwrap();
let text = "Each glyph of a long justified line keeps its own place in one text object.";
let size = Length::from_units(11 * POINT);
let items = [100 * POINT, 200 * POINT + 7].map(|y| {
let at = Placement {
x: 72 * POINT + 13,
y,
extra: 1_237,
rise: 0,
};
run(&fonts, font, text, size, RED, at)
});
let list = DisplayList::new(vec![page(612, 792, items.to_vec())]);
let pdf = write_pdf(&list, &fonts).unwrap();
assert_eq!(operators(&pdf, b"BT"), 4);
let read = read(&pdf).remove(0);
let expected = expected(&list.pages()[0]);
assert_eq!(read.shown.len(), expected.len());
let positions = operators(&pdf, b"Tm");
assert!(
positions * 4 <= expected.len(),
"{positions} text positions"
);
for (shown, glyph) in read.shown.iter().zip(&expected) {
assert!(
same_place(shown.x, glyph.x) && same_place(shown.y, glyph.y),
"{shown:?} {glyph:?}"
);
}
}
#[test]
fn places_a_glyph_with_a_text_span_of_its_own_at_its_own_half_emu() {
let (fonts, font) = carlito().unwrap();
let space = fonts.glyph_id(font, ' ').unwrap();
let words = [
"Each", "line", "of", "this", "test", "has", "spaces", "and", "fixed",
];
let text = (0..36)
.map(|index| words[index % words.len()])
.collect::<Vec<_>>()
.join(" \u{a0}");
let size = Length::from_units(11 * POINT + 1_016);
let items = (0..12).map(|line| {
let at = Placement {
x: 36 * POINT + 977 * line,
y: (60 + 20 * line) * POINT + 3,
extra: 1_237 + 101 * line,
rise: 0,
};
let mut item = run(&fonts, font, &text, size, RED, at);
if let Item::Glyphs(run) = &mut item {
for glyph in &mut run.glyphs {
if run.text[glyph.text_start as usize..].starts_with('\u{a0}') {
glyph.id = space;
}
}
}
item
});
let list = DisplayList::new(vec![page(1_400, 400, items.collect())]);
let pdf = write_pdf(&list, &fonts).unwrap();
let key = b"/ActualText";
let spans: usize = Pdf::new(pdf.clone())
.unwrap()
.objects()
.into_iter()
.filter_map(hayro::hayro_syntax::object::Object::into_stream)
.filter_map(|stream| stream.decoded().ok())
.map(|content| content.windows(key.len()).filter(|w| w == key).count())
.sum();
assert!(spans >= 12, "{spans} text spans");
let read = read(&pdf).remove(0);
let expected = expected(&list.pages()[0]);
assert_eq!(read.shown.len(), expected.len());
for (shown, glyph) in read.shown.iter().zip(&expected) {
assert!(
same_place(shown.x, glyph.x) && same_place(shown.y, glyph.y),
"{shown:?} {glyph:?}"
);
}
}
fn form_boxes(pdf: &[u8]) -> Vec<Vec<f64>> {
let key = b"/BBox";
(0..pdf.len())
.filter(|&at| pdf[at..].starts_with(key))
.map(|at| {
let rest = &pdf[at + key.len()..];
let start = rest.iter().position(|&byte| byte == b'[').unwrap() + 1;
let end = rest.iter().position(|&byte| byte == b']').unwrap();
std::str::from_utf8(&rest[start..end])
.unwrap()
.split_ascii_whitespace()
.map(|number| number.parse().unwrap())
.collect()
})
.collect()
}
#[test]
fn bounds_the_drawing_of_a_run_past_its_last_glyph() {
let (fonts, font) = carlito().unwrap();
let item = run(
&fonts,
font,
"Basic paragraph",
pt(24),
RED,
Placement::at(0, 1_000_000),
);
let Item::Glyphs(glyphs) = &item else {
unreachable!("a run gives glyphs");
};
let last = glyphs.glyphs.last().unwrap();
let units = f64::from(fonts.metrics(font).unwrap().units_per_em);
let advance = f64::from(fonts.advance(font, last.id).unwrap()) / units * 24.0;
let right = crate::exact_points(last.x) + advance;
let pdf = write_pdf(&DisplayList::new(vec![page(300, 100, vec![item])]), &fonts).unwrap();
assert_eq!(operators(&pdf, b"BT"), 1, "the run is one text object");
let boxes = form_boxes(&pdf);
assert_ne!(boxes, Vec::<Vec<f64>>::new());
assert!(
boxes.iter().all(|area| area[2] >= right),
"{boxes:?} {right}"
);
}
fn reads_as(points: f64, units: i64) -> bool {
same_place(
points,
f64::from(i32::try_from(units).unwrap()) / per_point(),
)
}
fn low_on_a_large_page(fonts: &FontDb, font: FontId) -> DisplayList {
let line = "Places low on a large page come back at their own half-EMU, glyph by glyph.";
let justified = run(
fonts,
font,
line,
Length::from_units(279_407),
Rgb::BLACK,
Placement {
extra: 4_321,
rise: 1_777,
..Placement::at(pt(40).units() + 7, pt(1_100).units() + 13)
},
);
let mut turned = run(
fonts,
font,
"Turned",
pt(14),
RED,
Placement::at(pt(700).units() + 11, pt(1_000).units() + 5),
);
if let Item::Glyphs(glyphs) = &mut turned {
glyphs.turn = Some(paint::Turn {
xx: 0,
yx: 1_000_000,
xy: -1_000_000,
yy: 0,
});
let first = glyphs.glyphs[0].clone();
for glyph in &mut glyphs.glyphs {
let along = glyph.x.units() - first.x.units();
glyph.x = first.x;
glyph.y = Length::from_units(first.y.units() + along);
}
}
let at = |units: i64| Length::from_units(units);
let filled = Item::Rect(Rect {
x: at(pt(600).units() + 3),
y: at(pt(1_150).units() + 9),
width: at(pt(200).units() + 1),
height: at(12_701),
color: TEAL,
});
let corner = |x: i64, y: i64| paint::Point { x: at(x), y: at(y) };
let path = Item::Path(PathItem {
commands: vec![
PathCommand::MoveTo(corner(pt(520).units() + 1, pt(1_120).units() + 3)),
PathCommand::LineTo(corner(pt(560).units() + 5, pt(1_121).units() + 7)),
PathCommand::LineTo(corner(pt(540).units() + 9, pt(1_140).units() + 11)),
PathCommand::Close,
],
color: RED,
fill_rule: paint::FillRule::NonZero,
});
let png = encoded(gray(4, 3), image::ImageFormat::Png).unwrap();
let mut picture = image_item(&png, (600, 1_050, 40, 30), None);
if let Item::Image(image) = &mut picture {
image.x = at(image.x.units() + 17);
image.y = at(image.y.units() + 19);
image.width = at(image.width.units() + 3);
}
let items = vec![justified, turned, filled, path, picture];
DisplayList::new(vec![Page::new(
Length::from_units(16_838 * 1_270),
Length::from_units(23_811 * 1_270),
Orientation::Portrait,
items,
)])
}
#[test]
fn gives_each_place_back_at_its_own_half_emu_low_on_a_large_page() {
let (fonts, font) = carlito().unwrap();
let list = low_on_a_large_page(&fonts, font);
let pdf = write_pdf(&list, &fonts).unwrap();
let read = read(&pdf).remove(0);
let expected = expected(&list.pages()[0]);
assert_eq!(read.shown.len(), expected.len());
for (shown, glyph) in read.shown.iter().zip(&expected) {
assert!(
same_place(shown.x, glyph.x) && same_place(shown.y, glyph.y),
"{shown:?} {glyph:?}"
);
}
let [rect, path] = [&read.filled[0], &read.filled[1]];
let rect_edges = [600 * POINT + 3, 1_150 * POINT + 9, 800 * POINT + 4, 0];
let rect_bottom = 1_150 * POINT + 9 + 12_701;
let rect_units = [rect_edges[0], rect_edges[1], rect_edges[2], rect_bottom];
let path_units = [
520 * POINT + 1,
1_120 * POINT + 3,
560 * POINT + 5,
1_140 * POINT + 11,
];
for (bounds, units) in [(rect.bounds, rect_units), (path.bounds, path_units)] {
let read_back = bounds.iter().zip(units).all(|(&p, u)| reads_as(p, u));
assert!(read_back, "{bounds:?} {units:?}");
}
let image = [
600 * POINT + 17,
1_050 * POINT + 19,
640 * POINT + 20,
1_080 * POINT + 19,
];
let bounds = read.drawn[0].bounds;
let read_back = bounds.iter().zip(image).all(|(&p, u)| reads_as(p, u));
assert!(read_back, "{bounds:?} {image:?}");
}
#[test]
fn keeps_the_text_and_color_of_each_glyph() {
let (fonts, font) = carlito().unwrap();
let list = sample(&fonts, font);
let pdf = write_pdf(&list, &fonts).unwrap();
for (read, page) in read(&pdf).iter().zip(list.pages()) {
let texts = |glyphs: &[Shown]| glyphs.iter().map(|g| g.text.clone()).collect::<String>();
let colors = |glyphs: &[Shown]| glyphs.iter().map(|g| g.color).collect::<Vec<_>>();
let expected = expected(page);
assert_eq!(texts(&read.shown), texts(&expected));
assert_eq!(colors(&read.shown), colors(&expected));
}
let runs: String = list.pages()[0]
.items()
.iter()
.filter_map(|item| match item {
Item::Glyphs(run) => Some(run.text.as_str()),
Item::Rect(_) | Item::Path(_) | Item::Gradient(_) | Item::Image(_) | Item::Group(_) => {
None
}
})
.collect();
assert_eq!(runs, "Hello, PDF world!Justified text, with spaces.x2y3");
}
fn outlined_page(width: Length) -> Reader {
let (fonts, font) = carlito().unwrap();
let mut item = run(&fonts, font, "Hi", pt(24), RED, Placement::at(0, 1_000_000));
if let Item::Glyphs(glyphs) = &mut item {
glyphs.outline = Some(paint::Outline {
width,
color: Rgb {
r: 255,
g: 255,
b: 0,
},
join: paint::Join::Round,
});
}
let list = DisplayList::new(vec![page(200, 100, vec![item])]);
read(&write_pdf(&list, &fonts).unwrap()).remove(0)
}
#[test]
fn strokes_each_glyph_of_a_run_with_an_outline_once_with_round_joins() {
let page = outlined_page(Length::from_emus(11_112).unwrap());
assert_eq!(page.stroked.len(), 1);
let all = page.stroked.iter().all(|&(color, width, join)| {
color == [255, 255, 0, 255] && (width - 0.875).abs() < 1e-4 && matches!(join, Join::Round)
});
assert!(all, "{:?}", page.stroked);
let text: String = page.shown.iter().map(|g| g.text.as_str()).collect();
assert_eq!(text, "Hi");
assert_eq!(page.shown[0].color, [200, 0, 0, 255]);
}
#[test]
fn leaves_out_an_outline_without_width() {
assert_eq!(outlined_page(Length::ZERO).stroked.len(), 0);
}
#[test]
fn writes_the_same_bytes_every_time() {
let (fonts, font) = carlito().unwrap();
let list = sample(&fonts, font);
let first = write_pdf(&list, &fonts).unwrap();
let (other_fonts, other_font) = carlito().unwrap();
let second = write_pdf(&sample(&other_fonts, other_font), &other_fonts).unwrap();
assert_eq!(first, second);
assert!(first.starts_with(b"%PDF-1.7"));
}
#[test]
fn shows_a_glyph_for_several_characters_once() {
let (fonts, font) = carlito().unwrap();
let ligature = fonts.glyph_id(font, '\u{fb01}').unwrap();
let mut item = run(
&fonts,
font,
"a fine",
pt(12),
Rgb::BLACK,
Placement::at(0, pt(50).units()),
);
let Item::Glyphs(glyph_run) = &mut item else {
unreachable!()
};
glyph_run.glyphs[2].id = ligature;
glyph_run.glyphs[2].text_end = 4;
glyph_run.glyphs.remove(3);
let list = DisplayList::new(vec![page(100, 100, vec![item])]);
let pdf = write_pdf(&list, &fonts).unwrap();
let shown = &read(&pdf)[0].shown;
let texts: Vec<&str> = shown.iter().map(|glyph| glyph.text.as_str()).collect();
assert_eq!(texts, ["a", " ", "fi", "n", "e"]);
assert!(largest_position_error(&list, &pdf) < 0.5);
}
#[test]
fn skips_runs_without_glyphs_or_size_and_rectangles_without_area() {
let (fonts, font) = carlito().unwrap();
let empty = Item::Glyphs(GlyphRun {
font,
size: pt(12),
color: Rgb::BLACK,
text: String::new(),
glyphs: Vec::new(),
outline: None,
filled: true,
effect: false,
turn: None,
});
let sizeless = run(
&fonts,
font,
"gone",
Length::ZERO,
Rgb::BLACK,
Placement::at(0, 0),
);
let flat = rect(1, 1, 0, 5, RED);
let thin = rect(1, 1, 5, 0, RED);
let page = |items| {
DisplayList::new(vec![Page::new(
pt(10),
pt(10),
Orientation::Portrait,
items,
)])
};
let skipped = write_pdf(&page(vec![empty, sizeless, flat, thin]), &fonts).unwrap();
assert_eq!(skipped, write_pdf(&page(vec![]), &fonts).unwrap());
let read = &read(&skipped)[0];
assert_eq!((read.shown.len(), read.filled.len()), (0, 0));
}
#[test]
fn fills_each_rectangle_at_its_place_in_its_color() {
let (fonts, font) = carlito().unwrap();
let list = sample(&fonts, font);
let filled: Vec<Vec<Filled>> = read(&write_pdf(&list, &fonts).unwrap())
.into_iter()
.map(|page| page.filled)
.collect();
let black = [0, 0, 0, 255];
let teal = [TEAL.r, TEAL.g, TEAL.b, 255];
let wanted = [
vec![([72.0, 74.803, 152.0, 75.303], black)],
vec![([10.0, 10.0, 110.0, 40.0], teal)],
];
for (filled, wanted) in filled.iter().zip(&wanted) {
assert_eq!(filled.len(), wanted.len());
for (area, (bounds, color)) in filled.iter().zip(wanted) {
assert_eq!(area.color, *color);
for (edge, wanted_edge) in area.bounds.iter().zip(bounds) {
assert!((edge - wanted_edge).abs() < 0.001, "{area:?}");
}
}
}
}
#[test]
fn fills_rectangles_with_negative_sides_from_the_other_edge() {
let fonts = FontDb::new();
let page = |item| {
DisplayList::new(vec![Page::new(
pt(10),
pt(10),
Orientation::Portrait,
vec![item],
)])
};
let forward = write_pdf(&page(rect(2, 3, 4, 5, RED)), &fonts).unwrap();
let backward = write_pdf(&page(rect(6, 8, -4, -5, RED)), &fonts).unwrap();
assert_eq!(forward, backward);
let area = &read(&forward)[0].filled[0];
assert_eq!(area.bounds, [2.0, 3.0, 6.0, 8.0]);
}
#[test]
fn fills_each_path_with_its_curves_color_and_rule() {
let at = |x, y| paint::Point { x: pt(x), y: pt(y) };
let commands = vec![
PathCommand::MoveTo(at(1, 1)),
PathCommand::LineTo(at(9, 1)),
PathCommand::LineTo(at(9, 5)),
PathCommand::QuadTo(at(9, 9), at(5, 9)),
PathCommand::CubicTo(at(3, 9), at(1, 7), at(1, 5)),
PathCommand::Close,
];
let path = |fill_rule| {
Item::Path(PathItem {
commands: commands.clone(),
color: TEAL,
fill_rule,
})
};
let empty = Item::Path(PathItem {
commands: Vec::new(),
color: RED,
fill_rule: paint::FillRule::NonZero,
});
let list = DisplayList::new(vec![Page::new(
pt(10),
pt(10),
Orientation::Portrait,
vec![
path(paint::FillRule::NonZero),
path(paint::FillRule::EvenOdd),
empty,
],
)]);
let filled = &read(&write_pdf(&list, &FontDb::new()).unwrap())[0].filled;
let rules: Vec<bool> = filled.iter().map(|area| area.even_odd).collect();
assert_eq!(rules, [false, true]);
for area in filled {
assert_eq!(area.color, [TEAL.r, TEAL.g, TEAL.b, 255]);
for (edge, wanted) in area.bounds.iter().zip([1.0, 1.0, 9.0, 9.0]) {
assert!((edge - wanted).abs() < 0.001, "{area:?}");
}
}
}
#[test]
fn fills_a_path_with_an_axial_shading_that_gives_the_colors_of_its_gradient() {
let at = |x, y| paint::Point { x: pt(x), y: pt(y) };
let commands = vec![
PathCommand::MoveTo(at(100, 100)),
PathCommand::LineTo(at(300, 100)),
PathCommand::LineTo(at(300, 150)),
PathCommand::LineTo(at(100, 150)),
PathCommand::Close,
];
let stops = vec![
GradientStop::new(GradientStop::START, Rgb::WHITE),
GradientStop::new(250_000, TEAL),
GradientStop::new(500_000, RED),
GradientStop::new(500_000, Rgb { r: 0, g: 0, b: 90 }),
GradientStop::new(GradientStop::END, Rgb::BLACK),
];
let gradient = GradientItem::new(
commands,
paint::FillRule::NonZero,
(at(300, 100), at(-100, 100)),
stops,
);
let flat = GradientItem::new(
gradient.commands.clone(),
paint::FillRule::NonZero,
(at(300, 100), at(300, 100)),
gradient.stops.clone(),
);
let list = DisplayList::new(vec![Page::new(
pt(400),
pt(400),
Orientation::Portrait,
vec![Item::Gradient(gradient.clone()), Item::Gradient(flat)],
)]);
let page = &read(&write_pdf(&list, &FontDb::new()).unwrap())[0];
let [shaded] = page.shaded.as_slice() else {
panic!("not one shading: {:?}", page.shaded);
};
assert!(same_place(shaded.axis.0.x, 300.0) && same_place(shaded.axis.0.y, 100.0));
assert!(same_place(shaded.axis.1.x, -100.0) && same_place(shaded.axis.1.y, 100.0));
assert_eq!(shaded.extend, [true, true]);
for (step, color) in (0..=20_u32).zip(&shaded.colors) {
let wanted = gradient.color_at(i64::from(step * 50_000));
let close = |a: u8, b: u8| a.abs_diff(b) <= 1;
assert!(
close(color[0], wanted.r) && close(color[1], wanted.g) && close(color[2], wanted.b),
"{step}: {color:?} against {wanted:?}"
);
}
assert_eq!(page.filled.len(), 2);
assert_eq!(page.filled[1].color, [255, 255, 255, 255]);
}
#[test]
fn gives_the_far_edges_of_a_wide_fill_back_at_their_own_half_emus() {
let mut items = Vec::new();
let mut wanted = Vec::new();
for step in 0..200_i32 {
let left = 254_000 + 3_217 + step * 7;
let top = 508_000 + 1_009 + step * 13;
let right = 13_462_000 + 3_217 + step * 1_013;
let bottom = 15_748_000 + 2_111 + step * 911;
let at = |x: i32, y: i32| paint::Point {
x: Length::from_units(x.into()),
y: Length::from_units(y.into()),
};
items.push(Item::Path(PathItem {
commands: vec![
PathCommand::MoveTo(at(left, top)),
PathCommand::LineTo(at(right, top)),
PathCommand::LineTo(at(right, bottom)),
PathCommand::LineTo(at(left, bottom)),
PathCommand::Close,
],
color: TEAL,
fill_rule: paint::FillRule::NonZero,
}));
items.push(Item::Rect(Rect {
x: Length::from_units(left.into()),
y: Length::from_units(top.into()),
width: Length::from_units((right - left).into()),
height: Length::from_units((bottom - top).into()),
color: TEAL,
}));
wanted.extend([[left, top, right, bottom]; 2]);
}
let list = DisplayList::new(vec![Page::new(
pt(600),
pt(800),
Orientation::Portrait,
items,
)]);
let filled = &read(&write_pdf(&list, &FontDb::new()).unwrap())[0].filled;
assert_eq!(filled.len(), wanted.len());
for (area, wanted) in filled.iter().zip(&wanted) {
for (edge, units) in area.bounds.iter().zip(wanted) {
assert!(reads_as(*edge, i64::from(*units)), "{area:?} {wanted:?}");
}
}
}
#[test]
fn writes_no_metadata() {
let (fonts, font) = carlito().unwrap();
let pdf = write_pdf(&sample(&fonts, font), &fonts).unwrap();
assert!(!pdf.windows(9).any(|window| window == b"/Metadata"));
}
#[test]
fn rejects_lists_that_pdf_cannot_hold() {
let (fonts, font) = carlito().unwrap();
let page = |width, items| Page::new(width, pt(10), Orientation::Portrait, items);
let list = |pages| DisplayList::new(pages);
assert_eq!(write_pdf(&list(vec![]), &fonts), Err(Error::NoPages));
assert_eq!(
write_pdf(&list(vec![page(Length::ZERO, vec![])]), &fonts),
Err(Error::PageSize)
);
let text = run(&fonts, font, "ab", pt(10), Rgb::BLACK, Placement::at(0, 0));
let other = FontId::from_index(1);
let mut unknown_font = text.clone();
let mut unknown_glyph = text.clone();
let mut outside = text.clone();
let mut split = run(&fonts, font, "é", pt(10), Rgb::BLACK, Placement::at(0, 0));
if let (Item::Glyphs(a), Item::Glyphs(b), Item::Glyphs(c), Item::Glyphs(d)) = (
&mut unknown_font,
&mut unknown_glyph,
&mut outside,
&mut split,
) {
a.font = other;
b.glyphs[1].id = 60_000;
c.glyphs[1].text_end = 3;
d.glyphs[0].text_end = 1;
}
let one = |item| write_pdf(&list(vec![page(pt(10), vec![item])]), &fonts);
assert_eq!(one(unknown_font), Err(Error::UnknownFont(other)));
assert_eq!(
one(unknown_glyph),
Err(Error::UnknownGlyph {
font,
glyph: 60_000
})
);
assert_eq!(one(outside), Err(Error::TextRange));
assert_eq!(one(split), Err(Error::TextRange));
}
#[test]
fn gives_the_error_of_a_run_inside_a_clipped_group() {
let (fonts, font) = carlito().unwrap();
let mut text = run(&fonts, font, "ab", pt(10), Rgb::BLACK, Placement::at(0, 0));
if let Item::Glyphs(glyphs) = &mut text {
glyphs.glyphs[1].id = 60_000;
}
let clipped = Item::Group(Group {
items: vec![text],
clip: Some(GroupClip::rect(pt(1), pt(1), pt(5), pt(5))),
places: f_office_paint::GroupPlaces::Own,
});
let list = DisplayList::new(vec![Page::new(
pt(10),
pt(10),
Orientation::Portrait,
vec![clipped],
)]);
let glyph = 60_000;
assert_eq!(
write_pdf(&list, &fonts),
Err(Error::UnknownGlyph { font, glyph })
);
}
fn without_glyph_locations() -> Vec<u8> {
let mut data = CARLITO.to_vec();
let tables = usize::from(u16::from_be_bytes([data[4], data[5]]));
let record = (0..tables)
.map(|index| 12 + 16 * index)
.find(|&at| &data[at..at + 4] == b"loca")
.unwrap();
data[record..record + 4].copy_from_slice(b"zzzz");
data
}
#[test]
fn reports_a_font_that_krilla_cannot_embed() {
let mut fonts = FontDb::new();
let font = fonts.add_font(without_glyph_locations()).unwrap()[0];
let list = DisplayList::new(vec![Page::new(
pt(10),
pt(10),
Orientation::Portrait,
vec![run(
&fonts,
font,
"a",
pt(10),
Rgb::BLACK,
Placement::at(0, 0),
)],
)]);
let error = write_pdf(&list, &fonts).unwrap_err();
assert!(matches!(error, Error::Write(_)), "{error:?}");
}
#[test]
fn errors_print() {
let font = FontId::from_index(2);
let errors = [
Error::NoPages,
Error::PageSize,
Error::UnknownFont(font),
Error::UnreadableFont(font),
Error::UnknownGlyph { font, glyph: 7 },
Error::TextRange,
Error::Clip,
Error::Write("broken".to_owned()),
];
let messages: Vec<String> = errors.iter().map(ToString::to_string).collect();
assert_eq!(
messages,
[
"the display list has no page",
"a page has a size that is not positive",
"the font database has no font 2",
"font 2 cannot be embedded",
"font 2 has no glyph 7",
"a glyph's text range is not in its run's text",
"a group's clip is not a path that krilla can build",
"the PDF cannot be written: broken",
]
);
}
fn gray(width: u32, height: u32) -> image::GrayImage {
image::GrayImage::from_fn(width, height, |x, _| {
image::Luma([u8::try_from((x * 40).min(255)).unwrap()])
})
}
fn image_page(items: Vec<Item>) -> Page {
page(300, 200, items)
}
#[test]
fn draws_each_image_in_its_rectangle() {
let fonts = FontDb::new();
let png = encoded(gray(4, 3), image::ImageFormat::Png).unwrap();
let jpeg = encoded(gray(5, 2), image::ImageFormat::Jpeg).unwrap();
let list = DisplayList::new(vec![image_page(vec![
image_item(&png, (10, 20, 40, 30), None),
image_item(&jpeg, (100, 50, 50, 20), None),
])]);
let pdf = write_pdf(&list, &fonts).unwrap();
let drawn = &read(&pdf)[0].drawn;
assert_eq!(drawn.len(), 2);
let [first, second] = [&drawn[0], &drawn[1]];
assert_eq!(first.pixels, (4, 3));
assert_eq!(first.jpeg, None);
assert_eq!(second.pixels, (5, 2));
assert_eq!(
second.jpeg.as_deref(),
Some(&jpeg.load_bytes().unwrap()[..])
);
assert_near(first.bounds, [10.0, 20.0, 50.0, 50.0]);
assert_near(second.bounds, [100.0, 50.0, 150.0, 70.0]);
}
fn through_profile(profile: &[u8], stored: [u8; 3]) -> [u8; 3] {
use moxcms::{ColorProfile, Layout, TransformOptions};
let source = ColorProfile::new_from_slice(profile).unwrap();
let transform = source
.create_transform_8bit(
Layout::Rgb,
&ColorProfile::new_srgb(),
Layout::Rgb,
TransformOptions::default(),
)
.unwrap();
let mut drawn = [0; 3];
transform.transform(&stored, &mut drawn).unwrap();
drawn
}
#[test]
fn draws_the_stored_colors_of_a_file_whose_profile_the_picture_decode_does_not_apply() {
let mut profile = moxcms::ColorProfile::new_adobe_rgb().encode().unwrap();
profile[8..12].copy_from_slice(&[2, 0x10, 0, 0]);
let stored = [100, 200, 100];
let converted = through_profile(&profile, stored);
assert!(
converted
.iter()
.zip(stored)
.any(|(a, b)| a.abs_diff(b) > 20),
"{converted:?}"
);
let pixels = image::RgbImage::from_pixel(8, 8, image::Rgb(stored));
for (format, tolerance) in [(image::ImageFormat::Png, 0), (image::ImageFormat::Jpeg, 3)] {
let picture = encoded_with_profile(&pixels, format, profile.clone()).unwrap();
let list = DisplayList::new(vec![image_page(vec![image_item(
&picture,
(10, 20, 40, 30),
None,
)])]);
let pdf = write_pdf(&list, &FontDb::new()).unwrap();
let (rgb, _) = read(&pdf)[0].drawn[0].sample.unwrap();
assert!(
rgb.iter()
.zip(stored)
.all(|(a, b)| a.abs_diff(b) <= tolerance),
"{format:?} {rgb:?}"
);
}
}
#[test]
fn grayscale_uses_have_separate_cached_pixels_and_keep_alpha() {
for (encoding, alpha) in [
(image::ImageFormat::Png, 96),
(image::ImageFormat::Jpeg, 255),
] {
let original = grayscale_source(encoding);
let mut gray = original.clone();
gray.color = paint::ImageColor::Gray709;
for gray_first in [true, false] {
let color_item = image_item(&original, (10, 20, 40, 30), None);
let gray_item = image_item(&gray, (60, 20, 40, 30), None);
let items = if gray_first {
vec![gray_item, color_item]
} else {
vec![color_item, gray_item]
};
let list = DisplayList::new(vec![image_page(vec![Item::Group(Group::new(items))])]);
let pdf = write_pdf(&list, &FontDb::new()).unwrap();
let pages = read(&pdf);
let drawn = &pages[0].drawn;
let (gray, color) = if gray_first {
(&drawn[0], &drawn[1])
} else {
(&drawn[1], &drawn[0])
};
assert_grayscale_use(gray, color, &original, alpha);
}
}
}
fn grayscale_source(encoding: image::ImageFormat) -> paint::Image {
let pixels = image::RgbaImage::from_pixel(4, 3, image::Rgba([19, 67, 139, 96]));
encoded(pixels, encoding).unwrap()
}
fn assert_grayscale_use(gray: &Drawn, color: &Drawn, original: &paint::Image, expected_alpha: u8) {
assert_ne!(gray.object, color.object);
let (rgb, alpha) = gray.sample.unwrap();
assert!(rgb.iter().all(|v| v.abs_diff(61) <= 1), "{rgb:?}");
assert_eq!(alpha, expected_alpha);
let (rgb, original_alpha) = color.sample.unwrap();
assert!(rgb[2] > rgb[0] + 100);
assert_eq!(alpha, original_alpha);
assert_eq!(gray.jpeg, None);
let original_bytes = original.load_bytes().unwrap();
assert_eq!(
color.jpeg.as_deref(),
(original.format == ImageFormat::Jpeg).then_some(&original_bytes[..])
);
}
#[test]
fn shares_image_bytes_but_keeps_each_uses_opacity() {
let fonts = FontDb::new();
let mut png = encoded(gray(4, 3), image::ImageFormat::Png).unwrap();
let opaque = image_item(&png, (10, 20, 40, 30), None);
png.opacity = f_office_paint::Opacity::clamped(10_000);
let pale = image_item(&png, (60, 20, 40, 30), None);
let list = DisplayList::new(vec![image_page(vec![
Item::Group(Group::new(vec![pale])),
opaque,
])]);
let pdf = write_pdf(&list, &fonts).unwrap();
let drawn = &read(&pdf)[0].drawn;
assert_eq!(drawn.len(), 2);
assert!((drawn[0].opacity - 0.1).abs() < 0.00001);
assert_eq!(drawn[1].opacity, 1.0);
assert_eq!(drawn[0].object, drawn[1].object);
assert_near(drawn[0].bounds, [60.0, 20.0, 100.0, 50.0]);
}
#[track_caller]
fn assert_near(shown: [f64; 4], expected: [f64; 4]) {
for (a, b) in shown.iter().zip(expected) {
assert!(same_place(*a, b), "{shown:?} {expected:?}");
}
}
#[test]
fn moves_the_glyphs_of_a_turned_or_scaled_run_back_through_the_turns_inverse() {
let glyph = |x: i64, y: i64| Glyph {
id: 1,
x: Length::from_units(x),
y: Length::from_units(y),
text_start: 0,
text_end: 1,
};
let run = GlyphRun {
font: FontId::from_index(0),
size: pt(12),
color: Rgb::BLACK,
text: "ab".to_owned(),
glyphs: vec![glyph(1_000, 2_000), glyph(1_600, 2_000)],
outline: None,
filled: true,
effect: false,
turn: None,
};
let places = |turn| {
super::upright_run(&run, turn)
.glyphs
.iter()
.map(|g| (g.x.units(), g.y.units()))
.collect::<Vec<_>>()
};
let one = paint::Turn::SCALE;
let half = paint::Turn {
xx: one / 2,
yx: 0,
xy: 0,
yy: one,
};
assert_eq!(places(half), [(1_000, 2_000), (2_200, 2_000)]);
let down = paint::Turn {
xx: 0,
yx: one,
xy: -one,
yy: 0,
};
assert_eq!(places(down), [(1_000, 2_000), (1_000, 1_400)]);
}
#[test]
fn leans_each_glyph_of_a_slanted_run_at_its_own_place() {
let (fonts, font) = carlito().unwrap();
let mut slanted = run(
&fonts,
font,
"Lean",
pt(20),
Rgb::BLACK,
Placement::at(pt(50).units() + 3, pt(100).units() + 7),
);
let Item::Glyphs(glyphs) = &mut slanted else {
panic!("a run of glyphs");
};
glyphs.turn = Some(paint::Turn {
xx: paint::Turn::SCALE,
yx: 0,
xy: -333_333,
yy: paint::Turn::SCALE,
});
let places: Vec<_> = glyphs
.glyphs
.iter()
.map(|g| (g.x.units(), g.y.units()))
.collect();
let list = DisplayList::new(vec![Page::new(
pt(300),
pt(200),
Orientation::Portrait,
vec![slanted],
)]);
let pdf = write_pdf(&list, &fonts).unwrap();
let read = read(&pdf);
let page = &read[0];
assert_eq!(page.leans.len(), 4);
for lean in &page.leans {
assert!((lean - 0.333_333).abs() < 0.000_001, "{lean}");
}
assert_eq!(page.shown.len(), places.len());
for (shown, (x, y)) in page.shown.iter().zip(places) {
assert!(reads_as(shown.x, x) && reads_as(shown.y, y), "{shown:?}");
}
}
#[test]
fn turns_an_image_about_the_centre_of_its_rectangle() {
let fonts = FontDb::new();
let png = encoded(gray(4, 3), image::ImageFormat::Png).unwrap();
let mut item = image_item(&png, (10, 20, 40, 30), None);
let one = paint::Turn::SCALE;
if let Item::Image(image) = &mut item {
image.turn = Some(paint::Turn {
xx: 0,
yx: one,
xy: -one,
yy: 0,
});
}
let list = DisplayList::new(vec![image_page(vec![item])]);
let drawn = &read(&write_pdf(&list, &fonts).unwrap())[0].drawn;
assert_near(drawn[0].bounds, [15.0, 15.0, 45.0, 55.0]);
}
#[test]
fn places_a_turned_image_at_its_own_half_emus() {
let fonts = FontDb::new();
let png = encoded(gray(4, 3), image::ImageFormat::Png).unwrap();
let (x, y, across, down): (i32, i32, i32, i32) = (3_060_737, 4_150_919, 10_768_731, 8_660_133);
let one = paint::Turn::SCALE;
let item = Item::Image(paint::ImageItem {
x: Length::from_units(x.into()),
y: Length::from_units(y.into()),
width: Length::from_units(across.into()),
height: Length::from_units(down.into()),
clip: None,
turn: Some(paint::Turn {
xx: 0,
yx: one,
xy: -one,
yy: 0,
}),
image: png,
});
let list = DisplayList::new(vec![page(600, 800, vec![item])]);
let drawn = &read(&write_pdf(&list, &fonts).unwrap())[0].drawn;
let unit = 1.0 / per_point();
let (centre_x, centre_y) = (
(f64::from(x) + f64::from(across) / 2.0) * unit,
(f64::from(y) + f64::from(down) / 2.0) * unit,
);
let (half_across, half_down) = (f64::from(across) / 2.0 * unit, f64::from(down) / 2.0 * unit);
let expected = [
centre_x - half_down,
centre_y - half_across,
centre_x + half_down,
centre_y + half_across,
];
for (shown, wanted) in drawn[0].bounds.iter().zip(expected) {
assert!(
(shown - wanted).abs() < 0.4 * unit,
"{:?} {expected:?}",
drawn[0].bounds
);
}
}
#[test]
fn gives_the_far_edges_of_a_long_picture_back_at_their_own_half_emus() {
let fonts = FontDb::new();
let png = encoded(gray(4, 3), image::ImageFormat::Png).unwrap();
let one = paint::Turn::SCALE;
for step in 0..60_i32 {
let (x, y) = (127_000 + step * 3_217, 254_000 + step * 1_009);
let (across, down) = (15_240_002 + step * 101_014, 20_320_000 + step * 77_912);
let item = |turn| {
Item::Image(paint::ImageItem {
x: Length::from_units(x.into()),
y: Length::from_units(y.into()),
width: Length::from_units(across.into()),
height: Length::from_units(down.into()),
clip: None,
turn,
image: png.clone(),
})
};
let quarter = paint::Turn {
xx: 0,
yx: one,
xy: -one,
yy: 0,
};
let list = DisplayList::new(vec![page(
1_200,
1_400,
vec![item(None), item(Some(quarter))],
)]);
let drawn = &read(&write_pdf(&list, &fonts).unwrap())[0].drawn;
let (centre_x, centre_y) = (x + across / 2, y + down / 2);
let expected = [
[x, y, x + across, y + down],
[
centre_x - down / 2,
centre_y - across / 2,
centre_x + down / 2,
centre_y + across / 2,
],
];
for (picture, wanted) in drawn.iter().zip(expected) {
for (shown, units) in picture.bounds.iter().zip(wanted) {
assert!(
reads_as(*shown, units.into()),
"step {step}: {:?} {wanted:?}",
picture.bounds
);
}
}
}
}
#[test]
fn gives_the_sides_and_turn_of_a_picture_turned_by_another_angle_back() {
let fonts = FontDb::new();
let png = encoded(gray(4, 3), image::ImageFormat::Png).unwrap();
for [cos, sin] in [[866_026, 499_999], [707_107, 707_107]] {
for step in 0..40_i32 {
let (x, y) = (127_000 + step * 3_217, 254_000 + step * 1_009);
let (across, down) = (1_270_001 + step * 507_013, 2_540_000 + step * 389_561);
let turn = paint::Turn {
xx: cos,
yx: sin,
xy: -sin,
yy: cos,
};
let item = Item::Image(paint::ImageItem {
x: Length::from_units(x.into()),
y: Length::from_units(y.into()),
width: Length::from_units(across.into()),
height: Length::from_units(down.into()),
clip: None,
turn: Some(turn),
image: png.clone(),
});
let list = DisplayList::new(vec![page(1_400, 1_600, vec![item])]);
let drawn = &read(&write_pdf(&list, &fonts).unwrap())[0].drawn;
let [row, column] = drawn[0].sides;
assert!(
reads_as(row, across.into()) && reads_as(column, down.into()),
"step {step}: {:?} {across} {down}",
drawn[0].sides
);
let scale = f64::from(paint::Turn::SCALE);
let entries = drawn[0].turn.map(|entry| (entry * scale).round());
let wanted = [cos, sin, -sin, cos].map(f64::from);
assert_eq!(entries, wanted, "step {step}");
}
}
}
#[test]
fn shows_an_image_inside_its_clip() {
let fonts = FontDb::new();
let png = encoded(gray(4, 3), image::ImageFormat::Png).unwrap();
let mut item = image_item(&png, (10, 20, 40, 30), None);
if let Item::Image(image) = &mut item {
image.clip = Some(Clip {
x: pt(20),
y: pt(25),
width: pt(10),
height: pt(5),
});
}
let list = DisplayList::new(vec![image_page(vec![item])]);
let drawn = &read(&write_pdf(&list, &fonts).unwrap())[0].drawn;
assert_near(drawn[0].clip.unwrap(), [20.0, 25.0, 30.0, 30.0]);
assert_near(drawn[0].bounds, [10.0, 20.0, 50.0, 50.0]);
}
#[test]
fn shows_the_items_of_a_group_inside_its_clip_and_ends_the_clip_after_them() {
let fonts = FontDb::new();
let png = encoded(gray(4, 3), image::ImageFormat::Png).unwrap();
let clip = GroupClip::rect(pt(20), pt(25), pt(10), pt(5));
let group = Item::Group(Group {
items: vec![image_item(&png, (10, 20, 40, 30), None)],
clip: Some(clip),
places: f_office_paint::GroupPlaces::Own,
});
let after = image_item(&png, (10, 20, 40, 30), None);
let list = DisplayList::new(vec![image_page(vec![group, after])]);
let drawn = &read(&write_pdf(&list, &fonts).unwrap())[0].drawn;
assert_near(drawn[0].clip.unwrap(), [20.0, 25.0, 30.0, 30.0]);
assert_near(drawn[1].clip.unwrap(), drawn[1].bounds);
}
#[test]
fn places_an_image_far_below_the_foot_of_the_page_exactly() {
let fonts = FontDb::new();
let png = encoded(gray(4, 3), image::ImageFormat::Png).unwrap();
let page = Page::new(
pt(300),
pt(841) + Length::from_units(23_368),
Orientation::Portrait,
vec![image_item(&png, (10, 20, 40, 1600), None)],
);
let drawn = &read(&write_pdf(&DisplayList::new(vec![page]), &fonts).unwrap())[0].drawn;
let bottom = drawn[0].bounds[3];
assert!((bottom - 1620.0).abs() < 1e-5, "{bottom}");
}
#[test]
fn keeps_a_clip_that_cuts_almost_nothing_from_the_clip_around_it() {
let fonts = FontDb::new();
let png = encoded(gray(4, 3), image::ImageFormat::Png).unwrap();
let narrower = pt(10) - Length::from_units(51);
let inner = Item::Group(Group {
items: vec![image_item(&png, (10, 20, 40, 30), None)],
clip: Some(GroupClip::rect(pt(20), pt(25), narrower, pt(5))),
places: f_office_paint::GroupPlaces::Own,
});
let outer = Item::Group(Group {
items: vec![inner],
clip: Some(GroupClip::rect(pt(20), pt(25), pt(10), pt(5))),
places: f_office_paint::GroupPlaces::Own,
});
let list = DisplayList::new(vec![image_page(vec![outer])]);
let drawn = &read(&write_pdf(&list, &fonts).unwrap())[0].drawn;
let right = drawn[0].clip.unwrap()[2];
assert!(
(right - (30.0 - 51.0 / per_point())).abs() < 1e-4,
"{right}"
);
}
#[test]
fn embeds_an_image_once_for_every_page_that_shows_it() {
let fonts = FontDb::new();
let png = encoded(gray(30, 30), image::ImageFormat::Png).unwrap();
let page = || image_page(vec![image_item(&png, (10, 20, 40, 30), None)]);
let one = write_pdf(&DisplayList::new(vec![page()]), &fonts).unwrap();
let three = write_pdf(&DisplayList::new(vec![page(), page(), page()]), &fonts).unwrap();
let objects = |pdf: &[u8]| {
let mut objects: Vec<ObjectIdentifier> = read(pdf)
.iter()
.flat_map(|page| page.drawn.iter().map(|drawn| drawn.object))
.collect();
let drawn = objects.len();
objects.dedup();
(drawn, objects.len())
};
assert_eq!(objects(&one), (1, 1));
assert_eq!(objects(&three), (3, 1));
}
#[test]
fn gives_wide_image_clip_edges_back_at_their_own_half_emus() {
let fonts = FontDb::new();
let png = encoded(gray(4, 3), image::ImageFormat::Png).unwrap();
for step in 0..40_i32 {
let x_units = 1_828_813 + step * 3_217;
let y_units = 1_828_819 + step * 1_009;
let w_units = 3_302_003 + step * 487_111;
let h_units = 3_302_007 + step * 431_213;
let clip = paint::Clip {
x: Length::from_units(i64::from(x_units)),
y: Length::from_units(i64::from(y_units)),
width: Length::from_units(i64::from(w_units)),
height: Length::from_units(i64::from(h_units)),
};
let item = Item::Image(paint::ImageItem {
x: clip.x - pt(20),
y: clip.y - pt(20),
width: clip.width + pt(40),
height: clip.height + pt(40),
clip: Some(clip),
turn: None,
image: png.clone(),
});
let page = Page::new(pt(1_200), pt(1_200), Orientation::Portrait, vec![item]);
let drawn = &read(&write_pdf(&DisplayList::new(vec![page]), &fonts).unwrap())[0].drawn;
let got = drawn[0].clip.unwrap();
let expected = [x_units, y_units, x_units + w_units, y_units + h_units];
for (actual_pt, want_units) in got.into_iter().zip(expected) {
assert!(
reads_as(actual_pt, i64::from(want_units)),
"step {step}: edge {actual_pt} pt != {want_units} units"
);
}
assert!(
reads_as(got[2] - got[0], i64::from(w_units)),
"step {step}: width {} pt != {w_units} units",
got[2] - got[0]
);
assert!(
reads_as(got[3] - got[1], i64::from(h_units)),
"step {step}: height {} pt != {h_units} units",
got[3] - got[1]
);
}
}
#[test]
fn gives_quarter_turned_odd_picture_sides_back_at_their_own_half_emus() {
let fonts = FontDb::new();
let png = encoded(gray(4, 3), image::ImageFormat::Png).unwrap();
let one = paint::Turn::SCALE;
let quarter = paint::Turn {
xx: 0,
yx: one,
xy: -one,
yy: 0,
};
for step in 0..40_i32 {
let (x, y) = (127_000 + step * 3_217, 254_000 + step * 1_009);
let (across, down) = (15_240_001 + step * 101_013, 20_320_003 + step * 77_911);
let item = Item::Image(paint::ImageItem {
x: Length::from_units(i64::from(x)),
y: Length::from_units(i64::from(y)),
width: Length::from_units(i64::from(across)),
height: Length::from_units(i64::from(down)),
clip: None,
turn: Some(quarter),
image: png.clone(),
});
let page = Page::new(pt(1_200), pt(1_400), Orientation::Portrait, vec![item]);
let drawn = &read(&write_pdf(&DisplayList::new(vec![page]), &fonts).unwrap())[0].drawn;
let [row, column] = drawn[0].sides;
assert!(
reads_as(row, i64::from(across)) && reads_as(column, i64::from(down)),
"step {step}: {:?} != ({across}, {down})",
drawn[0].sides
);
}
}
#[test]
fn leaves_out_images_that_it_cannot_embed() {
let fonts = FontDb::new();
let png = encoded(gray(4, 3), image::ImageFormat::Png).unwrap();
let gif = paint::Image {
format: ImageFormat::Gif,
..png.clone()
};
let emf = paint::Image {
format: ImageFormat::Emf,
..gif.clone()
};
let mut clipped = image_item(&png, (0, 0, 10, 10), None);
if let Item::Image(image) = &mut clipped {
image.clip = Some(Clip {
x: pt(0),
y: pt(0),
width: pt(0),
height: pt(10),
});
}
let list = DisplayList::new(vec![image_page(vec![
image_item(&gif, (0, 0, 10, 10), None),
image_item(&emf, (0, 0, 10, 10), None),
image_item(
&paint::Image::new(b"\xFF\xD8\xFF".to_vec()),
(0, 0, 10, 10),
None,
),
image_item(&png, (0, 0, 0, 10), None),
image_item(&png, (0, 0, 10, -10), None),
clipped,
])]);
let written = write_warned(&list, &fonts).unwrap();
let drawn = &read(&written.value)[0].drawn;
assert_eq!(drawn.len(), 1);
let clip = drawn[0].clip.unwrap();
assert!(clip[2] - clip[0] < 0.001, "{clip:?}");
let warnings: Vec<(Warning, u32)> = written
.warnings
.iter()
.map(|(warning, count)| (warning.clone(), count))
.collect();
let skipped = |format, fault| Warning::ImageSkipped { format, fault };
assert_eq!(
warnings,
[
(skipped(ImageFormat::Gif, ImageFault::Data), 1),
(skipped(ImageFormat::Emf, ImageFault::Format), 1),
(skipped(ImageFormat::Jpeg, ImageFault::Data), 1),
]
);
}
fn assert_left_out(png: Vec<u8>, fault: ImageFault) {
let fonts = FontDb::new();
let large = paint::Image::new(png);
assert_eq!(large.format, ImageFormat::Png);
let small = encoded(gray(4, 3), image::ImageFormat::Png).unwrap();
let list = DisplayList::new(vec![image_page(vec![
image_item(&large, (0, 0, 10, 10), None),
image_item(&small, (10, 20, 40, 30), None),
])]);
let written = write_warned(&list, &fonts).unwrap();
let drawn = &read(&written.value)[0].drawn;
assert_eq!(drawn.len(), 1);
assert_eq!(drawn[0].pixels, (4, 3));
let warnings: Vec<(Warning, u32)> = written
.warnings
.iter()
.map(|(warning, count)| (warning.clone(), count))
.collect();
let format = ImageFormat::Png;
assert_eq!(warnings, [(Warning::ImageSkipped { format, fault }, 1)]);
}
#[test]
fn leaves_out_a_png_file_whose_pixels_do_not_decode() {
let png = encoded(gray(5, 2), image::ImageFormat::Png).unwrap();
let png_bytes = png.load_bytes().unwrap();
let idat = png_bytes
.windows(4)
.position(|name| name == b"IDAT")
.unwrap();
let damaged = png_bytes[..idat + 6].to_vec();
let header =
image::ImageReader::with_format(std::io::Cursor::new(&damaged), image::ImageFormat::Png);
assert_eq!(header.into_dimensions().ok(), Some((5, 2)));
assert_left_out(damaged, ImageFault::Data);
}
#[test]
fn leaves_out_a_png_file_whose_pixels_need_more_than_the_limit() {
let bytes = |rows: u64| 8_192 * rows * 4;
assert!(bytes(8_193) > paint::MAX_DECODED_BYTES);
assert!(bytes(8_192) <= paint::MAX_DECODED_BYTES);
assert_left_out(zero_png(8_192, 8_193, 8).unwrap(), ImageFault::Limit);
}
#[test]
fn leaves_out_a_png_file_of_16_bit_samples_whose_decoder_needs_more_than_the_limit() {
let bytes = |rows: u64| 8_192 * rows * 8;
assert!(bytes(4_097) > paint::MAX_DECODED_BYTES);
assert!(bytes(4_096) <= paint::MAX_DECODED_BYTES);
let small = zero_png(4, 3, 16).unwrap();
let decode = |limit| paint::decode_file(&small, ImageFormat::Png, limit).map(drop);
assert_eq!(decode(4 * 3 * 8 - 1), Err(ImageFault::Limit));
assert_eq!(decode(4 * 3 * 8), Ok(()));
assert_left_out(zero_png(8_192, 4_097, 16).unwrap(), ImageFault::Limit);
}
#[test]
fn draws_gif_bmp_and_tiff_images_as_png_files() {
let fonts = FontDb::new();
let pixels = image::RgbaImage::from_pixel(4, 3, image::Rgba([0, 0, 0, 255]));
let images = [
image::ImageFormat::Gif,
image::ImageFormat::Bmp,
image::ImageFormat::Tiff,
]
.map(|encoding| encoded(pixels.clone(), encoding).unwrap());
let lefts = [10, 100, 190];
let items = images
.iter()
.zip(lefts)
.map(|(image, left)| image_item(image, (left, 20, 40, 30), None))
.collect();
let written = write_warned(&DisplayList::new(vec![image_page(items)]), &fonts).unwrap();
assert!(written.warnings.is_empty());
let drawn = &read(&written.value)[0].drawn;
assert_eq!(drawn.len(), 3);
for (drawn, left) in drawn.iter().zip(lefts) {
let left = f64::from(left);
assert_eq!(drawn.pixels, (4, 3));
assert_eq!(drawn.jpeg, None);
let (color, alpha) = drawn.sample.unwrap();
assert!(color.iter().all(|&value| value < 16), "{color:?}");
assert_eq!(alpha, 255);
assert_near(drawn.bounds, [left, 20.0, left + 40.0, 50.0]);
}
}
#[test]
fn warns_of_each_use_of_an_image_that_it_leaves_out_and_names_its_kind() {
let fonts = FontDb::new();
let broken = paint::Image::new(b"\xFF\xD8\xFF".to_vec());
let page = || image_page(vec![image_item(&broken, (0, 0, 10, 10), None)]);
let list = DisplayList::new(vec![page(), page()]);
let written = write_warned(&list, &fonts).unwrap();
let warning = Warning::ImageSkipped {
format: ImageFormat::Jpeg,
fault: ImageFault::Data,
};
assert_eq!(written.warnings.iter().collect::<Vec<_>>(), [(&warning, 2)]);
assert_eq!(warning.kind(), "pdf-image-skipped");
assert_eq!(
warning.to_string(),
"an image in JPEG format is left out of the PDF: its data does not decode"
);
let metafile = Warning::ImageSkipped {
format: ImageFormat::Emf,
fault: ImageFault::Format,
};
assert_eq!(
metafile.to_string(),
"an image in EMF format is left out of the PDF: the output draws no image of this format"
);
}
#[test]
fn streams_objects_incrementally_to_writer_matching_write_pdf() {
struct CountingWriter {
buf: Vec<u8>,
write_calls: usize,
flushes: usize,
}
impl std::io::Write for CountingWriter {
fn write(&mut self, data: &[u8]) -> std::io::Result<usize> {
self.write_calls += 1;
self.buf.extend_from_slice(data);
Ok(data.len())
}
fn flush(&mut self) -> std::io::Result<()> {
self.flushes += 1;
Ok(())
}
}
let (fonts, font) = carlito().unwrap();
let list = sample(&fonts, font);
let mut sink = CountingWriter {
buf: Vec::new(),
write_calls: 0,
flushes: 0,
};
super::write_pdf_to(&list, &fonts, &mut sink).unwrap();
assert!(
sink.write_calls >= 10,
"expected incremental object writes, got {}",
sink.write_calls
);
assert_eq!(sink.flushes, 1);
assert_eq!(sink.buf, write_pdf(&list, &fonts).unwrap());
}