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, 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 pub hidden_annotations: Vec<u32>,
195}
196
197impl RenderRequest {
198 #[must_use]
202 pub fn page(page: u32, scale: f32) -> Self {
203 Self {
204 page,
205 scale,
206 clip: None,
207 rotation: Rotation::None,
208 flags: RenderFlags::default(),
209 background: Some(Rgba8::WHITE),
210 appearance: PageAppearance::Original,
211 hidden_annotations: Vec::new(),
212 }
213 }
214
215 #[must_use]
219 pub const fn with_clip(mut self, clip: PixelRect) -> Self {
220 self.clip = Some(clip);
221 self
222 }
223
224 #[must_use]
228 pub const fn with_rotation(mut self, rotation: Rotation) -> Self {
229 self.rotation = rotation;
230 self
231 }
232
233 #[must_use]
237 pub const fn with_flags(mut self, flags: RenderFlags) -> Self {
238 self.flags = flags;
239 self
240 }
241
242 #[must_use]
246 pub const fn with_background(mut self, background: Option<Rgba8>) -> Self {
247 self.background = background;
248 self
249 }
250
251 #[must_use]
255 pub const fn with_appearance(mut self, appearance: PageAppearance) -> Self {
256 self.appearance = appearance;
257 self
258 }
259
260 #[must_use]
265 pub fn with_hidden_annotations(mut self, places: impl IntoIterator<Item = u32>) -> Self {
266 self.hidden_annotations = places.into_iter().collect();
267 self
268 }
269}
270
271#[derive(Debug, Clone, Copy, PartialEq)]
275pub struct RenderPage {
276 pub width: f32,
278 pub height: f32,
280 pub rotate: Rotation,
282}
283
284#[derive(Debug, Clone, Copy, PartialEq, Eq)]
289pub struct TilePlan {
290 pub page_width: u32,
292 pub page_height: u32,
294 pub tile: PixelRect,
296}
297
298impl TilePlan {
299 pub fn new(page: &RenderPage, request: &RenderRequest, limits: &RenderLimits) -> Result<Self, RenderError> {
310 let scale = f64::from(request.scale);
311 if !scale.is_finite() || scale <= 0.0 {
312 return Err(RenderError::InvalidRequest {
313 what: "scale must be finite and positive",
314 });
315 }
316 if !(page.width.is_finite() && page.height.is_finite() && page.width > 0.0 && page.height > 0.0) {
317 return Err(RenderError::InvalidRequest {
318 what: "the page has no drawable area",
319 });
320 }
321 let (w, h) = if request.rotation.is_quarter_turn() {
322 (page.height, page.width)
323 } else {
324 (page.width, page.height)
325 };
326 let page_width = pixels(f64::from(w) * scale)?;
327 let page_height = pixels(f64::from(h) * scale)?;
328 let tile = request.clip.unwrap_or(PixelRect {
329 x: 0,
330 y: 0,
331 width: page_width,
332 height: page_height,
333 });
334 if tile.width == 0 || tile.height == 0 {
335 return Err(RenderError::InvalidRequest {
336 what: "the tile is empty",
337 });
338 }
339 let right = u64::from(tile.x) + u64::from(tile.width);
340 let bottom = u64::from(tile.y) + u64::from(tile.height);
341 if right > u64::from(page_width) || bottom > u64::from(page_height) {
342 return Err(RenderError::InvalidRequest {
343 what: "the tile extends past the page",
344 });
345 }
346 let (tw, th) = (u64::from(tile.width), u64::from(tile.height));
347 let side = u64::from(limits.max_render_side);
348 if tw > side || th > side {
349 return Err(RenderError::TooLarge {
350 width: tw,
351 height: th,
352 limit: side,
353 unit: "pixels per side",
354 });
355 }
356 if tw * th > limits.max_render_pixels {
357 return Err(RenderError::TooLarge {
358 width: tw,
359 height: th,
360 limit: limits.max_render_pixels,
361 unit: "pixels",
362 });
363 }
364 Ok(Self {
365 page_width,
366 page_height,
367 tile,
368 })
369 }
370
371 #[must_use]
375 pub fn byte_len(&self) -> usize {
376 usize::try_from(u64::from(self.tile.width) * u64::from(self.tile.height) * BYTES_PER_PIXEL as u64)
379 .unwrap_or(usize::MAX)
380 }
381
382 #[must_use]
389 pub fn page_to_tile(&self, page: &RenderPage, rotation: Rotation) -> Matrix {
390 let (w0, h0) = if rotation.is_quarter_turn() {
392 (f64::from(self.page_height), f64::from(self.page_width))
393 } else {
394 (f64::from(self.page_width), f64::from(self.page_height))
395 };
396 let (sx, sy) = (w0 / f64::from(page.width), h0 / f64::from(page.height));
397 let (tx, ty) = (f64::from(self.tile.x), f64::from(self.tile.y));
398 Matrix::new(match rotation {
400 Rotation::None => [sx, 0.0, 0.0, sy, -tx, -ty],
401 Rotation::Clockwise90 => [0.0, sx, -sy, 0.0, h0 - tx, -ty],
402 Rotation::Half => [-sx, 0.0, 0.0, -sy, w0 - tx, h0 - ty],
403 Rotation::Clockwise270 => [0.0, -sx, sy, 0.0, -tx, w0 - ty],
404 })
405 }
406
407 pub fn check_buffer(&self, out: &[u8]) -> Result<(), RenderError> {
414 let expected = self.byte_len();
415 if out.len() == expected {
416 Ok(())
417 } else {
418 Err(RenderError::BufferSize {
419 expected,
420 actual: out.len(),
421 })
422 }
423 }
424}
425
426fn pixels(v: f64) -> Result<u32, RenderError> {
429 let v = v.floor().max(1.0);
430 if v > f64::from(i32::MAX) {
431 return Err(RenderError::InvalidRequest {
432 what: "the page is too large to address at this scale",
433 });
434 }
435 #[expect(
437 clippy::cast_possible_truncation,
438 clippy::cast_sign_loss,
439 reason = "range checked above"
440 )]
441 Ok(v as u32)
442}
443
444#[cfg(test)]
445mod tests {
446
447 use super::{PixelRect, RenderLimits, RenderPage, RenderRequest, Rotation, TilePlan};
448 use crate::RenderError;
449
450 const LETTER: RenderPage = RenderPage {
451 width: 612.0,
452 height: 792.0,
453 rotate: Rotation::None,
454 };
455
456 mod tile_plan {
457 use super::*;
458
459 #[test]
460 fn whole_page_floors_points_times_scale() {
461 let plan = TilePlan::new(&LETTER, &RenderRequest::page(0, 96.0 / 72.0), &RenderLimits::default()).unwrap();
462 assert_eq!((plan.page_width, plan.page_height), (816, 1056));
463 assert_eq!(plan.byte_len(), 816 * 1056 * 4);
464 }
465
466 #[test]
467 fn quarter_turn_swaps_the_page_size() {
468 let req = RenderRequest::page(0, 1.0).with_rotation(Rotation::Clockwise90);
469 let plan = TilePlan::new(&LETTER, &req, &RenderLimits::default()).unwrap();
470 assert_eq!((plan.page_width, plan.page_height), (792, 612));
471 }
472
473 #[test]
474 fn rejects_a_non_finite_or_non_positive_scale() {
475 for scale in [0.0, -1.0, f32::NAN, f32::INFINITY] {
476 let err = TilePlan::new(&LETTER, &RenderRequest::page(0, scale), &RenderLimits::default()).unwrap_err();
477 assert_eq!(err.code(), "invalid-argument", "{scale}");
478 }
479 }
480
481 #[test]
482 fn rejects_a_tile_past_the_page() {
483 let req = RenderRequest::page(0, 1.0).with_clip(PixelRect {
484 x: 600,
485 y: 0,
486 width: 13,
487 height: 10,
488 });
489 let err = TilePlan::new(&LETTER, &req, &RenderLimits::default()).unwrap_err();
490 assert_eq!(
491 err,
492 RenderError::InvalidRequest {
493 what: "the tile extends past the page"
494 }
495 );
496 }
497
498 #[test]
499 fn rejects_a_page_without_area() {
500 for (width, height) in [(0.0, 792.0), (612.0, -1.0), (f32::NAN, 792.0)] {
501 let page = RenderPage {
502 width,
503 height,
504 rotate: Rotation::None,
505 };
506 let err = TilePlan::new(&page, &RenderRequest::page(0, 1.0), &RenderLimits::default()).unwrap_err();
507 assert_eq!(err.code(), "invalid-argument", "{width}×{height}");
508 }
509 }
510
511 #[test]
512 fn rejects_an_empty_tile() {
513 let req = RenderRequest::page(0, 1.0).with_clip(PixelRect {
514 x: 0,
515 y: 0,
516 width: 0,
517 height: 10,
518 });
519 assert_eq!(
520 TilePlan::new(&LETTER, &req, &RenderLimits::default())
521 .unwrap_err()
522 .code(),
523 "invalid-argument"
524 );
525 }
526
527 #[test]
528 fn refuses_a_tile_over_the_pixel_limit_before_allocating() {
529 let err = TilePlan::new(&LETTER, &RenderRequest::page(0, 1000.0), &RenderLimits::default()).unwrap_err();
531 assert_eq!(err.code(), "render-too-large");
532 }
533
534 #[test]
535 fn allows_a_small_tile_of_a_huge_zoom() {
536 let req = RenderRequest::page(0, 1000.0).with_clip(PixelRect {
537 x: 300_000,
538 y: 400_000,
539 width: 512,
540 height: 512,
541 });
542 let plan = TilePlan::new(&LETTER, &req, &RenderLimits::default()).unwrap();
543 assert_eq!(plan.byte_len(), 512 * 512 * 4);
544 }
545
546 #[test]
547 fn refuses_a_page_too_large_to_address() {
548 let err = TilePlan::new(&LETTER, &RenderRequest::page(0, 1e9), &RenderLimits::default()).unwrap_err();
549 assert_eq!(err.code(), "invalid-argument");
550 }
551
552 #[test]
553 fn page_to_tile_maps_the_corners() {
554 let page = RenderPage {
555 width: 100.0,
556 height: 50.0,
557 rotate: Rotation::None,
558 };
559 let req = RenderRequest::page(0, 2.0);
560 let plan = TilePlan::new(&page, &req, &RenderLimits::default()).unwrap();
561 assert_eq!(
562 plan.page_to_tile(&page, Rotation::None).apply(100.0, 50.0),
563 (200.0, 100.0)
564 );
565 let turned = req.clone().with_rotation(Rotation::Clockwise90);
566 let plan = TilePlan::new(&page, &turned, &RenderLimits::default()).unwrap();
567 assert_eq!(
569 plan.page_to_tile(&page, Rotation::Clockwise90).apply(0.0, 0.0),
570 (100.0, 0.0)
571 );
572 let shifted = req.with_clip(PixelRect {
573 x: 10,
574 y: 20,
575 width: 5,
576 height: 5,
577 });
578 let plan = TilePlan::new(&page, &shifted, &RenderLimits::default()).unwrap();
579 assert_eq!(plan.page_to_tile(&page, Rotation::None).apply(5.0, 10.0), (0.0, 0.0));
580 }
581
582 #[test]
583 fn check_buffer_wants_exactly_the_tile_bytes() {
584 let plan = TilePlan::new(&LETTER, &RenderRequest::page(0, 0.1), &RenderLimits::default()).unwrap();
585 assert!(plan.check_buffer(&vec![0; plan.byte_len()]).is_ok());
586 assert_eq!(plan.check_buffer(&[0; 3]).unwrap_err().code(), "invalid-argument");
587 }
588 }
589}