use laminapdf_model::Matrix;
use laminapdf_syntax::Rotation;
use crate::appearance::PageAppearance;
use crate::error::RenderError;
pub const BYTES_PER_PIXEL: usize = 4;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RenderLimits {
pub max_render_pixels: u64,
pub max_render_side: u32,
pub max_input_bytes: u64,
}
impl Default for RenderLimits {
fn default() -> Self {
Self {
max_render_pixels: 16_777_216,
max_render_side: 16_384,
max_input_bytes: 1 << 30,
}
}
}
#[derive(Debug, Clone, Default)]
pub struct RenderOpenOptions {
password: Option<String>,
limits: RenderLimits,
}
impl RenderOpenOptions {
#[must_use]
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn with_password(mut self, password: &str) -> Self {
self.password = Some(password.to_owned());
self
}
#[must_use]
pub const fn with_limits(mut self, limits: RenderLimits) -> Self {
self.limits = limits;
self
}
#[must_use]
pub fn password(&self) -> Option<&str> {
self.password.as_deref()
}
#[must_use]
pub const fn limits(&self) -> &RenderLimits {
&self.limits
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct PixelRect {
pub x: u32,
pub y: u32,
pub width: u32,
pub height: u32,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[expect(
clippy::struct_excessive_bools,
reason = "independent switches, each a PDFium render flag"
)]
pub struct RenderFlags {
pub annotations: bool,
pub form_widgets: bool,
pub print: bool,
pub grayscale: bool,
}
impl Default for RenderFlags {
fn default() -> Self {
Self {
annotations: true,
form_widgets: true,
print: false,
grayscale: false,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Rgba8 {
pub r: u8,
pub g: u8,
pub b: u8,
pub a: u8,
}
impl Rgba8 {
pub const WHITE: Self = Self {
r: 255,
g: 255,
b: 255,
a: 255,
};
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct RenderRequest {
pub page: u32,
pub scale: f32,
pub clip: Option<PixelRect>,
pub rotation: Rotation,
pub flags: RenderFlags,
pub background: Option<Rgba8>,
pub appearance: PageAppearance,
}
impl RenderRequest {
#[must_use]
pub fn page(page: u32, scale: f32) -> Self {
Self {
page,
scale,
clip: None,
rotation: Rotation::None,
flags: RenderFlags::default(),
background: Some(Rgba8::WHITE),
appearance: PageAppearance::Original,
}
}
#[must_use]
pub const fn with_clip(mut self, clip: PixelRect) -> Self {
self.clip = Some(clip);
self
}
#[must_use]
pub const fn with_rotation(mut self, rotation: Rotation) -> Self {
self.rotation = rotation;
self
}
#[must_use]
pub const fn with_flags(mut self, flags: RenderFlags) -> Self {
self.flags = flags;
self
}
#[must_use]
pub const fn with_background(mut self, background: Option<Rgba8>) -> Self {
self.background = background;
self
}
#[must_use]
pub const fn with_appearance(mut self, appearance: PageAppearance) -> Self {
self.appearance = appearance;
self
}
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct RenderPage {
pub width: f32,
pub height: f32,
pub rotate: Rotation,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct TilePlan {
pub page_width: u32,
pub page_height: u32,
pub tile: PixelRect,
}
impl TilePlan {
pub fn new(page: &RenderPage, request: &RenderRequest, limits: &RenderLimits) -> Result<Self, RenderError> {
let scale = f64::from(request.scale);
if !scale.is_finite() || scale <= 0.0 {
return Err(RenderError::InvalidRequest {
what: "scale must be finite and positive",
});
}
if !(page.width.is_finite() && page.height.is_finite() && page.width > 0.0 && page.height > 0.0) {
return Err(RenderError::InvalidRequest {
what: "the page has no drawable area",
});
}
let (w, h) = if request.rotation.is_quarter_turn() {
(page.height, page.width)
} else {
(page.width, page.height)
};
let page_width = pixels(f64::from(w) * scale)?;
let page_height = pixels(f64::from(h) * scale)?;
let tile = request.clip.unwrap_or(PixelRect {
x: 0,
y: 0,
width: page_width,
height: page_height,
});
if tile.width == 0 || tile.height == 0 {
return Err(RenderError::InvalidRequest {
what: "the tile is empty",
});
}
let right = u64::from(tile.x) + u64::from(tile.width);
let bottom = u64::from(tile.y) + u64::from(tile.height);
if right > u64::from(page_width) || bottom > u64::from(page_height) {
return Err(RenderError::InvalidRequest {
what: "the tile extends past the page",
});
}
let (tw, th) = (u64::from(tile.width), u64::from(tile.height));
let side = u64::from(limits.max_render_side);
if tw > side || th > side {
return Err(RenderError::TooLarge {
width: tw,
height: th,
limit: side,
unit: "pixels per side",
});
}
if tw * th > limits.max_render_pixels {
return Err(RenderError::TooLarge {
width: tw,
height: th,
limit: limits.max_render_pixels,
unit: "pixels",
});
}
Ok(Self {
page_width,
page_height,
tile,
})
}
#[must_use]
pub fn byte_len(&self) -> usize {
usize::try_from(u64::from(self.tile.width) * u64::from(self.tile.height) * BYTES_PER_PIXEL as u64)
.unwrap_or(usize::MAX)
}
#[must_use]
pub fn page_to_tile(&self, page: &RenderPage, rotation: Rotation) -> Matrix {
let (w0, h0) = if rotation.is_quarter_turn() {
(f64::from(self.page_height), f64::from(self.page_width))
} else {
(f64::from(self.page_width), f64::from(self.page_height))
};
let (sx, sy) = (w0 / f64::from(page.width), h0 / f64::from(page.height));
let (tx, ty) = (f64::from(self.tile.x), f64::from(self.tile.y));
Matrix::new(match rotation {
Rotation::None => [sx, 0.0, 0.0, sy, -tx, -ty],
Rotation::Clockwise90 => [0.0, sx, -sy, 0.0, h0 - tx, -ty],
Rotation::Half => [-sx, 0.0, 0.0, -sy, w0 - tx, h0 - ty],
Rotation::Clockwise270 => [0.0, -sx, sy, 0.0, -tx, w0 - ty],
})
}
pub fn check_buffer(&self, out: &[u8]) -> Result<(), RenderError> {
let expected = self.byte_len();
if out.len() == expected {
Ok(())
} else {
Err(RenderError::BufferSize {
expected,
actual: out.len(),
})
}
}
}
fn pixels(v: f64) -> Result<u32, RenderError> {
let v = v.floor().max(1.0);
if v > f64::from(i32::MAX) {
return Err(RenderError::InvalidRequest {
what: "the page is too large to address at this scale",
});
}
#[expect(
clippy::cast_possible_truncation,
clippy::cast_sign_loss,
reason = "range checked above"
)]
Ok(v as u32)
}
#[cfg(test)]
mod tests {
use super::{PixelRect, RenderLimits, RenderPage, RenderRequest, Rotation, TilePlan};
use crate::RenderError;
const LETTER: RenderPage = RenderPage {
width: 612.0,
height: 792.0,
rotate: Rotation::None,
};
mod tile_plan {
use super::*;
#[test]
fn whole_page_floors_points_times_scale() {
let plan = TilePlan::new(&LETTER, &RenderRequest::page(0, 96.0 / 72.0), &RenderLimits::default()).unwrap();
assert_eq!((plan.page_width, plan.page_height), (816, 1056));
assert_eq!(plan.byte_len(), 816 * 1056 * 4);
}
#[test]
fn quarter_turn_swaps_the_page_size() {
let req = RenderRequest::page(0, 1.0).with_rotation(Rotation::Clockwise90);
let plan = TilePlan::new(&LETTER, &req, &RenderLimits::default()).unwrap();
assert_eq!((plan.page_width, plan.page_height), (792, 612));
}
#[test]
fn rejects_a_non_finite_or_non_positive_scale() {
for scale in [0.0, -1.0, f32::NAN, f32::INFINITY] {
let err = TilePlan::new(&LETTER, &RenderRequest::page(0, scale), &RenderLimits::default()).unwrap_err();
assert_eq!(err.code(), "invalid-argument", "{scale}");
}
}
#[test]
fn rejects_a_tile_past_the_page() {
let req = RenderRequest::page(0, 1.0).with_clip(PixelRect {
x: 600,
y: 0,
width: 13,
height: 10,
});
let err = TilePlan::new(&LETTER, &req, &RenderLimits::default()).unwrap_err();
assert_eq!(
err,
RenderError::InvalidRequest {
what: "the tile extends past the page"
}
);
}
#[test]
fn rejects_a_page_without_area() {
for (width, height) in [(0.0, 792.0), (612.0, -1.0), (f32::NAN, 792.0)] {
let page = RenderPage {
width,
height,
rotate: Rotation::None,
};
let err = TilePlan::new(&page, &RenderRequest::page(0, 1.0), &RenderLimits::default()).unwrap_err();
assert_eq!(err.code(), "invalid-argument", "{width}×{height}");
}
}
#[test]
fn rejects_an_empty_tile() {
let req = RenderRequest::page(0, 1.0).with_clip(PixelRect {
x: 0,
y: 0,
width: 0,
height: 10,
});
assert_eq!(
TilePlan::new(&LETTER, &req, &RenderLimits::default())
.unwrap_err()
.code(),
"invalid-argument"
);
}
#[test]
fn refuses_a_tile_over_the_pixel_limit_before_allocating() {
let err = TilePlan::new(&LETTER, &RenderRequest::page(0, 1000.0), &RenderLimits::default()).unwrap_err();
assert_eq!(err.code(), "render-too-large");
}
#[test]
fn allows_a_small_tile_of_a_huge_zoom() {
let req = RenderRequest::page(0, 1000.0).with_clip(PixelRect {
x: 300_000,
y: 400_000,
width: 512,
height: 512,
});
let plan = TilePlan::new(&LETTER, &req, &RenderLimits::default()).unwrap();
assert_eq!(plan.byte_len(), 512 * 512 * 4);
}
#[test]
fn refuses_a_page_too_large_to_address() {
let err = TilePlan::new(&LETTER, &RenderRequest::page(0, 1e9), &RenderLimits::default()).unwrap_err();
assert_eq!(err.code(), "invalid-argument");
}
#[test]
fn page_to_tile_maps_the_corners() {
let page = RenderPage {
width: 100.0,
height: 50.0,
rotate: Rotation::None,
};
let req = RenderRequest::page(0, 2.0);
let plan = TilePlan::new(&page, &req, &RenderLimits::default()).unwrap();
assert_eq!(
plan.page_to_tile(&page, Rotation::None).apply(100.0, 50.0),
(200.0, 100.0)
);
let turned = req.with_rotation(Rotation::Clockwise90);
let plan = TilePlan::new(&page, &turned, &RenderLimits::default()).unwrap();
assert_eq!(
plan.page_to_tile(&page, Rotation::Clockwise90).apply(0.0, 0.0),
(100.0, 0.0)
);
let shifted = req.with_clip(PixelRect {
x: 10,
y: 20,
width: 5,
height: 5,
});
let plan = TilePlan::new(&page, &shifted, &RenderLimits::default()).unwrap();
assert_eq!(plan.page_to_tile(&page, Rotation::None).apply(5.0, 10.0), (0.0, 0.0));
}
#[test]
fn check_buffer_wants_exactly_the_tile_bytes() {
let plan = TilePlan::new(&LETTER, &RenderRequest::page(0, 0.1), &RenderLimits::default()).unwrap();
assert!(plan.check_buffer(&vec![0; plan.byte_len()]).is_ok());
assert_eq!(plan.check_buffer(&[0; 3]).unwrap_err().code(), "invalid-argument");
}
}
}