#![deny(clippy::float_arithmetic)]
use std::num::NonZeroU32;
use std::ops::Range;
use std::sync::Arc;
use f_office_fonts::FontId;
use f_office_units::binary32::Binary32;
use f_office_units::{Length, div_round, div_round_i128};
mod color_effect;
#[cfg(feature = "decode")]
mod decode;
#[cfg(feature = "files")]
pub mod files;
pub mod image_header;
mod image_store;
mod page_sizes;
pub mod paper_forms;
mod sink;
pub mod stroke;
#[cfg(feature = "testing")]
pub mod testing;
pub use color_effect::{ColorEffect, ImageColor};
pub use image_store::{
DEFAULT_IMAGE_BYTES_CACHE, ImageData, ImageId, ImageKey, ImageLoader, ImageRef, LruBytesCache,
next_store_id,
};
#[cfg(feature = "decode")]
pub use decode::{converts_inks, decode, decode_file, without_profile};
pub use page_sizes::{GivenSize, PageSizes};
pub use sink::{PageSink, Painted};
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct DisplayList {
pages: Vec<Page>,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Page {
width: Length,
height: Length,
orientation: Orientation,
items: Vec<Item>,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Orientation {
#[default]
Portrait,
Landscape,
}
impl DisplayList {
#[must_use]
pub const fn new(pages: Vec<Page>) -> Self {
Self { pages }
}
#[must_use]
pub const fn pages(&self) -> &[Page] {
self.pages.as_slice()
}
#[must_use]
pub fn into_pages(self) -> Vec<Page> {
self.pages
}
}
impl Page {
#[must_use]
pub const fn new(
width: Length,
height: Length,
orientation: Orientation,
items: Vec<Item>,
) -> Self {
Self {
width,
height,
orientation,
items,
}
}
#[must_use]
pub const fn orientation(&self) -> Orientation {
self.orientation
}
#[must_use]
pub const fn width(&self) -> Length {
self.width
}
#[must_use]
pub const fn height(&self) -> Length {
self.height
}
#[must_use]
pub const fn items(&self) -> &[Item] {
self.items.as_slice()
}
#[must_use]
pub fn map_items(self, change: impl FnOnce(Vec<Item>) -> Vec<Item>) -> Self {
Self {
items: change(self.items),
..self
}
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Item {
Glyphs(GlyphRun),
Rect(Rect),
Path(PathItem),
Gradient(GradientItem),
Image(ImageItem),
Group(Group),
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Group {
pub items: Vec<Item>,
pub clip: Option<GroupClip>,
pub places: GroupPlaces,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum GroupPlaces {
#[default]
Own,
Page,
Cell,
Points,
Stroked {
width: Length,
},
}
impl Group {
#[must_use]
pub fn new(items: Vec<Item>) -> Self {
Self {
items,
clip: None,
places: GroupPlaces::Own,
}
}
#[must_use]
pub fn of_page(items: Vec<Item>, clip: GroupClip) -> Self {
Self {
items,
clip: Some(clip),
places: GroupPlaces::Page,
}
}
#[must_use]
pub fn of_cell(items: Vec<Item>, clip: GroupClip) -> Self {
Self {
items,
clip: Some(clip),
places: GroupPlaces::Cell,
}
}
fn placed_items(&mut self) -> &mut [Item] {
match self.places {
GroupPlaces::Page
| GroupPlaces::Cell
| GroupPlaces::Points
| GroupPlaces::Stroked { .. } => &mut self.items,
GroupPlaces::Own => &mut [],
}
}
fn points_mut(&mut self) -> impl Iterator<Item = &mut Point> {
let clip = self.clip.iter_mut().flat_map(|clip| &mut clip.commands);
let items = self.items.iter_mut().flat_map(|item| -> Vec<&mut Point> {
match item {
Item::Path(path) => path
.commands
.iter_mut()
.flat_map(PathCommand::points_mut)
.collect(),
Item::Gradient(GradientItem {
commands,
start,
end,
..
}) => commands
.iter_mut()
.flat_map(PathCommand::points_mut)
.chain([start, end])
.collect(),
_ => Vec::new(),
}
});
clip.flat_map(PathCommand::points_mut).chain(items)
}
#[must_use]
pub fn shows_nothing(&self) -> bool {
self.clip.as_ref().is_some_and(|clip| !clip.has_area())
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GroupClip {
pub commands: Vec<PathCommand>,
pub fill_rule: FillRule,
}
impl GroupClip {
#[must_use]
pub fn rect(x: Length, y: Length, width: Length, height: Length) -> Self {
let corner = |x, y| PathCommand::LineTo(Point { x, y });
Self {
commands: vec![
PathCommand::MoveTo(Point { x, y }),
corner(x + width, y),
corner(x + width, y + height),
corner(x, y + height),
PathCommand::Close,
],
fill_rule: FillRule::NonZero,
}
}
#[must_use]
pub fn has_area(&self) -> bool {
let spread = |of: fn(Point) -> Length| {
let mut values = self.commands.iter().flat_map(PathCommand::points).map(of);
let first = values.next();
first.is_some_and(|first| values.any(|value| value != first))
};
spread(|point| point.x) && spread(|point| point.y)
}
}
impl Item {
pub fn map_places(
&mut self,
mut place: impl FnMut(Point) -> Point,
mut length: impl FnMut(Length) -> Length,
) {
self.map_places_with(&mut place, &mut length);
}
#[must_use]
pub fn first_place(&self) -> Option<Point> {
let first_point =
|commands: &[PathCommand]| commands.iter().flat_map(PathCommand::points).next();
match self {
Self::Glyphs(run) => run.glyphs.first().map(|glyph| Point {
x: glyph.x,
y: glyph.y,
}),
Self::Rect(rect) => Some(Point {
x: rect.x,
y: rect.y,
}),
Self::Path(path) => first_point(&path.commands),
Self::Gradient(gradient) => first_point(&gradient.commands),
Self::Image(image) => Some(Point {
x: image.x,
y: image.y,
}),
Self::Group(group) => group.items.iter().find_map(Self::first_place).or_else(|| {
group
.clip
.as_ref()
.and_then(|clip| first_point(&clip.commands))
}),
}
}
fn map_places_with(
&mut self,
place: &mut dyn FnMut(Point) -> Point,
length: &mut dyn FnMut(Length) -> Length,
) {
match self {
Self::Glyphs(run) => {
run.size = length(run.size);
for glyph in &mut run.glyphs {
Point {
x: glyph.x,
y: glyph.y,
} = place(Point {
x: glyph.x,
y: glyph.y,
});
}
if let Some(outline) = &mut run.outline {
outline.width = length(outline.width);
}
}
Self::Rect(rect) => {
Point {
x: rect.x,
y: rect.y,
} = place(Point {
x: rect.x,
y: rect.y,
});
rect.width = length(rect.width);
rect.height = length(rect.height);
}
Self::Path(path) => map_points(&mut path.commands, place),
Self::Gradient(gradient) => {
map_points(&mut gradient.commands, place);
gradient.start = place(gradient.start);
gradient.end = place(gradient.end);
}
Self::Image(image) => {
Point {
x: image.x,
y: image.y,
} = place(Point {
x: image.x,
y: image.y,
});
image.width = length(image.width);
image.height = length(image.height);
if let Some(clip) = &mut image.clip {
clip.map_places_with(place, length);
}
}
Self::Group(group) => {
for item in &mut group.items {
item.map_places_with(place, length);
}
if let Some(clip) = &mut group.clip {
map_points(&mut clip.commands, place);
}
}
}
}
}
fn map_points(commands: &mut [PathCommand], place: &mut dyn FnMut(Point) -> Point) {
for point in commands.iter_mut().flat_map(PathCommand::points_mut) {
*point = place(*point);
}
}
impl Clip {
fn map_places_with(
&mut self,
place: &mut dyn FnMut(Point) -> Point,
length: &mut dyn FnMut(Length) -> Length,
) {
Point {
x: self.x,
y: self.y,
} = place(Point {
x: self.x,
y: self.y,
});
self.width = length(self.width);
self.height = length(self.height);
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct GlyphRun {
pub font: FontId,
pub size: Length,
pub color: Rgb,
pub text: String,
pub glyphs: Vec<Glyph>,
pub outline: Option<Outline>,
pub filled: bool,
pub effect: bool,
pub turn: Option<Turn>,
}
impl GlyphRun {
#[must_use]
pub fn glyph_range(&self, glyph: &Glyph) -> Option<Range<usize>> {
let start = usize::try_from(glyph.text_start).ok()?;
let end = usize::try_from(glyph.text_end).ok()?;
self.text.get(start..end).map(|_| start..end)
}
#[must_use]
pub fn glyph_text(&self, glyph: &Glyph) -> Option<&str> {
self.text.get(self.glyph_range(glyph)?)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Outline {
pub width: Length,
pub color: Rgb,
pub join: Join,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Join {
Round,
Miter,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Glyph {
pub id: u32,
pub x: Length,
pub y: Length,
pub text_start: u32,
pub text_end: u32,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Rect {
pub x: Length,
pub y: Length,
pub width: Length,
pub height: Length,
pub color: Rgb,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PathItem {
pub commands: Vec<PathCommand>,
pub color: Rgb,
pub fill_rule: FillRule,
}
#[derive(Clone, Debug, PartialEq, Eq)]
#[non_exhaustive]
pub struct GradientItem {
pub commands: Vec<PathCommand>,
pub fill_rule: FillRule,
pub start: Point,
pub end: Point,
pub stops: Vec<GradientStop>,
}
impl GradientItem {
#[must_use]
pub fn new(
commands: Vec<PathCommand>,
fill_rule: FillRule,
axis: (Point, Point),
stops: Vec<GradientStop>,
) -> Self {
Self {
commands,
fill_rule,
start: axis.0,
end: axis.1,
stops,
}
}
#[must_use]
pub fn color_at(&self, place: i64) -> Rgb {
let (Some(first), Some(last)) = (self.stops.first(), self.stops.last()) else {
return Rgb::BLACK;
};
if place < i64::from(first.place) {
return first.color;
}
let after = self
.stops
.partition_point(|stop| i64::from(stop.place) <= place);
let (Some(before), Some(next)) = (
after.checked_sub(1).and_then(|at| self.stops.get(at)),
self.stops.get(after),
) else {
return last.color;
};
let span = i64::from(next.place) - i64::from(before.place);
let along = place - i64::from(before.place);
let mix = |from: u8, to: u8| {
let from = i64::from(from);
let value = from + div_round(along * (i64::from(to) - from), span);
u8::try_from(value.clamp(0, 255)).unwrap_or(u8::MAX)
};
Rgb {
r: mix(before.color.r, next.color.r),
g: mix(before.color.g, next.color.g),
b: mix(before.color.b, next.color.b),
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct GradientStop {
pub place: u32,
pub color: Rgb,
}
impl GradientStop {
pub const START: u32 = 0;
pub const END: u32 = 1_000_000;
#[must_use]
pub const fn new(place: u32, color: Rgb) -> Self {
Self { place, color }
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PathCommand {
MoveTo(Point),
LineTo(Point),
QuadTo(Point, Point),
CubicTo(Point, Point, Point),
Close,
}
impl PathCommand {
pub fn points_mut(&mut self) -> impl Iterator<Item = &mut Point> {
let points = match self {
Self::MoveTo(a) | Self::LineTo(a) => [Some(a), None, None],
Self::QuadTo(a, b) => [Some(a), Some(b), None],
Self::CubicTo(a, b, c) => [Some(a), Some(b), Some(c)],
Self::Close => [None, None, None],
};
points.into_iter().flatten()
}
pub fn points(&self) -> impl Iterator<Item = Point> {
let points = match *self {
Self::MoveTo(a) | Self::LineTo(a) => [Some(a), None, None],
Self::QuadTo(a, b) => [Some(a), Some(b), None],
Self::CubicTo(a, b, c) => [Some(a), Some(b), Some(c)],
Self::Close => [None, None, None],
};
points.into_iter().flatten()
}
}
pub const THINNEST_FILL: Length = Length::from_units(100);
#[must_use]
pub const fn fill_shows(across: Length, down: Length) -> bool {
across.units().abs() > THINNEST_FILL.units() && down.units().abs() > THINNEST_FILL.units()
}
#[must_use]
pub fn path_shows(commands: &[PathCommand]) -> bool {
let drawn = fill_commands(commands);
let mut points = drawn.iter().flat_map(PathCommand::points);
let Some(first) = points.next() else {
return false;
};
let (low, high) = points.fold((first, first), |(low, high), p| {
(
Point {
x: low.x.min(p.x),
y: low.y.min(p.y),
},
Point {
x: high.x.max(p.x),
y: high.y.max(p.y),
},
)
});
fill_shows(high.x - low.x, high.y - low.y)
}
#[must_use]
pub fn fill_commands(commands: &[PathCommand]) -> Vec<PathCommand> {
let mut current: Option<Point> = None;
let mut start: Option<Point> = None;
commands
.iter()
.filter_map(|&command| match command {
PathCommand::MoveTo(p) => {
(current, start) = (Some(p), Some(p));
Some(command)
}
PathCommand::LineTo(p) => {
let empty = current == Some(p);
current = Some(p);
(!empty).then_some(command)
}
PathCommand::CubicTo(_, _, p) => {
current = Some(p);
Some(command)
}
PathCommand::QuadTo(control, end) => {
let from = current.unwrap_or(control);
current = Some(end);
let [_, first, second, _] = stroke::quad_as_cubic(from, control, end);
Some(PathCommand::CubicTo(first, second, end))
}
PathCommand::Close => {
current = start;
Some(command)
}
})
.collect()
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct Point {
pub x: Length,
pub y: Length,
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum FillRule {
#[default]
NonZero,
EvenOdd,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct ImageItem {
pub x: Length,
pub y: Length,
pub width: Length,
pub height: Length,
pub clip: Option<Clip>,
pub turn: Option<Turn>,
pub image: Image,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Turn {
pub xx: i32,
pub yx: i32,
pub xy: i32,
pub yy: i32,
}
impl Turn {
pub const SCALE: i32 = 1_000_000;
}
impl ImageItem {
#[must_use]
pub fn shown(&self) -> Option<Clip> {
let clip = self.clip?;
let end = |start: Length, length: Length| start.units().checked_add(length.units());
let left = clip.x.max(self.x).units();
let top = clip.y.max(self.y).units();
let right = end(clip.x, clip.width)?.min(end(self.x, self.width)?);
let bottom = end(clip.y, clip.height)?.min(end(self.y, self.height)?);
(left < right && top < bottom).then(|| Clip {
x: Length::from_units(left),
y: Length::from_units(top),
width: Length::from_units(right - left),
height: Length::from_units(bottom - top),
})
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub struct Clip {
pub x: Length,
pub y: Length,
pub width: Length,
pub height: Length,
}
#[derive(Clone, Debug, PartialEq, Eq, Hash)]
pub struct Image {
pub format: ImageFormat,
pub data: ImageData,
pub opacity: Opacity,
pub color: ImageColor,
pub inks: InkConversion,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Opacity(i64);
impl Opacity {
pub const FULL: Self = Self(f_office_units::scale::DRAWING_WHOLE);
#[must_use]
pub const fn clamped(share: i64) -> Self {
let whole = f_office_units::scale::DRAWING_WHOLE;
Self(if share < 0 {
0
} else if share > whole {
whole
} else {
share
})
}
#[must_use]
pub const fn times(self, other: Self) -> Self {
Self(div_round(
self.0 * other.0,
f_office_units::scale::DRAWING_WHOLE,
))
}
#[must_use]
pub const fn share(self) -> i64 {
self.0
}
}
impl Image {
#[must_use]
pub fn new(data: impl Into<Arc<[u8]>>) -> Self {
let data = data.into();
Self {
format: ImageFormat::detect(&data),
data: ImageData::Inline(data),
opacity: Opacity::FULL,
color: ImageColor::Original,
inks: InkConversion::EmbeddedProfile,
}
}
#[must_use]
pub const fn from_ref(format: ImageFormat, image_ref: ImageRef) -> Self {
Self {
format,
data: ImageData::Lazy(image_ref),
opacity: Opacity::FULL,
color: ImageColor::Original,
inks: InkConversion::EmbeddedProfile,
}
}
#[must_use]
pub fn load_bytes(&self) -> Option<Arc<[u8]>> {
self.data.bytes()
}
#[must_use]
pub fn load_bytes_with_format(&self) -> Option<(Arc<[u8]>, ImageFormat)> {
self.data.bytes_with_format(self.format)
}
#[must_use]
pub fn load_prefix(&self, max_bytes: usize) -> Option<Arc<[u8]>> {
self.data.prefix(max_bytes)
}
#[must_use]
pub fn cache_key(&self) -> ImageKey {
self.data.key()
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub enum InkConversion {
#[default]
EmbeddedProfile,
InkTable,
}
pub const MAX_DECODED_BYTES: u64 = 256 << 20;
pub const MAX_DECODED_BYTES_TO_WRITE_AGAIN: u64 = 512 << 20;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum ImageFormat {
Png,
Jpeg,
Gif,
Bmp,
Tiff,
Emf,
Wmf,
EffectPicture,
Unknown,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum ImageFault {
Format,
Data,
Limit,
}
impl std::fmt::Display for ImageFault {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::Format => "the output draws no image of this format",
Self::Data => "its data does not decode",
Self::Limit => "it is larger than the output's limits",
})
}
}
impl std::fmt::Display for ImageFormat {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Self::Png => "PNG",
Self::Jpeg => "JPEG",
Self::Gif => "GIF",
Self::Bmp => "BMP",
Self::Tiff => "TIFF",
Self::Emf => "EMF",
Self::Wmf => "WMF",
Self::EffectPicture => "effect picture",
Self::Unknown => "unknown",
})
}
}
impl ImageFormat {
#[must_use]
pub fn detect(data: &[u8]) -> Self {
const EMR_HEADER: [u8; 4] = [1, 0, 0, 0];
const EMF_SIGNATURE: &[u8] = b" EMF";
let starts = |signature: &[u8]| data.starts_with(signature);
if starts(b"\x89PNG\r\n\x1a\n") {
Self::Png
} else if starts(&[0xFF, 0xD8, 0xFF]) {
Self::Jpeg
} else if starts(b"GIF87a") || starts(b"GIF89a") {
Self::Gif
} else if starts(b"BM") {
Self::Bmp
} else if starts(b"II*\0") || starts(b"MM\0*") {
Self::Tiff
} else if starts(&EMR_HEADER) && data.get(40..44) == Some(EMF_SIGNATURE) {
Self::Emf
} else if is_wmf(data) {
Self::Wmf
} else {
Self::Unknown
}
}
}
fn is_wmf(data: &[u8]) -> bool {
data.starts_with(&[0xD7, 0xCD, 0xC6, 0x9A])
|| data.starts_with(&[1, 0, 9, 0])
|| data.starts_with(&[2, 0, 9, 0])
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
pub struct Rgb {
pub r: u8,
pub g: u8,
pub b: u8,
}
impl Rgb {
pub const BLACK: Self = Self { r: 0, g: 0, b: 0 };
pub const WHITE: Self = Self {
r: u8::MAX,
g: u8::MAX,
b: u8::MAX,
};
#[must_use]
pub fn from_hex(text: &str) -> Option<Self> {
let digits = text.as_bytes();
if digits.len() != 6 || !digits.iter().all(u8::is_ascii_hexdigit) {
return None;
}
let value = u32::from_str_radix(text, 16).ok()?;
let [_, r, g, b] = value.to_be_bytes();
Some(Self { r, g, b })
}
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum Offset {
#[default]
None,
Share {
share: i64,
bias: i64,
step: i64,
},
Page {
steps: Fraction,
parts: i64,
per_inch: i64,
product: OffsetProduct,
},
}
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub enum OffsetProduct {
#[default]
Exact,
Binary32 {
dots_per_inch: i64,
},
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum WriterOffset {
EveryPage(Offset),
Sizes(&'static PageSizes),
}
impl WriterOffset {
pub const NONE: Self = Self::EveryPage(Offset::None);
#[must_use]
pub fn on_page(self, width: i64, height: i64, orientation: Orientation) -> (Offset, Offset) {
match self {
Self::Sizes(sizes) => sizes.offsets(width, height, orientation),
Self::EveryPage(offset) => (offset, offset),
}
}
}
pub const STEP_PARTS: i64 = 100_000;
impl Offset {
#[must_use]
pub fn of(self, x: i64, side: i64) -> i64 {
self.of_in(x, side, 1)
}
#[must_use]
pub(crate) fn written_place(self, x: i64, side: i64) -> i64 {
if let Self::Page {
steps,
parts,
per_inch,
product: OffsetProduct::Binary32 { dots_per_inch },
} = self
&& let Some(place) =
binary32_written_place(x, side, (steps, parts, per_inch), dots_per_inch)
{
return place;
}
x + self.of(x, side)
}
#[must_use]
pub fn of_in(self, x: i64, side: i64, fraction: i64) -> i64 {
let fraction = i128::from(fraction.max(1));
match self {
Self::None => 0,
Self::Share { share, bias, step } => {
if share <= 0 || step <= 0 {
return 0;
}
let steps = div_round_i128(
i128::from(x) + i128::from(bias) * i128::from(share),
i128::from(step) * i128::from(share),
);
i64::try_from(steps * i128::from(step) * fraction).unwrap_or(0)
}
Self::Page {
steps,
parts,
per_inch,
product,
} => {
if side <= 0 || parts <= 0 || per_inch <= 0 || steps.1 <= 0 {
return 0;
}
if let OffsetProduct::Binary32 { dots_per_inch } = product {
return binary32_page_offset(
x,
side,
(steps, parts, per_inch),
(dots_per_inch, fraction),
)
.unwrap_or(0);
}
let parts = i128::from(parts);
let product = div_round_i128(
i128::from(x) * i128::from(steps.0) * parts,
i128::from(steps.1) * i128::from(side),
);
let n = div_round_i128(product, parts);
let inch = i128::from(Length::UNITS_PER_INCH);
i64::try_from(div_round_i128(n * inch * fraction, i128::from(per_inch)))
.unwrap_or(0)
}
}
}
}
fn binary32_page_offset(
x: i64,
side: i64,
(steps, parts, per_inch): (Fraction, i64, i64),
(dots_per_inch, fraction): (i64, i128),
) -> Option<i64> {
if dots_per_inch <= 0 {
return None;
}
let inch = i128::from(Length::UNITS_PER_INCH);
let dpi = i128::from(dots_per_inch);
let dots = i64::try_from(div_round_i128(i128::from(side) * dpi, inch)).ok()?;
let place = i64::try_from(div_round_i128(i128::from(x) * dpi, inch)).ok()?;
let entry = page_entry(dots, (steps, parts, per_inch), dpi)?;
let written_parts = i128::from(entry.times(place).whole(false));
let written = div_round_i128(written_parts, parts.into());
let difference = written
.checked_mul(dpi)?
.checked_sub(i128::from(place).checked_mul(per_inch.into())?)?;
i64::try_from(div_round_i128(
difference.checked_mul(inch)?.checked_mul(fraction)?,
i128::from(per_inch).checked_mul(dpi)?,
))
.ok()
}
fn binary32_written_place(
x: i64,
side: i64,
(steps, parts, per_inch): (Fraction, i64, i64),
dots_per_inch: i64,
) -> Option<i64> {
if dots_per_inch <= 0 || parts <= 0 || per_inch <= 0 {
return None;
}
let inch = i128::from(Length::UNITS_PER_INCH);
let dpi = i128::from(dots_per_inch);
let dots = i64::try_from(div_round_i128(i128::from(side) * dpi, inch)).ok()?;
let entry = page_entry(dots, (steps, parts, per_inch), dpi)?;
let (mantissa, exponent) = (i128::from(entry.mantissa()), entry.exponent());
let mut numerator = mantissa.checked_mul(i128::from(x))?.checked_mul(dpi)?;
let mut denominator = inch;
let shift = exponent.unsigned_abs();
if exponent >= 0 {
numerator = numerator.checked_mul(1_i128.checked_shl(shift)?)?;
} else {
denominator = denominator.checked_mul(1_i128.checked_shl(shift)?)?;
}
let product = Binary32::nearest(numerator, denominator);
let written_parts = i128::from(product.whole(false));
let written = div_round_i128(written_parts, parts.into());
i64::try_from(div_round_i128(
written.checked_mul(inch)?,
i128::from(per_inch),
))
.ok()
}
fn page_entry(
dots: i64,
(steps, parts, per_inch): (Fraction, i64, i64),
dpi: i128,
) -> Option<Binary32> {
if dots <= 0 {
return None;
}
let (gain, over) = (i128::from(steps.0), i128::from(steps.1));
let numerator = i128::from(per_inch)
.checked_mul(dots.into())?
.checked_mul(over)?
.checked_add(gain.checked_mul(dpi)?)?
.checked_mul(parts.into())?;
let denominator = dpi.checked_mul(dots.into())?.checked_mul(over)?;
Some(Binary32::nearest(numerator, denominator))
}
fn offset_rect(rect: &mut Rect, across: Offset, width: Length) {
let right = rect.x.units() + rect.width.units();
let left = rect.x.units() + across.of(rect.x.units(), width.units());
let right = right + across.of(right, width.units());
rect.x = Length::from_units(left);
rect.width = Length::from_units(right - left);
}
pub type Fraction = (i64, i64);
pub const STRETCH_HEIGHTS: usize = 16;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Writer {
page_step: i64,
vertical_stretch: i64,
glyph_stretch_step: Option<Length>,
stretch_offset: Fraction,
stretch_factors: [(i64, Fraction); STRETCH_HEIGHTS],
stretch_heights: usize,
digits: Option<NonZeroU32>,
least_decimals: u32,
rectangle_steps: Option<NonZeroU32>,
baseline_steps: Option<NonZeroU32>,
picture_digits: Option<NonZeroU32>,
horizontal_offset: WriterOffset,
vertical_offset: WriterOffset,
jpeg_quality: Option<JpegQuality>,
jpeg_share: Option<JpegShare>,
jpeg_sample: Option<JpegSample>,
picture_density: Option<PictureDensity>,
palette_density: Option<PaletteDensity>,
picture_crop: PictureCrop,
alpha_mix: AlphaMix,
linear_limit: LinearLimit,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum AlphaMix {
Plain,
Weighted,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PictureCrop {
WholeFileUnderClip,
VisiblePart,
VisiblePartAtScale,
}
impl PictureCrop {
#[must_use]
pub const fn keeps_visible_part(self) -> bool {
!matches!(self, Self::WholeFileUnderClip)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct JpegQuality(u8);
impl JpegQuality {
#[must_use]
pub const fn new(quality: u8) -> Option<Self> {
if quality >= 1 && quality <= 100 {
Some(Self(quality))
} else {
None
}
}
#[must_use]
pub const fn get(self) -> u8 {
self.0
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct JpegShare(u16);
impl JpegShare {
#[must_use]
pub const fn new(thousandths: u16) -> Option<Self> {
if thousandths >= 1 && thousandths <= 1000 {
Some(Self(thousandths))
} else {
None
}
}
#[must_use]
pub const fn thousandths(self) -> u16 {
self.0
}
#[must_use]
pub fn takes(self, jpeg: usize, flate: usize) -> bool {
let (Ok(jpeg), Ok(flate)) = (u128::try_from(jpeg), u128::try_from(flate)) else {
return false;
};
jpeg * 1000 < u128::from(self.0) * flate
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct JpegSample {
share: u16,
floor: u32,
whole: u16,
}
impl JpegSample {
pub const STRIPS: usize = 16;
pub const ROWS: usize = 8;
#[must_use]
pub const fn new(share: u16, floor: u32, whole: u16) -> Option<Self> {
if share >= 1 && share <= 1000 && whole >= 1 && whole <= 1000 && floor >= 1 {
Some(Self {
share,
floor,
whole,
})
} else {
None
}
}
pub fn strips(height: usize) -> impl Iterator<Item = std::ops::Range<usize>> {
(0..Self::STRIPS).map(move |k| {
let start = k.saturating_mul(height) / Self::STRIPS;
start..start.saturating_add(Self::ROWS).min(height)
})
}
#[must_use]
pub fn takes(self, sample: usize, height: usize, (flate, raw): (usize, usize)) -> bool {
let (Ok(sample), Ok(height), Ok(flate), Ok(raw), Ok(rows)) = (
u128::try_from(sample),
u128::try_from(height),
u128::try_from(flate),
u128::try_from(raw),
u128::try_from(Self::STRIPS * Self::ROWS),
) else {
return false;
};
let estimate = sample * height;
flate * 1000 >= u128::from(self.whole) * raw
|| (estimate * 1000 >= u128::from(self.share) * flate * rows
&& estimate >= u128::from(self.floor) * rows)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PictureDensity {
pub limit_ppi: NonZeroU32,
pub ppi: NonZeroU32,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum PaletteClass {
OneBit,
FourBitColor,
EightBitColor,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct PaletteDensity {
pub one_bit_limit_ppi: NonZeroU32,
pub one_bit_ppi: NonZeroU32,
pub four_bits_limit_ppi: NonZeroU32,
pub eight_bits_limit_ppi: NonZeroU32,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum Resampler {
Filter(LinearLimit),
CentrePixel,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum LinearLimit {
Pixels(NonZeroU32),
Side(NonZeroU32),
}
impl LinearLimit {
#[must_use]
pub fn takes_linear(self, (width, height): (usize, usize)) -> bool {
let most = |count: NonZeroU32| usize::try_from(count.get()).unwrap_or(usize::MAX);
match self {
Self::Pixels(count) => width.saturating_mul(height) <= most(count),
Self::Side(count) => width.max(height) <= most(count),
}
}
}
const DEFAULT_LINEAR_LIMIT: LinearLimit = match NonZeroU32::new(1 << 17) {
Some(count) => LinearLimit::Pixels(count),
None => LinearLimit::Pixels(NonZeroU32::MIN),
};
impl Writer {
#[must_use]
pub const fn new(page_step: Length) -> Option<Self> {
if page_step.units() > 0 {
Some(Self {
page_step: page_step.units(),
vertical_stretch: 0,
glyph_stretch_step: None,
stretch_offset: (0, 1),
stretch_factors: [(0, (1, 1)); STRETCH_HEIGHTS],
stretch_heights: 0,
digits: None,
least_decimals: 0,
rectangle_steps: None,
baseline_steps: None,
picture_digits: None,
horizontal_offset: WriterOffset::NONE,
vertical_offset: WriterOffset::NONE,
jpeg_quality: None,
jpeg_share: None,
jpeg_sample: None,
picture_density: None,
palette_density: None,
picture_crop: PictureCrop::WholeFileUnderClip,
alpha_mix: AlphaMix::Plain,
linear_limit: DEFAULT_LINEAR_LIMIT,
})
} else {
None
}
}
#[must_use]
pub const fn with_jpeg_quality(self, quality: Option<JpegQuality>) -> Self {
Self {
jpeg_quality: quality,
..self
}
}
#[must_use]
pub const fn jpeg_quality(&self) -> Option<JpegQuality> {
self.jpeg_quality
}
#[must_use]
pub const fn with_jpeg_share(self, share: Option<JpegShare>) -> Self {
Self {
jpeg_share: share,
..self
}
}
#[must_use]
pub const fn jpeg_share(&self) -> Option<JpegShare> {
self.jpeg_share
}
#[must_use]
pub const fn with_jpeg_sample(self, sample: Option<JpegSample>) -> Self {
Self {
jpeg_sample: sample,
..self
}
}
#[must_use]
pub const fn jpeg_sample(&self) -> Option<JpegSample> {
self.jpeg_sample
}
#[must_use]
pub const fn with_picture_density(self, density: Option<PictureDensity>) -> Self {
Self {
picture_density: density,
..self
}
}
#[must_use]
pub const fn with_palette_density(self, density: Option<PaletteDensity>) -> Self {
Self {
palette_density: density,
..self
}
}
#[must_use]
pub const fn with_picture_crop(self, crop: PictureCrop) -> Self {
Self {
picture_crop: crop,
..self
}
}
#[must_use]
pub const fn picture_crop(&self) -> PictureCrop {
self.picture_crop
}
#[must_use]
pub const fn with_alpha_mix(self, mix: AlphaMix) -> Self {
Self {
alpha_mix: mix,
..self
}
}
#[must_use]
pub const fn alpha_mix(&self) -> AlphaMix {
self.alpha_mix
}
#[must_use]
pub const fn with_linear_limit(self, limit: LinearLimit) -> Self {
Self {
linear_limit: limit,
..self
}
}
#[must_use]
pub const fn digits(&self) -> Option<NonZeroU32> {
self.digits
}
#[must_use]
pub const fn least_decimals(&self) -> u32 {
self.least_decimals
}
#[must_use]
pub const fn rectangle_steps(&self) -> Option<NonZeroU32> {
self.rectangle_steps
}
#[must_use]
pub const fn baseline_steps(&self) -> Option<NonZeroU32> {
self.baseline_steps
}
#[must_use]
pub fn resampled_size(
&self,
pixels: (usize, usize),
size: (Length, Length),
palette: Option<PaletteClass>,
) -> Option<((usize, usize), Resampler)> {
let density = self.picture_density?;
let filter = Resampler::Filter(self.linear_limit);
let (limit_ppi, ppi, resampler) = match (self.palette_density, palette) {
(Some(palettes), Some(PaletteClass::OneBit)) => (
palettes.one_bit_limit_ppi,
palettes.one_bit_ppi,
Resampler::CentrePixel,
),
(Some(palettes), Some(PaletteClass::FourBitColor)) => {
(palettes.four_bits_limit_ppi, density.ppi, filter)
}
(Some(palettes), Some(PaletteClass::EightBitColor)) => {
(palettes.eight_bits_limit_ppi, density.ppi, filter)
}
_ => (density.limit_ppi, density.ppi, filter),
};
let inch = i128::from(Length::UNITS_PER_INCH);
let written = |count: usize, length: Length| {
let units = i128::from(length.units());
let pixels = i128::try_from(count).unwrap_or(i128::MAX);
if pixels * inch < i128::from(limit_ppi.get()) * units {
return count;
}
let most = (i128::from(ppi.get()) * units - 1) / inch;
usize::try_from(most).map_or(count, |most| most.min(count))
};
let (width, height) = size;
if width.units() <= 0 || height.units() <= 0 {
return None;
}
let new = (written(pixels.0, width), written(pixels.1, height));
(new != pixels && new.0 > 0 && new.1 > 0).then_some((new, resampler))
}
#[must_use]
pub const fn with_vertical_stretch(self, steps: i64) -> Self {
Self {
vertical_stretch: steps,
..self
}
}
#[must_use]
pub const fn with_glyph_stretch_step(self, step: Option<Length>) -> Option<Self> {
match step {
Some(step) if step.units() <= 0 => None,
Some(step) => Some(Self {
glyph_stretch_step: Some(step),
..self
}),
None => Some(Self {
glyph_stretch_step: None,
..self
}),
}
}
#[must_use]
pub fn with_stretch_factors(
self,
offset: Fraction,
factors: &[(Length, Fraction)],
) -> Option<Self> {
if factors.len() > STRETCH_HEIGHTS
|| offset.1 <= 0
|| factors.iter().any(|(_, factor)| factor.1 <= 0)
{
return None;
}
let mut table = [(0, (1, 1)); STRETCH_HEIGHTS];
for (slot, (height, factor)) in table.iter_mut().zip(factors) {
*slot = (height.units(), *factor);
}
Some(Self {
stretch_offset: offset,
stretch_factors: table,
stretch_heights: factors.len(),
..self
})
}
fn stretch_factor(&self, height: Length) -> (Fraction, Fraction) {
self.stretch_factors
.iter()
.take(self.stretch_heights)
.find(|(written, _)| *written == height.units())
.map_or(((1, 1), (0, 1)), |(_, factor)| {
(*factor, self.stretch_offset)
})
}
#[must_use]
pub const fn with_digits(self, digits: Option<NonZeroU32>) -> Self {
Self { digits, ..self }
}
#[must_use]
pub const fn with_least_decimals(self, decimals: u32) -> Self {
Self {
least_decimals: decimals,
..self
}
}
#[must_use]
pub const fn with_rectangle_steps(self, per_inch: Option<NonZeroU32>) -> Self {
Self {
rectangle_steps: per_inch,
..self
}
}
#[must_use]
pub const fn with_baseline_steps(self, per_inch: Option<NonZeroU32>) -> Self {
Self {
baseline_steps: per_inch,
..self
}
}
#[must_use]
pub const fn with_picture_digits(self, digits: Option<NonZeroU32>) -> Self {
Self {
picture_digits: digits,
..self
}
}
pub fn place_pictures(&self, list: &mut DisplayList) {
let Some(digits) = self.picture_digits else {
return;
};
for page in &mut list.pages {
for item in &mut page.items {
if let Item::Image(image) = item
&& image.turn.is_none()
{
(image.x, image.y, image.width, image.height) = written_box(
page.height,
(image.x, image.y, image.width, image.height),
(digits.get(), 0),
);
}
}
}
}
#[must_use]
pub const fn with_horizontal_offset(self, offset: WriterOffset) -> Self {
Self {
horizontal_offset: offset,
..self
}
}
#[must_use]
pub const fn with_vertical_offset(self, offset: WriterOffset) -> Self {
Self {
vertical_offset: offset,
..self
}
}
fn page_offsets(
&self,
width: Length,
height: Length,
orientation: Orientation,
) -> (Offset, Offset) {
let (width, height) = (width.units(), height.units());
(
self.horizontal_offset.on_page(width, height, orientation).0,
self.vertical_offset.on_page(width, height, orientation).1,
)
}
#[cfg(feature = "development")]
#[must_use]
pub fn development_page_offsets(
&self,
width: Length,
height: Length,
orientation: Orientation,
) -> (Offset, Offset) {
self.page_offsets(width, height, orientation)
}
#[must_use]
pub const fn page_side(&self, length: Length) -> Length {
let step = self.page_step;
Length::from_units(div_round(length.units(), step) * step)
}
pub fn finish(&self, list: &mut DisplayList) {
for page in &mut list.pages {
page.width = self.page_side(page.width);
page.height = self.page_side(page.height);
let extra = self.vertical_stretch * self.page_step;
if extra != 0 && page.height.units() > 0 {
let (factor, offset) = self.stretch_factor(page.height);
let stretch = Stretch {
taller: page.height.units() + extra,
height: page.height.units(),
glyph_step: self.glyph_stretch_step,
factor,
offset,
};
for item in &mut page.items {
stretch.item(item);
}
}
self.offset_items(page);
if let Some(digits) = self.digits {
let digits = (digits.get(), self.least_decimals);
for item in &mut page.items {
self.write_digits(page.height, digits, item);
}
}
stroke_items(&mut page.items);
}
}
fn offset_items(&self, page: &mut Page) {
let (width, height) = (page.width, page.height);
let (across, down_offset) = self.page_offsets(width, height, page.orientation);
let down =
|y: Length| Length::from_units(y.units() + down_offset.of(y.units(), height.units()));
let place = |point: &mut Point| {
let x = point.x.units();
point.x = Length::from_units(x + across.of(x, width.units()));
point.y = down(point.y);
};
offset_all(&mut page.items, &|item| match item {
Item::Rect(rect) => {
offset_rect(rect, across, width);
let bottom = Length::from_units(rect.y.units() + rect.height.units());
let top = down(rect.y);
let bottom = down(bottom);
rect.y = top;
rect.height = Length::from_units(bottom.units() - top.units());
}
Item::Glyphs(run) => {
for glyph in &mut run.glyphs {
glyph.y = down(glyph.y);
}
}
Item::Group(group) if group.places == GroupPlaces::Cell => {
let clip = group.clip.iter_mut().flat_map(|clip| &mut clip.commands);
clip.flat_map(PathCommand::points_mut).for_each(place);
}
Item::Group(group) if group.places == GroupPlaces::Points => {
group.points_mut().for_each(place);
}
Item::Group(group) if matches!(group.places, GroupPlaces::Stroked { .. }) => {
place_edges(&mut group.items, (across, down_offset), (width, height));
}
Item::Path(_) | Item::Gradient(_) | Item::Image(_) | Item::Group(_) => {}
});
}
fn write_digits(&self, height: Length, digits: (u32, u32), item: &mut Item) {
match item {
Item::Glyphs(run) => {
for glyph in &mut run.glyphs {
glyph.y = match self.baseline_steps {
Some(per_inch) => {
counted_y(height, glyph.y, digits, i64::from(per_inch.get()))
}
None => written_y(height, glyph.y, digits),
};
}
}
Item::Rect(rect) => {
let exact = (rect.x, rect.y, rect.width, rect.height);
(rect.x, rect.y, rect.width, rect.height) = self
.rectangle_steps
.and_then(|steps| held_box(height, exact, (digits, i64::from(steps.get()))))
.unwrap_or_else(|| written_box(height, exact, digits));
}
Item::Group(group) => {
if group.places == GroupPlaces::Points {
for point in group.points_mut() {
*point = written_point(height, *point, digits);
}
}
for item in group.placed_items() {
self.write_digits(height, digits, item);
}
}
Item::Path(_) | Item::Gradient(_) | Item::Image(_) => {}
}
}
}
fn offset_all(items: &mut [Item], place: &dyn Fn(&mut Item)) {
for item in items {
if let Item::Group(group) = item
&& !matches!(group.places, GroupPlaces::Stroked { .. })
{
offset_all(group.placed_items(), place);
}
place(item);
}
}
fn place_edges(
items: &mut [Item],
(across, down): (Offset, Offset),
(width, height): (Length, Length),
) {
for item in items {
let Item::Rect(rect) = item else {
continue;
};
let (left, top) = (rect.x.units(), rect.y.units());
let (right, bottom) = (left + rect.width.units(), top + rect.height.units());
let (left, right) = (
across.written_place(left, width.units()),
across.written_place(right, width.units()),
);
let (top, bottom) = (
down.written_place(top, height.units()),
down.written_place(bottom, height.units()),
);
rect.x = Length::from_units(left);
rect.y = Length::from_units(top);
rect.width = Length::from_units(right - left);
rect.height = Length::from_units(bottom - top);
}
}
fn stroke_items(items: &mut [Item]) {
for item in items {
let Item::Group(group) = item else {
continue;
};
if let GroupPlaces::Stroked { width } = group.places {
let half = Length::from_units(div_round(width.units(), 2));
group.items = std::mem::take(&mut group.items)
.into_iter()
.flat_map(|item| match item {
Item::Rect(rect) => {
let outline = stroke_outline(&rect, half);
vec![Item::Rect(rect), Item::Path(outline)]
}
other => vec![other],
})
.collect();
}
stroke_items(&mut group.items);
}
}
const QUARTER_ARC_ARM: i64 = 552_284_750;
fn stroke_outline(rect: &Rect, half: Length) -> PathItem {
let (left, top) = (rect.x, rect.y);
let (right, bottom) = (rect.x + rect.width, rect.y + rect.height);
let (outer_left, outer_top) = (left - half, top - half);
let (outer_right, outer_bottom) = (right + half, bottom + half);
let start = Point {
x: left,
y: outer_bottom,
};
let sides = [
[
(right, outer_bottom),
(outer_right, outer_bottom),
(outer_right, bottom),
],
[
(outer_right, top),
(outer_right, outer_top),
(right, outer_top),
],
[
(left, outer_top),
(outer_left, outer_top),
(outer_left, top),
],
[
(outer_left, bottom),
(outer_left, outer_bottom),
(left, outer_bottom),
],
];
let mut commands = vec![PathCommand::MoveTo(start)];
for [(end_x, end_y), (corner_x, corner_y), (next_x, next_y)] in sides {
let end = Point { x: end_x, y: end_y };
commands.push(PathCommand::LineTo(end));
commands.push(quarter_arc(
end,
Point {
x: corner_x,
y: corner_y,
},
Point {
x: next_x,
y: next_y,
},
));
}
commands.push(PathCommand::Close);
if rect.width > half + half && rect.height > half + half {
let inner = [
(left, bottom - half),
(left + half, bottom),
(left + half, top),
(left, top + half),
(right, top + half),
(right - half, top),
(right - half, bottom),
(right, bottom - half),
(left, bottom - half),
];
for (index, (x, y)) in inner.into_iter().enumerate() {
let point = Point { x, y };
commands.push(if index == 0 {
PathCommand::MoveTo(point)
} else {
PathCommand::LineTo(point)
});
}
commands.push(PathCommand::Close);
}
PathItem {
commands,
color: rect.color,
fill_rule: FillRule::NonZero,
}
}
fn quarter_arc(from: Point, corner: Point, to: Point) -> PathCommand {
let arm = |distance: Length| {
Length::from_units(div_round(
distance.units().saturating_mul(QUARTER_ARC_ARM),
1_000_000_000,
))
};
let toward = |point: Point| Point {
x: point.x + arm(corner.x - point.x),
y: point.y + arm(corner.y - point.y),
};
PathCommand::CubicTo(toward(from), toward(to), to)
}
fn fraction(number: Binary32) -> (i128, u32) {
let (mantissa, exponent) = (i128::from(number.mantissa()), number.exponent());
match u32::try_from(exponent) {
Ok(up) => (mantissa << up, 0),
Err(_) => (mantissa, exponent.unsigned_abs()),
}
}
fn single_less(a: Binary32, b: Binary32) -> Option<Binary32> {
let ((a, a_shift), (b, b_shift)) = (fraction(a), fraction(b));
let shift = a_shift.max(b_shift);
let exact = (a << (shift - a_shift)) - (b << (shift - b_shift));
single(exact, 1_i128 << shift)
}
fn held(units: i64, per_inch: i64) -> Option<Binary32> {
let inch = i128::from(Length::UNITS_PER_INCH);
let per_inch = i128::from(per_inch);
let steps = div_round_i128(i128::from(units) * per_inch, inch);
if steps == 0 {
return Some(Binary32::ZERO);
}
let (step, shift) = fraction(single(72, per_inch)?);
single(steps * step, 1_i128 << shift)
}
fn held_box(
height: Length,
(x, y, width, tall): (Length, Length, Length, Length),
(digits, per_inch): (Digits, i64),
) -> Option<(Length, Length, Length, Length)> {
let point = i128::from(Length::UNITS_PER_POINT);
let written = |number: Binary32| {
let (significand, shift) = fraction(number);
decimal(
significand,
shift,
significant_decimals(significand, shift, digits),
)
};
let edge = |units: i64| held(units, per_inch);
let (left, right) = (edge(x.units())?, edge(x.units() + width.units())?);
let (top, bottom) = (edge(y.units())?, edge(y.units() + tall.units())?);
let foot = written(single_less(
single(i128::from(height.units()), point)?,
bottom,
)?);
let (left, across) = (written(left), written(single_less(right, left)?));
let down = written(single_less(bottom, top)?);
let (left_units, right_units) = (
decimal_units(left)?,
decimal_units(decimal_sum(left, across))?,
);
let bottom_units = height.units() - decimal_units(foot)?;
let top_units = height.units() - decimal_units(decimal_sum(foot, down))?;
Some((
Length::from_units(left_units),
Length::from_units(top_units),
Length::from_units(right_units - left_units),
Length::from_units(bottom_units - top_units),
))
}
fn written_point(height: Length, point: Point, digits: Digits) -> Point {
let unit = i128::from(Length::UNITS_PER_POINT);
let x = single(i128::from(point.x.units()), unit)
.map(fraction)
.and_then(|(significand, shift)| printed(significand, shift, digits))
.map_or(point.x, Length::from_units);
Point {
x,
y: written_y(height, point.y, digits),
}
}
type Digits = (u32, u32);
fn written_y(height: Length, y: Length, digits: Digits) -> Length {
let point = i128::from(Length::UNITS_PER_POINT);
let difference = match (
single(i128::from(height.units()), point),
single(i128::from(y.units()), point),
) {
(Some(top), Some(low)) => single_less(top, low),
_ => single(i128::from(height.units() - y.units()), point),
};
let Some((significand, shift)) = difference.map(fraction) else {
return y;
};
printed(significand, shift, digits)
.map_or(y, |units| Length::from_units(height.units() - units))
}
fn counted_y(height: Length, y: Length, digits: Digits, per_inch: i64) -> Length {
let point = i128::from(Length::UNITS_PER_POINT);
let inch = i128::from(Length::UNITS_PER_INCH);
let per_inch = i128::from(per_inch);
let scaled = i128::from(y.units()) * per_inch;
if scaled % inch != 0 {
return written_y(height, y, digits);
}
let count = scaled / inch;
let points = single(count, per_inch)
.map(fraction)
.and_then(|(significand, shift)| single(significand * 72, 1_i128 << shift));
let difference = single(i128::from(height.units()), point)
.zip(points)
.and_then(|(top, low)| single_less(top, low));
let Some((significand, shift)) = difference.map(fraction) else {
return written_y(height, y, digits);
};
printed(significand, shift, digits)
.map_or(y, |units| Length::from_units(height.units() - units))
}
fn written_box(
height: Length,
(x, y, width, tall): (Length, Length, Length, Length),
digits: Digits,
) -> (Length, Length, Length, Length) {
let point = i128::from(Length::UNITS_PER_POINT);
let written = |length: Length| {
single(i128::from(length.units()), point)
.map(fraction)
.and_then(|(significand, shift)| printed(significand, shift, digits))
.map_or(length, Length::from_units)
};
let written_tall = written(tall);
let bottom = written_y(height, Length::from_units(y.units() + tall.units()), digits);
(
written(x),
Length::from_units(bottom.units() - written_tall.units()),
written(width),
written_tall,
)
}
fn printed(significand: i128, shift: u32, (digits, least): Digits) -> Option<i64> {
let whole = (significand >> shift).max(1);
let decimals = digits.saturating_sub(whole.ilog10() + 1).max(least);
decimal_units(decimal(significand, shift, decimals))
}
fn significant_decimals(significand: i128, shift: u32, (digits, least): Digits) -> u32 {
let whole = significand >> shift;
if whole > 0 {
return digits.saturating_sub(whole.ilog10() + 1).max(least);
}
let mut decimals = digits;
let mut scaled = significand * 10;
while significand > 0 && scaled < 1 << shift {
decimals += 1;
scaled *= 10;
}
decimals
}
type Decimal = (i128, i128);
fn decimal(significand: i128, shift: u32, decimals: u32) -> Decimal {
let scale = i128::from(f_office_units::scale::TENTHS).pow(decimals);
(
(significand * scale * 2 + (1 << shift)) >> (shift + 1),
scale,
)
}
fn decimal_sum((a, a_scale): Decimal, (b, b_scale): Decimal) -> Decimal {
let scale = a_scale.max(b_scale);
(a * (scale / a_scale) + b * (scale / b_scale), scale)
}
fn decimal_units((value, scale): Decimal) -> Option<i64> {
let point = i128::from(Length::UNITS_PER_POINT);
i64::try_from(div_round_i128(value * point, scale)).ok()
}
#[must_use]
pub fn single(numerator: i128, denominator: i128) -> Option<Binary32> {
if numerator <= 0 || denominator <= 0 {
return None;
}
let mut exponent =
i32::try_from(numerator.ilog2()).ok()? - i32::try_from(denominator.ilog2()).ok()?;
let below = if exponent >= 0 {
numerator < denominator << exponent
} else {
numerator << -exponent < denominator
};
if below {
exponent -= 1;
}
let shift = u32::try_from(i32::try_from(Binary32::BITS).ok()? - 1 - exponent).ok()?;
if shift > u32::BITS * 2 {
return None;
}
Some(Binary32::nearest(numerator, denominator))
}
struct Stretch {
taller: i64,
height: i64,
glyph_step: Option<Length>,
factor: Fraction,
offset: Fraction,
}
impl Stretch {
fn glyph_y(&self, y: Length) -> Length {
let Some(glyph_step) = self.glyph_step else {
return self.y(y);
};
let distance = i128::from(y.units()) * i128::from(self.taller - self.height);
let per_step = i128::from(self.height) * i128::from(glyph_step.units());
let (factor, of) = (i128::from(self.factor.0), i128::from(self.factor.1));
let (offset, by) = (i128::from(self.offset.0), i128::from(self.offset.1));
let whole = of * by * per_step;
let steps = div_round_i128(distance * factor * by + offset * of * per_step, whole);
let moved = i64::try_from(steps * i128::from(glyph_step.units())).unwrap_or(i64::MAX);
Length::from_units(y.units().saturating_add(moved))
}
fn y(&self, y: Length) -> Length {
let product = i128::from(y.units()) * i128::from(self.taller);
let height = i128::from(self.height);
let rounded = div_round_i128(product, height);
Length::from_units(i64::try_from(rounded).unwrap_or(i64::MAX))
}
fn stepped_span(&self, (top, height): (Length, Length)) -> (Length, Length) {
let new_top = self.glyph_y(top);
let bottom = self.glyph_y(Length::from_units(top.units() + height.units()));
(
new_top,
Length::from_units(bottom.units() - new_top.units()),
)
}
fn point(&self, point: &mut Point) {
point.y = self.y(point.y);
}
fn item(&self, item: &mut Item) {
match item {
Item::Glyphs(run) => {
for glyph in &mut run.glyphs {
glyph.y = self.glyph_y(glyph.y);
}
}
Item::Rect(rect) => (rect.y, rect.height) = self.stepped_span((rect.y, rect.height)),
Item::Path(path) => {
for point in path.commands.iter_mut().flat_map(PathCommand::points_mut) {
self.point(point);
}
}
Item::Gradient(gradient) => {
let axis = [&mut gradient.start, &mut gradient.end];
let outline = gradient
.commands
.iter_mut()
.flat_map(PathCommand::points_mut);
for point in outline.chain(axis) {
self.point(point);
}
}
Item::Group(group) => {
if group.places != GroupPlaces::Own {
let clip = group.clip.iter_mut().flat_map(|clip| &mut clip.commands);
for point in clip.flat_map(PathCommand::points_mut) {
self.point(point);
}
}
for item in group.placed_items() {
self.item(item);
}
}
Item::Image(_) => {}
}
}
}
#[cfg(test)]
mod tests {
use std::sync::Arc;
use f_office_units::Length;
use super::{
DEFAULT_LINEAR_LIMIT, DisplayList, Glyph, GlyphRun, Image, ImageFormat, JpegQuality,
LinearLimit, Offset, OffsetProduct, Orientation, Page, PaletteClass, PaletteDensity,
PictureDensity, Resampler, Rgb, Writer, WriterOffset,
};
#[test]
fn takes_the_linear_interpolation_up_to_a_count_or_up_to_a_side() {
let count = |n| std::num::NonZeroU32::new(n).unwrap();
let (pixels, side) = (
LinearLimit::Pixels(count(1 << 17)),
LinearLimit::Side(count(419)),
);
let cases = [
(pixels, (400, 327), true),
(pixels, (400, 328), false),
(pixels, (480, 270), true),
(side, (419, 419), true),
(side, (420, 100), false),
(side, (100, 420), false),
(side, (480, 270), false),
];
for (limit, size, linear) in cases {
assert_eq!(limit.takes_linear(size), linear, "{limit:?} {size:?}");
}
assert_eq!(DEFAULT_LINEAR_LIMIT, pixels);
}
#[test]
fn answers_with_the_filter_of_its_own_limit() {
let side = LinearLimit::Side(std::num::NonZeroU32::new(419).unwrap());
let density = PictureDensity {
limit_ppi: std::num::NonZeroU32::new(275).unwrap(),
ppi: std::num::NonZeroU32::new(200).unwrap(),
};
let writer = Writer::new(Length::from_units(10))
.unwrap()
.with_picture_density(Some(density))
.with_linear_limit(side);
let inch = Length::from_units(Length::UNITS_PER_INCH);
let answer = writer.resampled_size((600, 600), (inch, inch), None);
assert_eq!(answer, Some(((199, 199), Resampler::Filter(side))));
}
#[test]
fn a_filled_path_draws_quadratic_curves_as_cubic_curves_of_whole_units() {
use super::PathCommand::{Close, CubicTo, LineTo, MoveTo, QuadTo};
let at = |x, y| super::Point {
x: Length::from_units(x),
y: Length::from_units(y),
};
let commands = [
MoveTo(at(0, 0)),
QuadTo(at(30, 10), at(31, 0)),
Close,
QuadTo(at(3, 3), at(6, 0)),
LineTo(at(9, 9)),
];
let expected = vec![
MoveTo(at(0, 0)),
CubicTo(at(20, 7), at(30, 7), at(31, 0)),
Close,
CubicTo(at(2, 2), at(4, 2), at(6, 0)),
LineTo(at(9, 9)),
];
assert_eq!(super::fill_commands(&commands), expected);
assert_eq!(
super::fill_commands(&[QuadTo(at(3, 3), at(6, 0))]),
vec![CubicTo(at(3, 3), at(4, 2), at(6, 0))]
);
}
#[test]
fn a_filled_path_leaves_out_lines_to_their_own_start() {
use super::PathCommand::{Close, LineTo, MoveTo};
let at = |x, y| super::Point {
x: Length::from_units(x),
y: Length::from_units(y),
};
let commands = [
MoveTo(at(5, 5)),
LineTo(at(5, 5)),
LineTo(at(9, 5)),
LineTo(at(9, 5)),
LineTo(at(9, 9)),
Close,
LineTo(at(5, 5)),
LineTo(at(7, 7)),
];
let expected = vec![
MoveTo(at(5, 5)),
LineTo(at(9, 5)),
LineTo(at(9, 9)),
Close,
LineTo(at(7, 7)),
];
assert_eq!(super::fill_commands(&commands), expected);
}
#[test]
fn a_fill_at_most_the_thinnest_fill_across_paints_nothing() {
use super::PathCommand::{Close, CubicTo, LineTo, MoveTo};
let at = |x, y| super::Point {
x: Length::from_units(x),
y: Length::from_units(y),
};
let bar = |across| {
[
MoveTo(at(0, 0)),
LineTo(at(across, 0)),
LineTo(at(across, 5000)),
LineTo(at(0, 5000)),
Close,
]
};
assert!(!super::path_shows(&bar(100)));
assert!(super::path_shows(&bar(101)));
assert!(!super::fill_shows(
Length::from_units(5000),
Length::from_units(-100)
));
assert!(super::fill_shows(
Length::from_units(5000),
Length::from_units(-101)
));
let bowed = [
MoveTo(at(0, 0)),
CubicTo(at(150, 1000), at(150, 4000), at(0, 5000)),
Close,
];
assert!(super::path_shows(&bowed));
assert!(!super::path_shows(&[]));
}
fn write_digits(writer: &Writer, height: Length, item: &mut super::Item) {
let digits = (writer.digits().unwrap().get(), writer.least_decimals());
writer.write_digits(height, digits, item);
}
#[test]
fn gives_the_text_of_a_glyph_only_on_whole_characters() {
let run = GlyphRun {
font: f_office_fonts::FontId::from_index(0),
size: Length::ZERO,
color: Rgb::BLACK,
text: "a\u{e9}".to_owned(),
glyphs: Vec::new(),
outline: None,
filled: true,
effect: false,
turn: None,
};
let glyph = |text_start, text_end| Glyph {
id: 0,
x: Length::ZERO,
y: Length::ZERO,
text_start,
text_end,
};
assert_eq!(run.glyph_text(&glyph(0, 1)), Some("a"));
assert_eq!(run.glyph_range(&glyph(1, 3)), Some(1..3));
assert_eq!(run.glyph_text(&glyph(1, 3)), Some("\u{e9}"));
assert_eq!(run.glyph_text(&glyph(1, 1)), Some(""));
for (start, end) in [(1, 2), (2, 3), (1, 0), (0, 4)] {
assert_eq!(run.glyph_range(&glyph(start, end)), None, "{start}..{end}");
assert_eq!(run.glyph_text(&glyph(start, end)), None, "{start}..{end}");
}
}
fn non_zero(count: u32) -> std::num::NonZeroU32 {
std::num::NonZeroU32::new(count).unwrap()
}
fn density(limit_ppi: u32, ppi: u32) -> PictureDensity {
PictureDensity {
limit_ppi: non_zero(limit_ppi),
ppi: non_zero(ppi),
}
}
#[test]
fn reads_six_hexadecimal_digits_only() {
let rgb = |r, g, b| Some(Rgb { r, g, b });
assert_eq!(Rgb::from_hex("FF0080"), rgb(255, 0, 128));
assert_eq!(Rgb::from_hex("1f3864"), rgb(31, 56, 100));
for wrong in [
"+FFFFF", "+F+F+F", "-FFFFF", "FFFFF", "FFFFFFF", "GGGGGG", " FFFFF", "auto",
] {
assert_eq!(Rgb::from_hex(wrong), None, "{wrong}");
}
}
fn every_kind(at: impl Fn(i64) -> super::Point, by: impl Fn(i64) -> Length) -> super::Item {
use super::{
Clip, FillRule, Glyph, GlyphRun, Group, GroupClip, GroupPlaces, ImageItem, Item, Join,
Outline, PathCommand, PathItem, Rect,
};
let glyph = |n: i64| Glyph {
id: 1,
x: at(n).x,
y: at(n).y,
text_start: 0,
text_end: 1,
};
let run = GlyphRun {
font: f_office_fonts::FontId::from_index(0),
size: by(1),
color: Rgb::BLACK,
text: "a".to_owned(),
glyphs: vec![glyph(1), glyph(2)],
outline: Some(Outline {
width: by(2),
color: Rgb::BLACK,
join: Join::Round,
}),
filled: true,
effect: false,
turn: None,
};
let rect = Rect {
x: at(3).x,
y: at(3).y,
width: by(3),
height: by(4),
color: Rgb::BLACK,
};
let path = PathItem {
commands: vec![
PathCommand::MoveTo(at(4)),
PathCommand::LineTo(at(5)),
PathCommand::QuadTo(at(6), at(7)),
PathCommand::CubicTo(at(8), at(9), at(10)),
PathCommand::Close,
],
color: Rgb::BLACK,
fill_rule: FillRule::NonZero,
};
let image = ImageItem {
x: at(11).x,
y: at(11).y,
width: by(5),
height: by(6),
clip: Some(Clip {
x: at(12).x,
y: at(12).y,
width: by(7),
height: by(8),
}),
turn: None,
image: Image::new(vec![0]),
};
Item::Group(Group::new(vec![
Item::Glyphs(run),
Item::Group(Group {
items: vec![Item::Rect(rect), Item::Path(path)],
clip: Some(GroupClip {
commands: vec![
PathCommand::MoveTo(at(13)),
PathCommand::LineTo(at(14)),
PathCommand::QuadTo(at(15), at(16)),
PathCommand::Close,
],
fill_rule: FillRule::EvenOdd,
}),
places: GroupPlaces::Own,
}),
Item::Image(image),
]))
}
#[test]
fn maps_every_place_and_length_of_an_item_and_of_the_items_of_its_groups() {
use super::Point;
let u = Length::from_units;
let at = |n: i64| Point {
x: u(2 * n - 1),
y: u(2 * n),
};
let mut item = every_kind(at, |n| u(10 * n));
item.map_places(
|p| Point {
x: p.x + u(1),
y: p.y * 2,
},
|v| v * 3,
);
let mapped = |n: i64| Point {
x: u(2 * n),
y: u(4 * n),
};
assert_eq!(item, every_kind(mapped, |n| u(30 * n)));
}
#[test]
fn gives_the_pages_and_the_parts_that_it_was_built_from() {
use super::Point;
let u = Length::from_units;
let at = |n: i64| Point { x: u(n), y: u(n) };
let items = vec![every_kind(at, u), every_kind(at, |n| u(2 * n))];
let landscape = Orientation::Landscape;
let page = Page::new(u(300), u(400), landscape, items.clone());
assert_eq!((page.width(), page.height()), (u(300), u(400)));
assert_eq!(page.orientation(), landscape);
assert_eq!(page.items(), items.as_slice());
let empty = Page::new(u(5), u(6), Orientation::Portrait, Vec::new());
let list = DisplayList::new(vec![page.clone(), empty.clone()]);
assert_eq!(list.pages(), [page.clone(), empty.clone()].as_slice());
assert_eq!(list.into_pages(), vec![page.clone(), empty]);
let fewer = page.map_items(|mut kept| {
kept.truncate(1);
kept
});
assert_eq!(
fewer,
Page::new(u(300), u(400), landscape, items[..1].to_vec())
);
}
#[test]
fn writes_the_page_size_in_whole_steps() {
assert_eq!(Writer::new(Length::ZERO), None);
let step = Length::from_units(Length::UNITS_PER_DOT);
let writer = Writer::new(step).unwrap();
let page = |width, height| Page {
width: Length::from_units(width),
height: Length::from_units(height),
orientation: Orientation::Portrait,
items: Vec::new(),
};
let mut list = DisplayList {
pages: vec![page(15_120_000, 3048 + 6096 * 3)],
};
writer.finish(&mut list);
assert_eq!(list.pages[0].width.units(), 2480 * 6096);
assert_eq!(list.pages[0].height.units(), 4 * 6096);
}
#[test]
fn keeps_the_picture_files_unless_it_has_a_jpeg_quality() {
let writer = Writer::new(Length::from_units(10)).unwrap();
assert_eq!(writer.jpeg_quality(), None);
let quality = JpegQuality::new(75);
assert_eq!(writer.with_jpeg_quality(quality).jpeg_quality(), quality);
assert_eq!(writer.with_jpeg_quality(None), writer);
}
#[test]
fn keeps_an_opacity_between_none_and_a_whole() {
use super::Opacity;
assert_eq!(Opacity::clamped(-5).share(), 0);
assert_eq!(Opacity::clamped(150_000), Opacity::FULL);
assert_eq!(Opacity::FULL.share(), 100_000);
let half = Opacity::clamped(50_000);
assert_eq!(half.times(Opacity::clamped(50_001)).share(), 25_001);
assert_eq!(Opacity::FULL.times(half), half);
}
#[test]
fn takes_a_jpeg_quality_of_1_to_100_only() {
assert_eq!(JpegQuality::new(1).map(JpegQuality::get), Some(1));
assert_eq!(JpegQuality::new(100).map(JpegQuality::get), Some(100));
assert_eq!(JpegQuality::new(0), None);
assert_eq!(JpegQuality::new(101), None);
assert_eq!(JpegQuality::new(255), None);
}
#[test]
fn resamples_pictures_denser_than_the_limit_below_its_density() {
let inches =
|hundredths: i64| Length::from_units(Length::UNITS_PER_INCH * hundredths / 100);
let size = (
inches(150),
Length::from_units(Length::UNITS_PER_POINT * 81),
);
let writer = Writer::new(Length::from_units(10)).unwrap();
assert_eq!(writer.resampled_size((600, 450), size, None), None);
let writer = writer.with_picture_density(Some(density(275, 200)));
let filter = |pixels| Some((pixels, Resampler::Filter(DEFAULT_LINEAR_LIMIT)));
assert_eq!(writer.resampled_size((412, 309), size, None), None);
assert_eq!(
writer.resampled_size((414, 311), size, None),
filter((299, 224))
);
assert_eq!(
writer.resampled_size((600, 450), size, None),
filter((299, 224))
);
let size = (
inches(125),
Length::from_units(Length::UNITS_PER_POINT * 135 / 2),
);
assert_eq!(
writer.resampled_size((500, 375), size, None),
filter((249, 187))
);
assert_eq!(
writer.resampled_size((600, 100), size, None),
filter((249, 100))
);
assert_eq!(
writer.resampled_size((600, 450), (Length::from_units(0), size.1), None),
None
);
}
#[test]
fn resamples_a_palette_of_a_class_by_the_limits_of_its_class() {
let size = (
Length::from_units(Length::UNITS_PER_INCH),
Length::from_units(Length::UNITS_PER_INCH * 3 / 10),
);
let palettes = PaletteDensity {
one_bit_limit_ppi: non_zero(750),
one_bit_ppi: non_zero(600),
four_bits_limit_ppi: non_zero(562),
eight_bits_limit_ppi: non_zero(395),
};
let writer = Writer::new(Length::from_units(10))
.unwrap()
.with_picture_density(Some(density(275, 200)));
let (centre, filter) = (
Resampler::CentrePixel,
Resampler::Filter(DEFAULT_LINEAR_LIMIT),
);
let classes = [
(
Some(PaletteClass::OneBit),
749_usize,
750_usize,
(599, 179),
centre,
),
(
Some(PaletteClass::FourBitColor),
561,
562,
(199, 59),
filter,
),
(
Some(PaletteClass::EightBitColor),
394,
395,
(199, 59),
filter,
),
(None, 274, 275, (199, 59), filter),
];
let with = writer.with_palette_density(Some(palettes));
for (class, kept, dense, new, resampler) in classes {
let (kept, dense) = ((kept, kept * 3 / 10), (dense, (dense * 3).div_ceil(10)));
assert_eq!(with.resampled_size(kept, size, class), None);
let written = with.resampled_size(dense, size, class);
assert_eq!(written, Some((new, resampler)));
let general = writer.resampled_size(dense, size, class);
assert_eq!(general, Some(((199, 59), filter)));
}
let none = Writer::new(Length::from_units(10))
.unwrap()
.with_palette_density(Some(palettes));
let one_bit = Some(PaletteClass::OneBit);
assert_eq!(none.resampled_size((900, 270), size, one_bit), None);
}
fn half_inch_sizes(
limit_ppi: u32,
ppi: u32,
pixels: &[(usize, usize)],
) -> Vec<Option<(usize, usize)>> {
let half = Length::from_units(Length::UNITS_PER_POINT * 36);
let writer = Writer::new(Length::from_units(10))
.unwrap()
.with_picture_density(Some(density(limit_ppi, ppi)));
pixels
.iter()
.map(|&pixels| writer.resampled_size(pixels, (half, half), None))
.map(|written| written.map(|(pixels, _)| pixels))
.collect()
}
#[test]
fn resamples_only_the_directions_denser_than_a_limit_of_275_ppi() {
assert_eq!(
half_inch_sizes(275, 200, &[(145, 130), (130, 145), (145, 138), (145, 137)]),
[
Some((99, 130)),
Some((130, 99)),
Some((99, 99)),
Some((99, 137))
]
);
}
#[test]
fn resamples_only_the_directions_at_a_limit_of_450_ppi_or_denser() {
assert_eq!(
half_inch_sizes(
450,
300,
&[(223, 223), (225, 225), (225, 175), (200, 225), (225, 150)]
),
[
None,
Some((149, 149)),
Some((149, 175)),
Some((200, 149)),
Some((149, 150))
]
);
}
fn across(limit_ppi: u32, ppi: u32, pixels: usize, units: i64) -> usize {
let writer = Writer::new(Length::from_units(10))
.unwrap()
.with_picture_density(Some(density(limit_ppi, ppi)));
let size = (
Length::from_units(units),
Length::from_emus(137_160).unwrap(),
);
writer
.resampled_size((pixels, 30), size, None)
.map_or(pixels, |(written, _)| written.0)
}
#[test]
fn tests_and_resamples_the_drawn_size_itself() {
let cases = [
(450, 300, 225, 914_400, 149),
(450, 300, 225, 915_670, 225),
(275, 200, 225, 914_400, 99),
(275, 200, 225, 915_670, 100),
(275, 200, 275, 1_828_800, 199),
(275, 200, 275, 1_828_801, 275),
(450, 300, 211, 573_024, 93),
(450, 300, 211, 573_025, 94),
(275, 200, 211, 932_688, 101),
(275, 200, 211, 932_689, 102),
(450, 300, 211, 857_504, 140),
(450, 300, 211, 857_505, 211),
];
for (limit, ppi, pixels, units, written) in cases {
assert_eq!(
across(limit, ppi, pixels, units),
written,
"{pixels} on {units}"
);
}
}
#[test]
fn stretches_glyphs_and_rectangles_down_by_the_steps_of_the_page() {
use super::Item;
let page = stretched();
let Item::Glyphs(run) = &page.items[0] else {
panic!("no glyphs")
};
assert_eq!(
(run.glyphs[0].x.units(), run.glyphs[0].y.units()),
(500, 402)
);
assert_eq!(run.size.units(), 120);
let Item::Rect(rect) = &page.items[1] else {
panic!("no rect")
};
let units = [rect.x, rect.y, rect.width, rect.height].map(Length::units);
assert_eq!(units, [100, 201, 300, 402]);
assert_eq!((page.width.units(), page.height.units()), (1000, 2000));
}
#[test]
fn stretches_paths_down_and_leaves_pictures_and_everything_without_a_stretch() {
use super::{Item, PathCommand, Point};
let page = stretched();
let Item::Path(path) = &page.items[2] else {
panic!("no path")
};
let corner = Point {
x: Length::from_units(1000),
y: Length::from_units(2010),
};
assert_eq!(path.commands[0], PathCommand::MoveTo(corner));
assert_eq!(page.items[3], sample_page().items[3]);
let mut plain = DisplayList {
pages: vec![sample_page()],
};
Writer::new(Length::from_units(10))
.unwrap()
.finish(&mut plain);
assert_eq!(plain.pages[0], sample_page());
}
#[test]
fn holds_a_quotient_as_the_nearest_single_precision_number() {
use super::{fraction, single};
let cases = [
((744_975, 1000), Some((12_205_670, 14))),
((434_125, 1000), Some((14_225_408, 15))),
((1, 3), Some((11_184_811, 25))),
((2, 3), Some((11_184_811, 24))),
((123_456_789, 25_400), Some((9_954_311, 11))),
((16_777_217, 2), Some((8_388_608, 0))),
((16_777_217, 1), None),
((0, 1), None),
(((1 << 25) - 1, 2), Some((1 << 24, 0))),
];
for ((numerator, denominator), expected) in cases {
assert_eq!(
single(numerator, denominator).map(fraction),
expected,
"{numerator}/{denominator}"
);
}
}
#[test]
fn writes_a_baseline_from_the_bottom_with_significant_digits() {
use super::written_y;
let point =
|thousandths: i64| Length::from_units(thousandths * Length::UNITS_PER_POINT / 1000);
let page = point(792_000);
assert_eq!(written_y(page, point(357_875), (5, 0)), point(357_870));
assert_eq!(written_y(page, point(47_025), (5, 0)), point(47_030));
assert_eq!(written_y(page, point(82_275), (5, 0)), point(82_280));
assert_eq!(written_y(page, point(741_025), (5, 0)), point(741_025));
assert_eq!(written_y(page, point(800_000), (5, 0)), point(800_000));
assert_eq!(written_y(page, point(586_425), (5, 0)), point(586_420));
}
#[test]
fn writes_a_baseline_from_its_count_of_steps() {
use super::{counted_y, written_y};
let point =
|thousandths: i64| Length::from_units(thousandths * Length::UNITS_PER_POINT / 1000);
let page = point(792_000);
let counted = |y: i64| counted_y(page, point(y), (5, 2), 2_880);
let written = |y: i64| written_y(page, point(y), (5, 2));
let pairs = [582_925, 273_825].map(|y| (counted(y), written(y)));
assert_eq!(pairs[0], (point(582_930), point(582_920)));
assert_eq!(pairs[1], (point(273_820), point(273_830)));
for same in [587_925, 586_425, 357_875, 744_975, 300_000] {
assert_eq!(counted(same), written(same), "{same}");
}
}
#[test]
fn writes_a_baseline_off_the_steps_from_its_own_points() {
use super::{counted_y, written_y};
let point =
|thousandths: i64| Length::from_units(thousandths * Length::UNITS_PER_POINT / 1000);
let page = point(792_000);
let counted = |y: i64| counted_y(page, point(y), (5, 2), 2_880);
let written = |y: i64| written_y(page, point(y), (5, 2));
for y in [0, 800_000, 582_938] {
assert_eq!(counted(y), written(y), "{y}");
}
assert_eq!(counted(582_938), point(582_940));
}
#[test]
fn writes_glyph_baselines_from_their_counts_where_the_writer_holds_steps() {
use super::{Glyph, GlyphRun, Item};
let point =
|thousandths: i64| Length::from_units(thousandths * Length::UNITS_PER_POINT / 1000);
let glyphs = || {
Item::Glyphs(GlyphRun {
font: f_office_fonts::FontId::from_index(0),
size: point(11_000),
color: Rgb::BLACK,
text: "a".to_owned(),
glyphs: vec![Glyph {
id: 1,
x: point(72_000),
y: point(582_925),
text_start: 0,
text_end: 1,
}],
outline: None,
filled: true,
effect: false,
turn: None,
})
};
let baseline = |writer: &Writer| {
let mut item = glyphs();
write_digits(writer, point(792_000), &mut item);
let Item::Glyphs(run) = item else {
unreachable!()
};
run.glyphs[0].y
};
let writer = Writer::new(Length::from_units(10))
.unwrap()
.with_digits(Some(non_zero(5)))
.with_least_decimals(2);
let counting = writer.with_baseline_steps(Some(non_zero(2_880)));
assert_eq!(counting.baseline_steps(), Some(non_zero(2_880)));
assert_eq!(writer.baseline_steps(), None);
assert_eq!(baseline(&counting), point(582_930));
assert_eq!(baseline(&writer), point(582_920));
}
#[test]
fn writes_a_baseline_from_1000_pt_with_the_least_decimals() {
use super::written_y;
let point =
|thousandths: i64| Length::from_units(thousandths * Length::UNITS_PER_POINT / 1000);
let page = point(1_584_000);
assert_eq!(written_y(page, point(576_120), (5, 0)), point(576_100));
assert_eq!(written_y(page, point(576_120), (5, 2)), point(576_120));
assert_eq!(written_y(page, point(576_400), (5, 2)), point(576_400));
let letter = point(792_000);
assert_eq!(written_y(letter, point(357_875), (5, 2)), point(357_870));
assert_eq!(written_y(letter, point(741_025), (5, 2)), point(741_025));
}
#[test]
fn offsets_a_rectangles_edges_as_a_text_objects_start() {
let writer = Writer::new(Length::from_units(10))
.unwrap()
.with_horizontal_offset(WriterOffset::EveryPage(Offset::Share {
share: 2_400,
bias: 18,
step: 635,
}));
let point = |thousandths: i64| Length::from_units(thousandths * 254 / 10);
let (width, height) = (point(612_000), point(792_000));
let across = |writer: Writer, x: Length| {
Length::from_units(
writer
.page_offsets(width, height, Orientation::Portrait)
.0
.of(x.units(), width.units()),
)
};
assert_eq!(across(writer, point(66_500)), point(25));
assert_eq!(across(writer, point(186_750)), point(75));
assert_eq!(
across(Writer::new(Length::from_units(10)).unwrap(), point(66_500)),
point(0)
);
}
const fn page_form(c: i64, parts: i64) -> Offset {
Offset::Page {
steps: (c, 100_000),
parts,
per_inch: 3_000,
product: OffsetProduct::Exact,
}
}
const fn binary32_page_form(c: i64) -> Offset {
Offset::Page {
steps: (c, 100_000),
parts: 16,
per_inch: 3_000,
product: OffsetProduct::Binary32 { dots_per_inch: 600 },
}
}
#[test]
fn rounds_the_product_of_the_dot_and_the_page_entry_in_binary32() {
let offset = |c, k: i64| binary32_page_form(c).of(k * DOT, LETTER);
assert_eq!(page_form(472_515, 16).of(3_743 * DOT, LETTER), 1_829);
assert_eq!(offset(472_515, 3_743), 2_438);
assert_eq!(offset(472_515, 3_742), 1_829);
for k in [600, 1_585, 1_586, 2_664, 2_665, 3_744] {
assert_eq!(
offset(472_515, k),
page_form(472_515, 16).of(k * DOT, LETTER)
);
}
assert_eq!(
binary32_page_form(472_515).of(3_743 * DOT + 1_000, LETTER),
2_438
);
assert_eq!(binary32_page_form(472_515).of(3_743 * DOT, 0), 0);
}
const DOT: i64 = 3_048;
const LETTER: i64 = 12_240 * 1_270;
#[test]
fn offsets_a_place_by_whole_steps_as_if_the_page_were_larger() {
for k in [600, 646, 692] {
assert_eq!(page_form(472_515, 16).of(k * DOT, LETTER), 610);
}
assert_eq!(page_form(472_515, 16).of(0, LETTER), 0);
assert_eq!(Offset::None.of(1_585 * DOT, LETTER), 0);
}
#[test]
fn rounds_the_product_of_the_page_form_before_the_division() {
assert_eq!(page_form(473_073, 16).of(1_585 * DOT, LETTER), 1_219);
assert_eq!(page_form(473_073, 16).of(1_583 * DOT, LETTER), 610);
assert_eq!(page_form(473_073, 1).of(1_585 * DOT, LETTER), 610);
assert_eq!(page_form(473_073, 0).of(1_585 * DOT, LETTER), 0);
}
#[test]
fn writes_a_rectangle_with_significant_digits() {
use super::Item;
let u = Length::from_units;
let writer = Writer::new(u(10)).unwrap().with_digits(Some(non_zero(5)));
let mut rect = Item::Rect(super::Rect {
x: u(3_023_870),
y: u(16_426_262),
width: u(9_084_361),
height: u(12_700),
color: super::Rgb::BLACK,
});
write_digits(&writer, u(842 * 25_400), &mut rect);
let Item::Rect(rect) = rect else {
unreachable!()
};
assert_eq!(
(
rect.x.units(),
rect.y.units(),
rect.width.units(),
rect.height.units()
),
(3_023_870, 16_426_180, 9_084_310, 12_700)
);
}
#[test]
fn writes_a_rectangle_from_its_edges_on_the_steps() {
use super::Item;
let u = Length::from_units;
let writer = Writer::new(u(10))
.unwrap()
.with_digits(Some(non_zero(5)))
.with_rectangle_steps(Some(non_zero(3_000)));
let rect = |x, y, width, height| {
Item::Rect(super::Rect {
x: u(x),
y: u(y),
width: u(width),
height: u(height),
color: super::Rgb::BLACK,
})
};
let mut rule = rect(8_029_651, 12_922_301, 12_192, 12_192);
write_digits(&writer, u(792 * 25_400), &mut rule);
let Item::Rect(rule) = rule else {
unreachable!()
};
let edges = |r: &super::Rect| (r.x.units(), r.y.units(), r.width.units(), r.height.units());
assert_eq!(edges(&rule), (8_029_702, 12_922_251, 12_192, 12_191));
let mut wide = rect(-25_400, 12_922_301, 50_800, 12_192);
write_digits(&writer, u(792 * 25_400), &mut wide);
let Item::Rect(wide) = wide else {
unreachable!()
};
assert_eq!(edges(&wide).2, 50_800);
assert_eq!(writer.rectangle_steps(), Some(non_zero(3_000)));
let far = || rect(25_974_446, 12_922_301, 12_192, 12_192);
let written = |writer: Writer| {
let mut item = far();
write_digits(&writer, u(792 * 25_400), &mut item);
let Item::Rect(written) = item else {
unreachable!()
};
edges(&written)
};
let (left, top, _, tall) = written(writer);
assert_eq!((left, top, tall), (25_974_040, 12_922_251, 12_191));
let (left, top, _, tall) = written(writer.with_least_decimals(2));
assert_eq!((left, top, tall), (25_974_548, 12_922_251, 12_191));
}
#[test]
fn writes_an_upright_image_with_significant_digits() {
use super::{ImageItem, Item, Turn};
let u = Length::from_units;
let image = |turn| {
Item::Image(ImageItem {
x: u(1_143_000),
y: u(1_682_799),
width: u(914_400),
height: u(1_219_200),
clip: None,
turn,
image: Image::new(vec![0]),
})
};
let turn = Turn {
xx: 0,
xy: -Turn::SCALE,
yx: Turn::SCALE,
yy: 0,
};
let placed = |writer: Writer| {
let mut list = DisplayList {
pages: vec![Page {
width: u(612 * 25_400),
height: u(792 * 25_400),
orientation: Orientation::Portrait,
items: vec![image(None), image(Some(turn))],
}],
};
writer.finish(&mut list);
writer.place_pictures(&mut list);
list.pages[0]
.items
.iter()
.map(|item| match item {
Item::Image(image) => (image.x, image.y, image.width, image.height),
_ => unreachable!(),
})
.collect::<Vec<_>>()
};
let exact = (u(1_143_000), u(1_682_799), u(914_400), u(1_219_200));
let writer = Writer::new(u(10)).unwrap();
assert_eq!(
placed(writer.with_picture_digits(Some(non_zero(5)))),
[
(u(1_143_000), u(1_682_750), u(914_400), u(1_219_200)),
exact
]
);
assert_eq!(
placed(writer.with_digits(Some(non_zero(5)))),
[exact, exact]
);
}
#[test]
fn rounds_the_stretch_of_a_glyph_to_whole_steps() {
use super::Item;
let moved = |step: Option<i64>| {
let writer = Writer::new(Length::from_units(10))
.unwrap()
.with_vertical_stretch(1)
.with_glyph_stretch_step(step.map(Length::from_units))
.unwrap();
let mut list = DisplayList {
pages: vec![sample_page()],
};
writer.finish(&mut list);
let (Item::Glyphs(run), Item::Rect(rect)) =
(&list.pages[0].items[0], &list.pages[0].items[1])
else {
panic!("no glyphs or rect")
};
(run.glyphs[0].y.units(), rect.y.units())
};
assert_eq!(moved(None), (402, 201));
assert_eq!(moved(Some(3)), (403, 200));
assert_eq!(moved(Some(5)), (400, 200));
assert_eq!(moved(Some(4)), (404, 200));
}
#[test]
fn refuses_a_glyph_stretch_step_that_is_not_positive() {
let writer = Writer::new(Length::from_units(10)).unwrap();
assert_eq!(writer.with_glyph_stretch_step(Some(Length::ZERO)), None);
assert_eq!(
writer.with_glyph_stretch_step(Some(Length::from_units(-4))),
None
);
assert_eq!(writer.with_glyph_stretch_step(None), Some(writer));
}
fn stepping_writer() -> Writer {
Writer::new(Length::from_units(10))
.unwrap()
.with_vertical_stretch(1)
.with_glyph_stretch_step(Some(Length::from_units(4)))
.unwrap()
}
fn moved(offset: super::Fraction, factors: &[(Length, super::Fraction)]) -> (i64, i64) {
use super::Item;
let mut list = DisplayList {
pages: vec![sample_page()],
};
stepping_writer()
.with_stretch_factors(offset, factors)
.unwrap()
.finish(&mut list);
let (Item::Glyphs(run), Item::Rect(rect)) =
(&list.pages[0].items[0], &list.pages[0].items[1])
else {
panic!("no glyphs or rect")
};
(run.glyphs[0].y.units(), rect.y.units())
}
#[test]
fn counts_the_steps_of_the_stretch_with_the_factor_and_offset_of_the_page_height() {
let u = Length::from_units;
let page = u(2000);
assert_eq!(moved((0, 1), &[]), (404, 200));
assert_eq!(moved((0, 1), &[(page, (99, 100))]), (400, 200));
assert_eq!(moved((1, 100), &[(page, (99, 100))]), (404, 200));
assert_eq!(moved((-1, 100), &[(page, (1, 1))]), (400, 200));
assert_eq!(moved((0, 1), &[(page, (2, 1))]), (404, 204));
assert_eq!(moved((-1, 100), &[(u(3000), (2, 1))]), (404, 200));
}
#[test]
fn holds_no_stretch_factors_without_denominators_or_beyond_its_heights() {
use super::STRETCH_HEIGHTS;
let writer = stepping_writer();
let page = Length::from_units(2000);
assert_eq!(writer.with_stretch_factors((0, 0), &[]), None);
assert_eq!(writer.with_stretch_factors((0, 1), &[(page, (1, 0))]), None);
let many = [(page, (1, 1)); STRETCH_HEIGHTS + 1];
assert_eq!(writer.with_stretch_factors((0, 1), &many), None);
}
#[test]
fn leaves_the_items_of_a_group_where_the_layout_puts_them() {
use super::Item;
let grouped = || {
let mut page = sample_page();
page.items = vec![Item::Group(super::Group::new(page.items))];
page
};
let writer = Writer::new(Length::from_units(10))
.unwrap()
.with_vertical_stretch(1)
.with_glyph_stretch_step(Some(Length::from_units(3)))
.unwrap()
.with_horizontal_offset(WriterOffset::EveryPage(Offset::Share {
share: 2,
bias: 0,
step: 10,
}))
.with_digits(Some(non_zero(5)));
let mut list = DisplayList {
pages: vec![grouped()],
};
writer.finish(&mut list);
assert_eq!(list.pages[0], grouped());
let sample = sample_page();
assert_eq!(list.pages[0].painted(), sample.painted());
}
#[test]
fn places_the_items_of_a_group_of_the_page_as_the_pages_items() {
use super::{Group, GroupClip, Item};
let writer = Writer::new(Length::from_units(10))
.unwrap()
.with_vertical_stretch(1)
.with_glyph_stretch_step(Some(Length::from_units(3)))
.unwrap()
.with_horizontal_offset(WriterOffset::EveryPage(Offset::Share {
share: 2,
bias: 0,
step: 10,
}))
.with_digits(Some(non_zero(5)));
let u = Length::from_units;
let mut plain = DisplayList {
pages: vec![sample_page()],
};
writer.finish(&mut plain);
let mut page = sample_page();
let clip = GroupClip::rect(u(0), u(1000), u(500), u(1000));
page.items = vec![Item::Group(Group::of_page(page.items, clip))];
let mut grouped = DisplayList { pages: vec![page] };
writer.finish(&mut grouped);
let placed = DisplayList {
pages: vec![Page {
items: vec![Item::Group(Group::of_page(
plain.pages[0].items.clone(),
GroupClip::rect(u(0), u(1005), u(500), u(1005)),
))],
..plain.pages.remove(0)
}],
};
assert_eq!(grouped, placed);
}
#[test]
fn moves_the_clip_of_a_table_cell_with_the_offsets_of_the_cells_items() {
use super::{Group, GroupClip, Item, Rect, Rgb};
let offset = WriterOffset::EveryPage(Offset::Share {
share: 2,
bias: 0,
step: 10,
});
let writer = Writer::new(Length::from_units(10))
.unwrap()
.with_horizontal_offset(offset)
.with_vertical_offset(offset);
let u = Length::from_units;
let (x, y, width, height) = (u(300), u(900), u(200), u(400));
let fill = Item::Rect(Rect {
x,
y,
width,
height,
color: Rgb::BLACK,
});
let clip = GroupClip::rect(x, y, width, height);
let page = |group: fn(Vec<Item>, GroupClip) -> Group| Page {
width: u(1000),
height: u(2000),
items: vec![Item::Group(group(vec![fill.clone()], clip.clone()))],
..sample_page()
};
let mut list = DisplayList {
pages: vec![page(Group::of_cell), page(Group::of_page)],
};
writer.finish(&mut list);
let group = |page: &Page| match &page.items[0] {
Item::Group(group) => group.clone(),
_ => unreachable!("the page holds one group"),
};
let cell = group(&list.pages[0]);
let Item::Rect(moved) = &cell.items[0] else {
unreachable!("the group holds one rectangle")
};
assert_ne!((moved.x, moved.y), (x, y));
assert_eq!(
cell.clip,
Some(GroupClip::rect(moved.x, moved.y, moved.width, moved.height))
);
assert_eq!(group(&list.pages[1]).clip, Some(clip));
}
#[test]
fn moves_every_point_of_a_group_of_points_as_a_rectangles_edges() {
use super::{Group, GroupClip, GroupPlaces, Item, PathItem, Rect, Rgb};
let offset = WriterOffset::EveryPage(Offset::Share {
share: 2,
bias: 0,
step: 10,
});
let writer = Writer::new(Length::from_units(10))
.unwrap()
.with_horizontal_offset(offset)
.with_vertical_offset(offset);
let u = Length::from_units;
let (x, y, width, height) = (u(300), u(900), u(200), u(400));
let fill = Item::Rect(Rect {
x,
y,
width,
height,
color: Rgb::BLACK,
});
let outline = |x, y, width, height| GroupClip::rect(x, y, width, height).commands;
let path = Item::Path(PathItem {
commands: outline(x, y, width, height),
color: Rgb::BLACK,
fill_rule: super::FillRule::NonZero,
});
let page = |places| Page {
width: u(1000),
height: u(2000),
items: vec![Item::Group(Group {
items: vec![fill.clone(), path.clone()],
clip: Some(GroupClip::rect(x, y, width, height)),
places,
})],
..sample_page()
};
let mut list = DisplayList {
pages: vec![page(GroupPlaces::Points), page(GroupPlaces::Page)],
};
writer.finish(&mut list);
let items = |page: &Page| match &page.items[0] {
Item::Group(group) => (group.items.clone(), group.clip.clone()),
_ => unreachable!("the page holds one group"),
};
let (moved, clip) = items(&list.pages[0]);
let [Item::Rect(rect), Item::Path(drawn)] = moved.as_slice() else {
unreachable!("the group holds a rectangle and a path")
};
assert_ne!((rect.x, rect.y), (x, y));
let edges = outline(rect.x, rect.y, rect.width, rect.height);
assert_eq!(drawn.commands, edges);
assert_eq!(clip.map(|clip| clip.commands), Some(edges));
let (kept, _) = items(&list.pages[1]);
assert_eq!(kept[1], path);
}
const LETTER_ACROSS: Offset = Offset::Page {
steps: (472_515, 100_000),
parts: 16,
per_inch: 3_000,
product: super::OffsetProduct::Binary32 { dots_per_inch: 600 },
};
#[test]
fn writes_an_edge_between_two_dots_by_the_entry_at_its_own_place() {
let side = 612 * 25_400;
let between = 4_700 * 3_048 + 122;
assert_eq!(LETTER_ACROSS.written_place(between, side), 14_328_648);
assert_eq!(between + LETTER_ACROSS.of(between, side), 14_328_160);
let dot = 4_800 * 3_048;
assert_eq!(LETTER_ACROSS.written_place(dot, side), 14_632_838);
assert_eq!(dot + LETTER_ACROSS.of(dot, side), 14_632_838);
let share = Offset::Share {
share: 2,
bias: 0,
step: 10,
};
assert_eq!(
share.written_place(between, side),
between + share.of(between, side)
);
}
fn drawn_rectangles(places: super::GroupPlaces) -> Vec<super::Item> {
use super::{Group, Item, Rect};
let u = Length::from_units;
let writer = Writer::new(u(1))
.unwrap()
.with_horizontal_offset(WriterOffset::EveryPage(LETTER_ACROSS));
let rect = Rect {
x: u(4_700 * 3_048 + 122),
y: u(9_000_000),
width: u(3_048),
height: u(50_000),
color: Rgb::BLACK,
};
let wide = Rect {
width: u(4 * 3_048),
..rect.clone()
};
let mut list = DisplayList {
pages: vec![Page {
width: u(612 * 25_400),
height: u(792 * 25_400),
items: vec![Item::Group(Group {
items: vec![Item::Rect(rect), Item::Rect(wide)],
clip: None,
places,
})],
..sample_page()
}],
};
writer.finish(&mut list);
match &list.pages[0].items[0] {
Item::Group(group) => group.items.clone(),
_ => unreachable!("the page holds one group"),
}
}
#[test]
fn draws_a_stroked_rectangle_and_then_its_stroke_after_placing_its_edges() {
use super::{FillRule, GroupPlaces, Item, PathCommand, Point};
let u = Length::from_units;
let stroked = drawn_rectangles(GroupPlaces::Stroked { width: u(3_556) });
let [Item::Rect(placed), Item::Path(outline), ..] = stroked.as_slice() else {
unreachable!("each rectangle and then its stroke's outline")
};
assert_eq!(placed.x, u(14_328_648));
assert_eq!(placed.width, u(14_331_696 - 14_328_648));
assert_eq!((placed.y, placed.height), (u(9_000_000), u(50_000)));
assert_eq!(
(outline.color, outline.fill_rule),
(Rgb::BLACK, FillRule::NonZero)
);
let (right, below) = (u(14_331_696), u(9_050_000) + u(1_778));
let at = |x, y| Point { x, y };
assert_eq!(
outline.commands[..3],
[
PathCommand::MoveTo(at(u(14_328_648), below)),
PathCommand::LineTo(at(right, below)),
PathCommand::CubicTo(
at(right + u(982), below),
at(right + u(1_778), u(9_050_000) + u(982)),
at(right + u(1_778), u(9_050_000)),
),
]
);
assert_eq!(outline.commands.len(), 10);
let points = drawn_rectangles(GroupPlaces::Points);
let [Item::Rect(nearest), Item::Rect(_)] = points.as_slice() else {
unreachable!("a group of points draws the rectangles alone")
};
assert_eq!(nearest.x, u(14_328_160));
}
#[test]
fn draws_the_inner_outline_of_the_stroke_of_a_rectangle_wider_than_the_stroke() {
use super::{GroupPlaces, Item, PathCommand, Point};
let u = Length::from_units;
let stroked = drawn_rectangles(GroupPlaces::Stroked { width: u(3_556) });
let [_, _, Item::Rect(wide), Item::Path(outline)] = stroked.as_slice() else {
unreachable!("each rectangle and then its stroke's outline")
};
let (left, right, bottom) = (wide.x, wide.x + wide.width, u(9_050_000));
assert_eq!(left, u(14_328_648));
let at = |x, y| Point { x, y };
assert_eq!(
outline.commands[10..13],
[
PathCommand::MoveTo(at(left, bottom - u(1_778))),
PathCommand::LineTo(at(left + u(1_778), bottom)),
PathCommand::LineTo(at(left + u(1_778), u(9_000_000))),
]
);
assert_eq!(
outline.commands[17],
PathCommand::LineTo(at(right, bottom - u(1_778)))
);
assert_eq!(outline.commands.len(), 20);
}
#[test]
fn writes_every_point_of_a_group_of_points_with_the_writers_digits() {
use super::{Group, GroupPlaces, Item, PathCommand, PathItem, Point, Rgb};
let u = Length::from_units;
let point = Point {
x: u(3_135_800),
y: u(17_783_134),
};
let height = u(792 * 25_400);
let page = Page {
width: u(612 * 25_400),
height,
items: vec![Item::Group(Group {
items: vec![Item::Path(PathItem {
commands: vec![PathCommand::MoveTo(point), PathCommand::Close],
color: Rgb::BLACK,
fill_rule: super::FillRule::NonZero,
})],
clip: None,
places: GroupPlaces::Points,
})],
..sample_page()
};
let written = |steps: Option<u32>| {
let writer = Writer::new(Length::from_units(1))
.unwrap()
.with_digits(Some(non_zero(5)))
.with_rectangle_steps(steps.map(non_zero));
let mut list = DisplayList {
pages: vec![page.clone()],
};
writer.finish(&mut list);
match &list.pages[0].items[0] {
Item::Group(group) => match &group.items[0] {
Item::Path(path) => path.commands[0].points().next(),
_ => None,
},
_ => None,
}
};
let plain = written(None).unwrap();
assert_eq!(plain.x, u(3_135_884));
assert_eq!(plain.y, super::written_y(height, point.y, (5, 0)));
assert_eq!(written(Some(3_000)), Some(plain));
}
fn stretched() -> Page {
let writer = Writer::new(Length::from_units(10))
.unwrap()
.with_vertical_stretch(1);
let mut list = DisplayList {
pages: vec![sample_page()],
};
writer.finish(&mut list);
list.pages.remove(0)
}
fn sample_page() -> Page {
use super::{Clip, Glyph, GlyphRun, ImageItem, Item, PathCommand, PathItem, Point, Rect};
let u = Length::from_units;
let glyph = Glyph {
id: 1,
x: u(500),
y: u(400),
text_start: 0,
text_end: 1,
};
let items = vec![
Item::Glyphs(GlyphRun {
font: f_office_fonts::FontId::from_index(0),
size: u(120),
color: super::Rgb::default(),
text: "a".to_owned(),
glyphs: vec![glyph],
outline: None,
filled: true,
effect: false,
turn: None,
}),
Item::Rect(Rect {
x: u(100),
y: u(200),
width: u(300),
height: u(400),
color: super::Rgb::default(),
}),
Item::Path(PathItem {
commands: vec![PathCommand::MoveTo(Point {
x: u(1000),
y: u(2000),
})],
color: super::Rgb::default(),
fill_rule: super::FillRule::NonZero,
}),
Item::Image(ImageItem {
x: u(0),
y: u(0),
width: u(1000),
height: u(2000),
clip: Some(Clip {
x: u(100),
y: u(200),
width: u(100),
height: u(200),
}),
turn: None,
image: Image::new(vec![0]),
}),
];
Page {
width: u(1000),
height: u(2000),
orientation: Orientation::Portrait,
items,
}
}
#[test]
fn detects_formats_from_their_signatures() {
let mut emf = vec![1, 0, 0, 0];
emf.resize(40, 0);
emf.extend_from_slice(b" EMF");
let cases: [(&[u8], ImageFormat); 12] = [
(b"\x89PNG\r\n\x1a\nrest", ImageFormat::Png),
(&[0xFF, 0xD8, 0xFF, 0xE0], ImageFormat::Jpeg),
(b"GIF89a", ImageFormat::Gif),
(b"GIF87a", ImageFormat::Gif),
(b"BM", ImageFormat::Bmp),
(b"II*\0", ImageFormat::Tiff),
(b"MM\0*", ImageFormat::Tiff),
(&emf, ImageFormat::Emf),
(&[0xD7, 0xCD, 0xC6, 0x9A], ImageFormat::Wmf),
(&[1, 0, 9, 0], ImageFormat::Wmf),
(&[2, 0, 9, 0], ImageFormat::Wmf),
(&[1, 0, 0, 0], ImageFormat::Unknown),
];
for (data, format) in cases {
assert_eq!(ImageFormat::detect(data), format, "{data:?}");
}
assert_eq!(ImageFormat::detect(&emf[..43]), ImageFormat::Unknown);
assert_eq!(ImageFormat::detect(b""), ImageFormat::Unknown);
}
#[test]
fn shares_the_bytes_of_an_image() {
let image = Image::new(vec![0xFF, 0xD8, 0xFF]);
assert_eq!(image.format, ImageFormat::Jpeg);
let copy = image.clone();
assert!(Arc::ptr_eq(
image.data.inline_bytes().unwrap(),
copy.data.inline_bytes().unwrap()
));
}
#[test]
fn shows_the_part_of_a_clip_that_lies_on_the_image() {
let length = Length::from_units;
let clip = |x, y, width, height| super::Clip {
x: length(x),
y: length(y),
width: length(width),
height: length(height),
};
let item = |clip| super::ImageItem {
x: length(100),
y: length(200),
width: length(80),
height: length(40),
clip,
turn: None,
image: Image::new(vec![0xFF, 0xD8, 0xFF]),
};
assert_eq!(
item(Some(clip(100, 200, 100, 30))).shown(),
Some(clip(100, 200, 80, 30))
);
assert_eq!(
item(Some(clip(90, 190, 100, 60))).shown(),
Some(clip(100, 200, 80, 40))
);
assert_eq!(item(Some(clip(180, 200, 10, 40))).shown(), None);
assert_eq!(item(None).shown(), None);
}
#[test]
fn first_place_is_the_first_place_that_map_places_maps() {
use super::{Group, GroupPlaces, Item, Rect};
let rect = |y| {
Item::Rect(Rect {
x: Length::from_units(1),
y: Length::from_units(y),
width: Length::from_units(2),
height: Length::from_units(3),
color: Rgb::BLACK,
})
};
let group = |items| {
Item::Group(Group {
items,
clip: None,
places: GroupPlaces::Own,
})
};
let empty = group(Vec::new());
let nested = group(vec![empty.clone(), rect(5), rect(7)]);
for item in [rect(4), empty, nested] {
let mut mapped = None;
item.clone().map_places(
|place| {
mapped.get_or_insert(place);
place
},
|length| length,
);
assert_eq!(item.first_place(), mapped);
}
}
fn four_stops() -> super::GradientItem {
use super::{FillRule, GradientItem, GradientStop, Point};
let origin = Point {
x: Length::ZERO,
y: Length::ZERO,
};
let stops = vec![
GradientStop::new(100_000, Rgb::BLACK),
GradientStop::new(
500_000,
Rgb {
r: 201,
g: 10,
b: 0,
},
),
GradientStop::new(500_000, Rgb { r: 0, g: 0, b: 255 }),
GradientStop::new(GradientStop::END, Rgb::WHITE),
];
GradientItem::new(Vec::new(), FillRule::NonZero, (origin, origin), stops)
}
#[test]
fn gives_the_color_of_a_gradient_between_its_stops_and_beyond_its_ends() {
let gradient = four_stops();
assert_eq!(gradient.color_at(-5), Rgb::BLACK);
assert_eq!(gradient.color_at(50_000), Rgb::BLACK);
assert_eq!(gradient.color_at(2_000_000), Rgb::WHITE);
assert_eq!(gradient.color_at(300_000), Rgb { r: 101, g: 5, b: 0 });
assert_eq!(
gradient.color_at(750_000),
Rgb {
r: 128,
g: 128,
b: 255
}
);
}
#[test]
fn gives_the_later_color_where_two_stops_meet_and_black_without_stops() {
let gradient = four_stops();
assert_eq!(
gradient.color_at(499_999),
Rgb {
r: 201,
g: 10,
b: 0
}
);
assert_eq!(gradient.color_at(500_000), Rgb { r: 0, g: 0, b: 255 });
let mut empty = gradient;
empty.stops.clear();
assert_eq!(empty.color_at(0), Rgb::BLACK);
}
#[test]
fn moves_the_axis_of_a_gradient_with_its_outline() {
use super::{FillRule, GradientItem, Item, PathCommand, Point};
let at = |x, y| Point {
x: Length::from_units(x),
y: Length::from_units(y),
};
let mut item = Item::Gradient(GradientItem::new(
vec![PathCommand::MoveTo(at(1, 2)), PathCommand::LineTo(at(3, 4))],
FillRule::NonZero,
(at(0, 0), at(10, 0)),
Vec::new(),
));
item.map_places(
|p| Point {
x: p.x + Length::from_units(100),
y: p.y,
},
|length| length,
);
let Item::Gradient(moved) = &item else {
panic!("not a gradient");
};
assert_eq!(moved.commands[0], PathCommand::MoveTo(at(101, 2)));
assert_eq!((moved.start, moved.end), (at(100, 0), at(110, 0)));
assert_eq!(item.first_place(), Some(at(101, 2)));
}
}