1use laminapdf_model::Matrix;
5use laminapdf_syntax::Rotation;
6
7use crate::appearance::PageAppearance;
8use crate::error::RenderError;
9
10pub const BYTES_PER_PIXEL: usize = 4;
15
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub struct RenderLimits {
21 pub max_render_pixels: u64,
23 pub max_render_side: u32,
25 pub max_input_bytes: u64,
28}
29
30impl Default for RenderLimits {
31 fn default() -> Self {
32 Self {
33 max_render_pixels: 16_777_216,
34 max_render_side: 16_384,
35 max_input_bytes: 1 << 30,
36 }
37 }
38}
39
40#[derive(Debug, Clone, Default)]
44pub struct RenderOpenOptions {
45 password: Option<String>,
46 limits: RenderLimits,
47}
48
49impl RenderOpenOptions {
50 #[must_use]
54 pub fn new() -> Self {
55 Self::default()
56 }
57
58 #[must_use]
63 pub fn with_password(mut self, password: &str) -> Self {
64 self.password = Some(password.to_owned());
65 self
66 }
67
68 #[must_use]
72 pub const fn with_limits(mut self, limits: RenderLimits) -> Self {
73 self.limits = limits;
74 self
75 }
76
77 #[must_use]
81 pub fn password(&self) -> Option<&str> {
82 self.password.as_deref()
83 }
84
85 #[must_use]
89 pub const fn limits(&self) -> &RenderLimits {
90 &self.limits
91 }
92}
93
94#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
99pub struct PixelRect {
100 pub x: u32,
102 pub y: u32,
104 pub width: u32,
106 pub height: u32,
108}
109
110#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
114#[expect(
115 clippy::struct_excessive_bools,
116 reason = "independent switches, each a PDFium render flag"
117)]
118pub struct RenderFlags {
119 pub annotations: bool,
121 pub form_widgets: bool,
124 pub print: bool,
126 pub grayscale: bool,
128}
129
130impl Default for RenderFlags {
131 fn default() -> Self {
132 Self {
133 annotations: true,
134 form_widgets: true,
135 print: false,
136 grayscale: false,
137 }
138 }
139}
140
141#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
145pub struct Rgba8 {
146 pub r: u8,
148 pub g: u8,
150 pub b: u8,
152 pub a: u8,
154}
155
156impl Rgba8 {
157 pub const WHITE: Self = Self {
161 r: 255,
162 g: 255,
163 b: 255,
164 a: 255,
165 };
166}
167
168#[derive(Debug, Clone, Copy, PartialEq)]
173pub struct RenderRequest {
174 pub page: u32,
176 pub scale: f32,
178 pub clip: Option<PixelRect>,
180 pub rotation: Rotation,
182 pub flags: RenderFlags,
184 pub background: Option<Rgba8>,
186 pub appearance: PageAppearance,
188}
189
190impl RenderRequest {
191 #[must_use]
195 pub fn page(page: u32, scale: f32) -> Self {
196 Self {
197 page,
198 scale,
199 clip: None,
200 rotation: Rotation::None,
201 flags: RenderFlags::default(),
202 background: Some(Rgba8::WHITE),
203 appearance: PageAppearance::Original,
204 }
205 }
206
207 #[must_use]
211 pub const fn with_clip(mut self, clip: PixelRect) -> Self {
212 self.clip = Some(clip);
213 self
214 }
215
216 #[must_use]
220 pub const fn with_rotation(mut self, rotation: Rotation) -> Self {
221 self.rotation = rotation;
222 self
223 }
224
225 #[must_use]
229 pub const fn with_flags(mut self, flags: RenderFlags) -> Self {
230 self.flags = flags;
231 self
232 }
233
234 #[must_use]
238 pub const fn with_background(mut self, background: Option<Rgba8>) -> Self {
239 self.background = background;
240 self
241 }
242
243 #[must_use]
247 pub const fn with_appearance(mut self, appearance: PageAppearance) -> Self {
248 self.appearance = appearance;
249 self
250 }
251}
252
253#[derive(Debug, Clone, Copy, PartialEq)]
257pub struct RenderPage {
258 pub width: f32,
260 pub height: f32,
262 pub rotate: Rotation,
264}
265
266#[derive(Debug, Clone, Copy, PartialEq, Eq)]
271pub struct TilePlan {
272 pub page_width: u32,
274 pub page_height: u32,
276 pub tile: PixelRect,
278}
279
280impl TilePlan {
281 pub fn new(page: &RenderPage, request: &RenderRequest, limits: &RenderLimits) -> Result<Self, RenderError> {
292 let scale = f64::from(request.scale);
293 if !scale.is_finite() || scale <= 0.0 {
294 return Err(RenderError::InvalidRequest {
295 what: "scale must be finite and positive",
296 });
297 }
298 if !(page.width.is_finite() && page.height.is_finite() && page.width > 0.0 && page.height > 0.0) {
299 return Err(RenderError::InvalidRequest {
300 what: "the page has no drawable area",
301 });
302 }
303 let (w, h) = if request.rotation.is_quarter_turn() {
304 (page.height, page.width)
305 } else {
306 (page.width, page.height)
307 };
308 let page_width = pixels(f64::from(w) * scale)?;
309 let page_height = pixels(f64::from(h) * scale)?;
310 let tile = request.clip.unwrap_or(PixelRect {
311 x: 0,
312 y: 0,
313 width: page_width,
314 height: page_height,
315 });
316 if tile.width == 0 || tile.height == 0 {
317 return Err(RenderError::InvalidRequest {
318 what: "the tile is empty",
319 });
320 }
321 let right = u64::from(tile.x) + u64::from(tile.width);
322 let bottom = u64::from(tile.y) + u64::from(tile.height);
323 if right > u64::from(page_width) || bottom > u64::from(page_height) {
324 return Err(RenderError::InvalidRequest {
325 what: "the tile extends past the page",
326 });
327 }
328 let (tw, th) = (u64::from(tile.width), u64::from(tile.height));
329 let side = u64::from(limits.max_render_side);
330 if tw > side || th > side {
331 return Err(RenderError::TooLarge {
332 width: tw,
333 height: th,
334 limit: side,
335 unit: "pixels per side",
336 });
337 }
338 if tw * th > limits.max_render_pixels {
339 return Err(RenderError::TooLarge {
340 width: tw,
341 height: th,
342 limit: limits.max_render_pixels,
343 unit: "pixels",
344 });
345 }
346 Ok(Self {
347 page_width,
348 page_height,
349 tile,
350 })
351 }
352
353 #[must_use]
357 pub fn byte_len(&self) -> usize {
358 usize::try_from(u64::from(self.tile.width) * u64::from(self.tile.height) * BYTES_PER_PIXEL as u64)
361 .unwrap_or(usize::MAX)
362 }
363
364 #[must_use]
371 pub fn page_to_tile(&self, page: &RenderPage, rotation: Rotation) -> Matrix {
372 let (w0, h0) = if rotation.is_quarter_turn() {
374 (f64::from(self.page_height), f64::from(self.page_width))
375 } else {
376 (f64::from(self.page_width), f64::from(self.page_height))
377 };
378 let (sx, sy) = (w0 / f64::from(page.width), h0 / f64::from(page.height));
379 let (tx, ty) = (f64::from(self.tile.x), f64::from(self.tile.y));
380 Matrix::new(match rotation {
382 Rotation::None => [sx, 0.0, 0.0, sy, -tx, -ty],
383 Rotation::Clockwise90 => [0.0, sx, -sy, 0.0, h0 - tx, -ty],
384 Rotation::Half => [-sx, 0.0, 0.0, -sy, w0 - tx, h0 - ty],
385 Rotation::Clockwise270 => [0.0, -sx, sy, 0.0, -tx, w0 - ty],
386 })
387 }
388
389 pub fn check_buffer(&self, out: &[u8]) -> Result<(), RenderError> {
396 let expected = self.byte_len();
397 if out.len() == expected {
398 Ok(())
399 } else {
400 Err(RenderError::BufferSize {
401 expected,
402 actual: out.len(),
403 })
404 }
405 }
406}
407
408fn pixels(v: f64) -> Result<u32, RenderError> {
411 let v = v.floor().max(1.0);
412 if v > f64::from(i32::MAX) {
413 return Err(RenderError::InvalidRequest {
414 what: "the page is too large to address at this scale",
415 });
416 }
417 #[expect(
419 clippy::cast_possible_truncation,
420 clippy::cast_sign_loss,
421 reason = "range checked above"
422 )]
423 Ok(v as u32)
424}
425
426#[cfg(test)]
427mod tests {
428
429 use super::{PixelRect, RenderLimits, RenderPage, RenderRequest, Rotation, TilePlan};
430 use crate::RenderError;
431
432 const LETTER: RenderPage = RenderPage {
433 width: 612.0,
434 height: 792.0,
435 rotate: Rotation::None,
436 };
437
438 mod tile_plan {
439 use super::*;
440
441 #[test]
442 fn whole_page_floors_points_times_scale() {
443 let plan = TilePlan::new(&LETTER, &RenderRequest::page(0, 96.0 / 72.0), &RenderLimits::default()).unwrap();
444 assert_eq!((plan.page_width, plan.page_height), (816, 1056));
445 assert_eq!(plan.byte_len(), 816 * 1056 * 4);
446 }
447
448 #[test]
449 fn quarter_turn_swaps_the_page_size() {
450 let req = RenderRequest::page(0, 1.0).with_rotation(Rotation::Clockwise90);
451 let plan = TilePlan::new(&LETTER, &req, &RenderLimits::default()).unwrap();
452 assert_eq!((plan.page_width, plan.page_height), (792, 612));
453 }
454
455 #[test]
456 fn rejects_a_non_finite_or_non_positive_scale() {
457 for scale in [0.0, -1.0, f32::NAN, f32::INFINITY] {
458 let err = TilePlan::new(&LETTER, &RenderRequest::page(0, scale), &RenderLimits::default()).unwrap_err();
459 assert_eq!(err.code(), "invalid-argument", "{scale}");
460 }
461 }
462
463 #[test]
464 fn rejects_a_tile_past_the_page() {
465 let req = RenderRequest::page(0, 1.0).with_clip(PixelRect {
466 x: 600,
467 y: 0,
468 width: 13,
469 height: 10,
470 });
471 let err = TilePlan::new(&LETTER, &req, &RenderLimits::default()).unwrap_err();
472 assert_eq!(
473 err,
474 RenderError::InvalidRequest {
475 what: "the tile extends past the page"
476 }
477 );
478 }
479
480 #[test]
481 fn rejects_a_page_without_area() {
482 for (width, height) in [(0.0, 792.0), (612.0, -1.0), (f32::NAN, 792.0)] {
483 let page = RenderPage {
484 width,
485 height,
486 rotate: Rotation::None,
487 };
488 let err = TilePlan::new(&page, &RenderRequest::page(0, 1.0), &RenderLimits::default()).unwrap_err();
489 assert_eq!(err.code(), "invalid-argument", "{width}×{height}");
490 }
491 }
492
493 #[test]
494 fn rejects_an_empty_tile() {
495 let req = RenderRequest::page(0, 1.0).with_clip(PixelRect {
496 x: 0,
497 y: 0,
498 width: 0,
499 height: 10,
500 });
501 assert_eq!(
502 TilePlan::new(&LETTER, &req, &RenderLimits::default())
503 .unwrap_err()
504 .code(),
505 "invalid-argument"
506 );
507 }
508
509 #[test]
510 fn refuses_a_tile_over_the_pixel_limit_before_allocating() {
511 let err = TilePlan::new(&LETTER, &RenderRequest::page(0, 1000.0), &RenderLimits::default()).unwrap_err();
513 assert_eq!(err.code(), "render-too-large");
514 }
515
516 #[test]
517 fn allows_a_small_tile_of_a_huge_zoom() {
518 let req = RenderRequest::page(0, 1000.0).with_clip(PixelRect {
519 x: 300_000,
520 y: 400_000,
521 width: 512,
522 height: 512,
523 });
524 let plan = TilePlan::new(&LETTER, &req, &RenderLimits::default()).unwrap();
525 assert_eq!(plan.byte_len(), 512 * 512 * 4);
526 }
527
528 #[test]
529 fn refuses_a_page_too_large_to_address() {
530 let err = TilePlan::new(&LETTER, &RenderRequest::page(0, 1e9), &RenderLimits::default()).unwrap_err();
531 assert_eq!(err.code(), "invalid-argument");
532 }
533
534 #[test]
535 fn page_to_tile_maps_the_corners() {
536 let page = RenderPage {
537 width: 100.0,
538 height: 50.0,
539 rotate: Rotation::None,
540 };
541 let req = RenderRequest::page(0, 2.0);
542 let plan = TilePlan::new(&page, &req, &RenderLimits::default()).unwrap();
543 assert_eq!(
544 plan.page_to_tile(&page, Rotation::None).apply(100.0, 50.0),
545 (200.0, 100.0)
546 );
547 let turned = req.with_rotation(Rotation::Clockwise90);
548 let plan = TilePlan::new(&page, &turned, &RenderLimits::default()).unwrap();
549 assert_eq!(
551 plan.page_to_tile(&page, Rotation::Clockwise90).apply(0.0, 0.0),
552 (100.0, 0.0)
553 );
554 let shifted = req.with_clip(PixelRect {
555 x: 10,
556 y: 20,
557 width: 5,
558 height: 5,
559 });
560 let plan = TilePlan::new(&page, &shifted, &RenderLimits::default()).unwrap();
561 assert_eq!(plan.page_to_tile(&page, Rotation::None).apply(5.0, 10.0), (0.0, 0.0));
562 }
563
564 #[test]
565 fn check_buffer_wants_exactly_the_tile_bytes() {
566 let plan = TilePlan::new(&LETTER, &RenderRequest::page(0, 0.1), &RenderLimits::default()).unwrap();
567 assert!(plan.check_buffer(&vec![0; plan.byte_len()]).is_ok());
568 assert_eq!(plan.check_buffer(&[0; 3]).unwrap_err().code(), "invalid-argument");
569 }
570 }
571}