Skip to main content

laminapdf_render/
request.rs

1//! What a caller asks a backend to draw ([`RenderRequest`]), the bounds every backend enforces
2//! ([`RenderLimits`]) and the tile geometry they share ([`TilePlan`]), ADR 0004 §1.
3
4use laminapdf_model::Matrix;
5use laminapdf_syntax::Rotation;
6
7use crate::appearance::PageAppearance;
8use crate::error::RenderError;
9
10/// The output pixel format of every backend: RGBA8, **straight (not premultiplied) alpha**,
11/// sRGB, rows packed at `width × 4` bytes. What `ImageData` and `createImageBitmap` take.
12///
13/// Added in 0.2.0.
14pub const BYTES_PER_PIXEL: usize = 4;
15
16/// Bounds on one render, checked before anything is allocated (`render-too-large`).
17///
18/// Added in 0.2.0.
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub struct RenderLimits {
21    /// Most pixels in one tile. Default 16,777,216 (4096 × 4096), iOS Safari's per-canvas cap.
22    pub max_render_pixels: u64,
23    /// Most pixels on either side of one tile. Default 16,384.
24    pub max_render_side: u32,
25    /// Most input bytes a backend that needs the whole file in memory (hayro) reads.
26    /// Default 1 GiB.
27    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/// How a backend opens a document.
41///
42/// Added in 0.2.0.
43#[derive(Debug, Clone, Default)]
44pub struct RenderOpenOptions {
45    password: Option<String>,
46    limits: RenderLimits,
47}
48
49impl RenderOpenOptions {
50    /// No password, default limits.
51    ///
52    /// Added in 0.2.0.
53    #[must_use]
54    pub fn new() -> Self {
55        Self::default()
56    }
57
58    /// The password for an encrypted document. The backend uses it in `open` and keeps no
59    /// copy (ADR 0004 §1): a shell that must reopen the document keeps it itself.
60    ///
61    /// Added in 0.2.0.
62    #[must_use]
63    pub fn with_password(mut self, password: &str) -> Self {
64        self.password = Some(password.to_owned());
65        self
66    }
67
68    /// Render limits for this document.
69    ///
70    /// Added in 0.2.0.
71    #[must_use]
72    pub const fn with_limits(mut self, limits: RenderLimits) -> Self {
73        self.limits = limits;
74        self
75    }
76
77    /// The password, if one was given.
78    ///
79    /// Added in 0.2.0.
80    #[must_use]
81    pub fn password(&self) -> Option<&str> {
82        self.password.as_deref()
83    }
84
85    /// The render limits.
86    ///
87    /// Added in 0.2.0.
88    #[must_use]
89    pub const fn limits(&self) -> &RenderLimits {
90        &self.limits
91    }
92}
93
94/// A rectangle in the output pixel space of the whole page at the request's scale and
95/// rotation, top-left origin, y down.
96///
97/// Added in 0.2.0.
98#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
99pub struct PixelRect {
100    /// Left edge.
101    pub x: u32,
102    /// Top edge.
103    pub y: u32,
104    /// Width in pixels.
105    pub width: u32,
106    /// Height in pixels.
107    pub height: u32,
108}
109
110/// What to draw besides the page content.
111///
112/// Added in 0.2.0.
113#[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    /// Annotation appearance streams (default on; PDFium's `FPDF_ANNOT`).
120    pub annotations: bool,
121    /// Form widgets, drawn read-only (default on). Widgets are annotations: they are drawn only
122    /// when `annotations` is on too.
123    pub form_widgets: bool,
124    /// Print intent: honours annotation `Print`/`NoView` flags (PDFium's `FPDF_PRINTING`).
125    pub print: bool,
126    /// Grayscale output.
127    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/// A straight-alpha sRGB colour.
142///
143/// Added in 0.2.0.
144#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
145pub struct Rgba8 {
146    /// Red.
147    pub r: u8,
148    /// Green.
149    pub g: u8,
150    /// Blue.
151    pub b: u8,
152    /// Alpha (255 = opaque).
153    pub a: u8,
154}
155
156impl Rgba8 {
157    /// Opaque white, the reader's page background.
158    ///
159    /// Added in 0.2.0.
160    pub const WHITE: Self = Self {
161        r: 255,
162        g: 255,
163        b: 255,
164        a: 255,
165    };
166}
167
168/// One render: a page, a scale, an optional tile, a view rotation, flags, a background and the
169/// page appearance.
170///
171/// Added in 0.2.0.
172#[derive(Debug, Clone, Copy, PartialEq)]
173pub struct RenderRequest {
174    /// The page, 0-based (ADR 0027).
175    pub page: u32,
176    /// Output pixels per point, device pixel ratio already applied (1.0 is 72 DPI).
177    pub scale: f32,
178    /// The tile to draw; `None` is the whole page (still bounded by [`RenderLimits`]).
179    pub clip: Option<PixelRect>,
180    /// The view rotation.
181    pub rotation: Rotation,
182    /// What to draw.
183    pub flags: RenderFlags,
184    /// The background; `None` is transparent.
185    pub background: Option<Rgba8>,
186    /// How the page's colours are drawn (default: its own).
187    pub appearance: PageAppearance,
188}
189
190impl RenderRequest {
191    /// The whole of page `page` at `scale`, upright, default flags, on white.
192    ///
193    /// Added in 0.2.0.
194    #[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    /// Only the tile `clip`.
208    ///
209    /// Added in 0.2.0.
210    #[must_use]
211    pub const fn with_clip(mut self, clip: PixelRect) -> Self {
212        self.clip = Some(clip);
213        self
214    }
215
216    /// The view rotation.
217    ///
218    /// Added in 0.2.0.
219    #[must_use]
220    pub const fn with_rotation(mut self, rotation: Rotation) -> Self {
221        self.rotation = rotation;
222        self
223    }
224
225    /// The flags.
226    ///
227    /// Added in 0.2.0.
228    #[must_use]
229    pub const fn with_flags(mut self, flags: RenderFlags) -> Self {
230        self.flags = flags;
231        self
232    }
233
234    /// The background (`None`: transparent).
235    ///
236    /// Added in 0.2.0.
237    #[must_use]
238    pub const fn with_background(mut self, background: Option<Rgba8>) -> Self {
239        self.background = background;
240        self
241    }
242
243    /// The page appearance.
244    ///
245    /// Added in 0.2.0.
246    #[must_use]
247    pub const fn with_appearance(mut self, appearance: PageAppearance) -> Self {
248        self.appearance = appearance;
249        self
250    }
251}
252
253/// A page as a backend reports it.
254///
255/// Added in 0.2.0.
256#[derive(Debug, Clone, Copy, PartialEq)]
257pub struct RenderPage {
258    /// Displayed width in points: the visible page box with `/Rotate` applied.
259    pub width: f32,
260    /// Displayed height in points.
261    pub height: f32,
262    /// The page's own `/Rotate`.
263    pub rotate: Rotation,
264}
265
266/// The geometry of one validated request: the whole page's pixel size at the scale and view
267/// rotation, and the tile inside it. Both backends render from this, so they agree on sizes.
268///
269/// Added in 0.2.0.
270#[derive(Debug, Clone, Copy, PartialEq, Eq)]
271pub struct TilePlan {
272    /// The whole page's width in pixels, after the view rotation.
273    pub page_width: u32,
274    /// The whole page's height in pixels, after the view rotation.
275    pub page_height: u32,
276    /// The tile.
277    pub tile: PixelRect,
278}
279
280impl TilePlan {
281    /// Validates `request` against `page` and `limits`.
282    ///
283    /// The page's pixel size is `max(1, floor(points × scale))` per side.
284    ///
285    /// # Errors
286    /// `invalid-argument` for a non-finite or non-positive scale, an empty tile or one outside
287    /// the page, or a page too large to address at this scale; `render-too-large` above
288    /// `limits`.
289    ///
290    /// Added in 0.2.0.
291    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    /// The bytes the tile needs: `width × height × 4`.
354    ///
355    /// Added in 0.2.0.
356    #[must_use]
357    pub fn byte_len(&self) -> usize {
358        // Bounded by RenderLimits (u32 sides, at most max_render_pixels): fits usize on every
359        // supported target only when the limit does, so saturate rather than wrap.
360        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    /// The affine matrix from the displayed page space of `page` (points, top-left origin, y down, `/Rotate` applied:
365    /// ADR 0027's page space) to this tile's pixels: scale to the page's integer pixel size,
366    /// apply the view `rotation`, shift the tile to the origin. Both adapters draw with it, so
367    /// their tiles agree.
368    ///
369    /// Added in 0.2.0.
370    #[must_use]
371    pub fn page_to_tile(&self, page: &RenderPage, rotation: Rotation) -> Matrix {
372        // The page's pixel size before the view rotation.
373        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        // Clockwise view rotations of the w0 × h0 bitmap, after scaling, then the tile shift.
381        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    /// Checks that `out` has exactly [`TilePlan::byte_len`] bytes.
390    ///
391    /// # Errors
392    /// `invalid-argument` (`BufferSize`) otherwise.
393    ///
394    /// Added in 0.2.0.
395    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
408/// `max(1, floor(v))` as pixels; a page wider than `i32::MAX` pixels (PDFium's limit) can't
409/// be addressed at this scale.
410fn 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    // In 1..=i32::MAX after the checks above: the cast is exact.
418    #[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            // A 1000× zoom of a letter page as one tile: 612,000 × 792,000 pixels.
512            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            // Clockwise: the top-left corner goes to the top-right of the 100 × 200 bitmap.
550            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}