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, the
169/// page appearance and the annotations left out.
170///
171/// Added in 0.2.0.
172#[derive(Debug, Clone, 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    /// Annotations left out of this render only, each by its place in the page's `/Annots`
189    /// (default none). An editor hides the annotation it moves, and draws it itself while the
190    /// gesture lasts. The place, not `/NM`, names it: `/NM` is only a hint and two annotations
191    /// may share one. A place past the end of `/Annots` hides nothing.
192    ///
193    /// Added in 0.5.0.
194    pub hidden_annotations: Vec<u32>,
195}
196
197impl RenderRequest {
198    /// The whole of page `page` at `scale`, upright, default flags, on white.
199    ///
200    /// Added in 0.2.0.
201    #[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    /// Only the tile `clip`.
216    ///
217    /// Added in 0.2.0.
218    #[must_use]
219    pub const fn with_clip(mut self, clip: PixelRect) -> Self {
220        self.clip = Some(clip);
221        self
222    }
223
224    /// The view rotation.
225    ///
226    /// Added in 0.2.0.
227    #[must_use]
228    pub const fn with_rotation(mut self, rotation: Rotation) -> Self {
229        self.rotation = rotation;
230        self
231    }
232
233    /// The flags.
234    ///
235    /// Added in 0.2.0.
236    #[must_use]
237    pub const fn with_flags(mut self, flags: RenderFlags) -> Self {
238        self.flags = flags;
239        self
240    }
241
242    /// The background (`None`: transparent).
243    ///
244    /// Added in 0.2.0.
245    #[must_use]
246    pub const fn with_background(mut self, background: Option<Rgba8>) -> Self {
247        self.background = background;
248        self
249    }
250
251    /// The page appearance.
252    ///
253    /// Added in 0.2.0.
254    #[must_use]
255    pub const fn with_appearance(mut self, appearance: PageAppearance) -> Self {
256        self.appearance = appearance;
257        self
258    }
259
260    /// Leaves out the annotations at these places in the page's `/Annots`, for this render
261    /// only (see [`RenderRequest::hidden_annotations`]).
262    ///
263    /// Added in 0.5.0.
264    #[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/// A page as a backend reports it.
272///
273/// Added in 0.2.0.
274#[derive(Debug, Clone, Copy, PartialEq)]
275pub struct RenderPage {
276    /// Displayed width in points: the visible page box with `/Rotate` applied.
277    pub width: f32,
278    /// Displayed height in points.
279    pub height: f32,
280    /// The page's own `/Rotate`.
281    pub rotate: Rotation,
282}
283
284/// The geometry of one validated request: the whole page's pixel size at the scale and view
285/// rotation, and the tile inside it. Both backends render from this, so they agree on sizes.
286///
287/// Added in 0.2.0.
288#[derive(Debug, Clone, Copy, PartialEq, Eq)]
289pub struct TilePlan {
290    /// The whole page's width in pixels, after the view rotation.
291    pub page_width: u32,
292    /// The whole page's height in pixels, after the view rotation.
293    pub page_height: u32,
294    /// The tile.
295    pub tile: PixelRect,
296}
297
298impl TilePlan {
299    /// Validates `request` against `page` and `limits`.
300    ///
301    /// The page's pixel size is `max(1, floor(points × scale))` per side.
302    ///
303    /// # Errors
304    /// `invalid-argument` for a non-finite or non-positive scale, an empty tile or one outside
305    /// the page, or a page too large to address at this scale; `render-too-large` above
306    /// `limits`.
307    ///
308    /// Added in 0.2.0.
309    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    /// The bytes the tile needs: `width × height × 4`.
372    ///
373    /// Added in 0.2.0.
374    #[must_use]
375    pub fn byte_len(&self) -> usize {
376        // Bounded by RenderLimits (u32 sides, at most max_render_pixels): fits usize on every
377        // supported target only when the limit does, so saturate rather than wrap.
378        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    /// The affine matrix from the displayed page space of `page` (points, top-left origin, y down, `/Rotate` applied:
383    /// ADR 0027's page space) to this tile's pixels: scale to the page's integer pixel size,
384    /// apply the view `rotation`, shift the tile to the origin. Both adapters draw with it, so
385    /// their tiles agree.
386    ///
387    /// Added in 0.2.0.
388    #[must_use]
389    pub fn page_to_tile(&self, page: &RenderPage, rotation: Rotation) -> Matrix {
390        // The page's pixel size before the view rotation.
391        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        // Clockwise view rotations of the w0 × h0 bitmap, after scaling, then the tile shift.
399        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    /// Checks that `out` has exactly [`TilePlan::byte_len`] bytes.
408    ///
409    /// # Errors
410    /// `invalid-argument` (`BufferSize`) otherwise.
411    ///
412    /// Added in 0.2.0.
413    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
426/// `max(1, floor(v))` as pixels; a page wider than `i32::MAX` pixels (PDFium's limit) can't
427/// be addressed at this scale.
428fn 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    // In 1..=i32::MAX after the checks above: the cast is exact.
436    #[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            // A 1000× zoom of a letter page as one tile: 612,000 × 792,000 pixels.
530            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            // Clockwise: the top-left corner goes to the top-right of the 100 × 200 bitmap.
568            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}