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]
65 pub fn with_password(mut self, password: &str) -> Self {
66 self.password = Some(password.to_owned());
67 self
68 }
69
70 #[must_use]
74 pub const fn with_limits(mut self, limits: RenderLimits) -> Self {
75 self.limits = limits;
76 self
77 }
78
79 #[must_use]
83 pub fn password(&self) -> Option<&str> {
84 self.password.as_deref()
85 }
86
87 #[must_use]
91 pub const fn limits(&self) -> &RenderLimits {
92 &self.limits
93 }
94}
95
96#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
101pub struct PixelRect {
102 pub x: u32,
104 pub y: u32,
106 pub width: u32,
108 pub height: u32,
110}
111
112#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
116#[expect(
117 clippy::struct_excessive_bools,
118 reason = "independent switches, each a PDFium render flag"
119)]
120pub struct RenderFlags {
121 pub annotations: bool,
123 pub form_widgets: bool,
126 pub print: bool,
128 pub grayscale: bool,
130}
131
132impl Default for RenderFlags {
133 fn default() -> Self {
134 Self {
135 annotations: true,
136 form_widgets: true,
137 print: false,
138 grayscale: false,
139 }
140 }
141}
142
143#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
147pub struct Rgba8 {
148 pub r: u8,
150 pub g: u8,
152 pub b: u8,
154 pub a: u8,
156}
157
158impl Rgba8 {
159 pub const WHITE: Self = Self {
163 r: 255,
164 g: 255,
165 b: 255,
166 a: 255,
167 };
168}
169
170#[derive(Debug, Clone, PartialEq)]
175pub struct RenderRequest {
176 pub page: u32,
178 pub scale: f32,
180 pub clip: Option<PixelRect>,
182 pub rotation: Rotation,
184 pub flags: RenderFlags,
186 pub background: Option<Rgba8>,
188 pub appearance: PageAppearance,
190 pub hidden_annotations: Vec<u32>,
197}
198
199impl RenderRequest {
200 #[must_use]
204 pub fn page(page: u32, scale: f32) -> Self {
205 Self {
206 page,
207 scale,
208 clip: None,
209 rotation: Rotation::None,
210 flags: RenderFlags::default(),
211 background: Some(Rgba8::WHITE),
212 appearance: PageAppearance::Original,
213 hidden_annotations: Vec::new(),
214 }
215 }
216
217 #[must_use]
221 pub const fn with_clip(mut self, clip: PixelRect) -> Self {
222 self.clip = Some(clip);
223 self
224 }
225
226 #[must_use]
230 pub const fn with_rotation(mut self, rotation: Rotation) -> Self {
231 self.rotation = rotation;
232 self
233 }
234
235 #[must_use]
239 pub const fn with_flags(mut self, flags: RenderFlags) -> Self {
240 self.flags = flags;
241 self
242 }
243
244 #[must_use]
248 pub const fn with_background(mut self, background: Option<Rgba8>) -> Self {
249 self.background = background;
250 self
251 }
252
253 #[must_use]
257 pub const fn with_appearance(mut self, appearance: PageAppearance) -> Self {
258 self.appearance = appearance;
259 self
260 }
261
262 #[must_use]
267 pub fn with_hidden_annotations(mut self, places: impl IntoIterator<Item = u32>) -> Self {
268 self.hidden_annotations = places.into_iter().collect();
269 self
270 }
271}
272
273#[derive(Debug, Clone, Copy, PartialEq)]
277pub struct RenderPage {
278 pub width: f32,
280 pub height: f32,
282 pub rotate: Rotation,
284}
285
286#[derive(Debug, Clone, Copy, PartialEq, Eq)]
291pub struct TilePlan {
292 pub page_width: u32,
294 pub page_height: u32,
296 pub tile: PixelRect,
298}
299
300impl TilePlan {
301 pub fn new(page: &RenderPage, request: &RenderRequest, limits: &RenderLimits) -> Result<Self, RenderError> {
312 let scale = f64::from(request.scale);
313 if !scale.is_finite() || scale <= 0.0 {
314 return Err(RenderError::InvalidRequest {
315 what: "scale must be finite and positive",
316 });
317 }
318 if !(page.width.is_finite() && page.height.is_finite() && page.width > 0.0 && page.height > 0.0) {
319 return Err(RenderError::InvalidRequest {
320 what: "the page has no drawable area",
321 });
322 }
323 let (w, h) = if request.rotation.is_quarter_turn() {
324 (page.height, page.width)
325 } else {
326 (page.width, page.height)
327 };
328 let page_width = pixels(f64::from(w) * scale)?;
329 let page_height = pixels(f64::from(h) * scale)?;
330 let tile = request.clip.unwrap_or(PixelRect {
331 x: 0,
332 y: 0,
333 width: page_width,
334 height: page_height,
335 });
336 if tile.width == 0 || tile.height == 0 {
337 return Err(RenderError::InvalidRequest {
338 what: "the tile is empty",
339 });
340 }
341 let right = u64::from(tile.x) + u64::from(tile.width);
342 let bottom = u64::from(tile.y) + u64::from(tile.height);
343 if right > u64::from(page_width) || bottom > u64::from(page_height) {
344 return Err(RenderError::InvalidRequest {
345 what: "the tile extends past the page",
346 });
347 }
348 let (tw, th) = (u64::from(tile.width), u64::from(tile.height));
349 let side = u64::from(limits.max_render_side);
350 if tw > side || th > side {
351 return Err(RenderError::TooLarge {
352 width: tw,
353 height: th,
354 limit: side,
355 unit: "pixels per side",
356 });
357 }
358 if tw * th > limits.max_render_pixels {
359 return Err(RenderError::TooLarge {
360 width: tw,
361 height: th,
362 limit: limits.max_render_pixels,
363 unit: "pixels",
364 });
365 }
366 Ok(Self {
367 page_width,
368 page_height,
369 tile,
370 })
371 }
372
373 #[must_use]
377 pub fn byte_len(&self) -> usize {
378 usize::try_from(u64::from(self.tile.width) * u64::from(self.tile.height) * BYTES_PER_PIXEL as u64)
381 .unwrap_or(usize::MAX)
382 }
383
384 #[must_use]
391 pub fn page_to_tile(&self, page: &RenderPage, rotation: Rotation) -> Matrix {
392 let (w0, h0) = if rotation.is_quarter_turn() {
394 (f64::from(self.page_height), f64::from(self.page_width))
395 } else {
396 (f64::from(self.page_width), f64::from(self.page_height))
397 };
398 let (sx, sy) = (w0 / f64::from(page.width), h0 / f64::from(page.height));
399 let (tx, ty) = (f64::from(self.tile.x), f64::from(self.tile.y));
400 Matrix::new(match rotation {
402 Rotation::None => [sx, 0.0, 0.0, sy, -tx, -ty],
403 Rotation::Clockwise90 => [0.0, sx, -sy, 0.0, h0 - tx, -ty],
404 Rotation::Half => [-sx, 0.0, 0.0, -sy, w0 - tx, h0 - ty],
405 Rotation::Clockwise270 => [0.0, -sx, sy, 0.0, -tx, w0 - ty],
406 })
407 }
408
409 pub fn check_buffer(&self, out: &[u8]) -> Result<(), RenderError> {
416 let expected = self.byte_len();
417 if out.len() == expected {
418 Ok(())
419 } else {
420 Err(RenderError::BufferSize {
421 expected,
422 actual: out.len(),
423 })
424 }
425 }
426}
427
428fn pixels(v: f64) -> Result<u32, RenderError> {
431 let v = v.floor().max(1.0);
432 if v > f64::from(i32::MAX) {
433 return Err(RenderError::InvalidRequest {
434 what: "the page is too large to address at this scale",
435 });
436 }
437 #[expect(
439 clippy::cast_possible_truncation,
440 clippy::cast_sign_loss,
441 reason = "range checked above"
442 )]
443 Ok(v as u32)
444}
445
446#[cfg(test)]
447mod tests {
448
449 use super::{PixelRect, RenderLimits, RenderPage, RenderRequest, Rotation, TilePlan};
450 use crate::RenderError;
451
452 const LETTER: RenderPage = RenderPage {
453 width: 612.0,
454 height: 792.0,
455 rotate: Rotation::None,
456 };
457
458 mod tile_plan {
459 use super::*;
460
461 #[test]
462 fn whole_page_floors_points_times_scale() {
463 let plan = TilePlan::new(&LETTER, &RenderRequest::page(0, 96.0 / 72.0), &RenderLimits::default()).unwrap();
464 assert_eq!((plan.page_width, plan.page_height), (816, 1056));
465 assert_eq!(plan.byte_len(), 816 * 1056 * 4);
466 }
467
468 #[test]
469 fn quarter_turn_swaps_the_page_size() {
470 let req = RenderRequest::page(0, 1.0).with_rotation(Rotation::Clockwise90);
471 let plan = TilePlan::new(&LETTER, &req, &RenderLimits::default()).unwrap();
472 assert_eq!((plan.page_width, plan.page_height), (792, 612));
473 }
474
475 #[test]
476 fn rejects_a_non_finite_or_non_positive_scale() {
477 for scale in [0.0, -1.0, f32::NAN, f32::INFINITY] {
478 let err = TilePlan::new(&LETTER, &RenderRequest::page(0, scale), &RenderLimits::default()).unwrap_err();
479 assert_eq!(err.code(), "invalid-argument", "{scale}");
480 }
481 }
482
483 #[test]
484 fn rejects_a_tile_past_the_page() {
485 let req = RenderRequest::page(0, 1.0).with_clip(PixelRect {
486 x: 600,
487 y: 0,
488 width: 13,
489 height: 10,
490 });
491 let err = TilePlan::new(&LETTER, &req, &RenderLimits::default()).unwrap_err();
492 assert_eq!(
493 err,
494 RenderError::InvalidRequest {
495 what: "the tile extends past the page"
496 }
497 );
498 }
499
500 #[test]
501 fn rejects_a_page_without_area() {
502 for (width, height) in [(0.0, 792.0), (612.0, -1.0), (f32::NAN, 792.0)] {
503 let page = RenderPage {
504 width,
505 height,
506 rotate: Rotation::None,
507 };
508 let err = TilePlan::new(&page, &RenderRequest::page(0, 1.0), &RenderLimits::default()).unwrap_err();
509 assert_eq!(err.code(), "invalid-argument", "{width}×{height}");
510 }
511 }
512
513 #[test]
514 fn rejects_an_empty_tile() {
515 let req = RenderRequest::page(0, 1.0).with_clip(PixelRect {
516 x: 0,
517 y: 0,
518 width: 0,
519 height: 10,
520 });
521 assert_eq!(
522 TilePlan::new(&LETTER, &req, &RenderLimits::default())
523 .unwrap_err()
524 .code(),
525 "invalid-argument"
526 );
527 }
528
529 #[test]
530 fn refuses_a_tile_over_the_pixel_limit_before_allocating() {
531 let err = TilePlan::new(&LETTER, &RenderRequest::page(0, 1000.0), &RenderLimits::default()).unwrap_err();
533 assert_eq!(err.code(), "render-too-large");
534 }
535
536 #[test]
537 fn allows_a_small_tile_of_a_huge_zoom() {
538 let req = RenderRequest::page(0, 1000.0).with_clip(PixelRect {
539 x: 300_000,
540 y: 400_000,
541 width: 512,
542 height: 512,
543 });
544 let plan = TilePlan::new(&LETTER, &req, &RenderLimits::default()).unwrap();
545 assert_eq!(plan.byte_len(), 512 * 512 * 4);
546 }
547
548 #[test]
549 fn refuses_a_page_too_large_to_address() {
550 let err = TilePlan::new(&LETTER, &RenderRequest::page(0, 1e9), &RenderLimits::default()).unwrap_err();
551 assert_eq!(err.code(), "invalid-argument");
552 }
553
554 #[test]
555 fn page_to_tile_maps_the_corners() {
556 let page = RenderPage {
557 width: 100.0,
558 height: 50.0,
559 rotate: Rotation::None,
560 };
561 let req = RenderRequest::page(0, 2.0);
562 let plan = TilePlan::new(&page, &req, &RenderLimits::default()).unwrap();
563 assert_eq!(
564 plan.page_to_tile(&page, Rotation::None).apply(100.0, 50.0),
565 (200.0, 100.0)
566 );
567 let turned = req.clone().with_rotation(Rotation::Clockwise90);
568 let plan = TilePlan::new(&page, &turned, &RenderLimits::default()).unwrap();
569 assert_eq!(
571 plan.page_to_tile(&page, Rotation::Clockwise90).apply(0.0, 0.0),
572 (100.0, 0.0)
573 );
574 let shifted = req.with_clip(PixelRect {
575 x: 10,
576 y: 20,
577 width: 5,
578 height: 5,
579 });
580 let plan = TilePlan::new(&page, &shifted, &RenderLimits::default()).unwrap();
581 assert_eq!(plan.page_to_tile(&page, Rotation::None).apply(5.0, 10.0), (0.0, 0.0));
582 }
583
584 #[test]
585 fn check_buffer_wants_exactly_the_tile_bytes() {
586 let plan = TilePlan::new(&LETTER, &RenderRequest::page(0, 0.1), &RenderLimits::default()).unwrap();
587 assert!(plan.check_buffer(&vec![0; plan.byte_len()]).is_ok());
588 assert_eq!(plan.check_buffer(&[0; 3]).unwrap_err().code(), "invalid-argument");
589 }
590 }
591}