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 to open the document and
59    /// hands none back: a shell that must reopen the document keeps it itself (ADR 0004 §1).
60    /// These options don't overwrite their copy, and hayro's parser holds one of its own for as
61    /// long as the document is open.
62    ///
63    /// Added in 0.2.0.
64    #[must_use]
65    pub fn with_password(mut self, password: &str) -> Self {
66        self.password = Some(password.to_owned());
67        self
68    }
69
70    /// Render limits for this document.
71    ///
72    /// Added in 0.2.0.
73    #[must_use]
74    pub const fn with_limits(mut self, limits: RenderLimits) -> Self {
75        self.limits = limits;
76        self
77    }
78
79    /// The password, if one was given.
80    ///
81    /// Added in 0.2.0.
82    #[must_use]
83    pub fn password(&self) -> Option<&str> {
84        self.password.as_deref()
85    }
86
87    /// The render limits.
88    ///
89    /// Added in 0.2.0.
90    #[must_use]
91    pub const fn limits(&self) -> &RenderLimits {
92        &self.limits
93    }
94}
95
96/// A rectangle in the output pixel space of the whole page at the request's scale and
97/// rotation, top-left origin, y down.
98///
99/// Added in 0.2.0.
100#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
101pub struct PixelRect {
102    /// Left edge.
103    pub x: u32,
104    /// Top edge.
105    pub y: u32,
106    /// Width in pixels.
107    pub width: u32,
108    /// Height in pixels.
109    pub height: u32,
110}
111
112/// What to draw besides the page content.
113///
114/// Added in 0.2.0.
115#[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    /// Annotation appearance streams (default on; PDFium's `FPDF_ANNOT`).
122    pub annotations: bool,
123    /// Form widgets, drawn read-only (default on). Widgets are annotations: they are drawn only
124    /// when `annotations` is on too.
125    pub form_widgets: bool,
126    /// Print intent: honours annotation `Print`/`NoView` flags (PDFium's `FPDF_PRINTING`).
127    pub print: bool,
128    /// Grayscale output.
129    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/// A straight-alpha sRGB colour.
144///
145/// Added in 0.2.0.
146#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
147pub struct Rgba8 {
148    /// Red.
149    pub r: u8,
150    /// Green.
151    pub g: u8,
152    /// Blue.
153    pub b: u8,
154    /// Alpha (255 = opaque).
155    pub a: u8,
156}
157
158impl Rgba8 {
159    /// Opaque white, the reader's page background.
160    ///
161    /// Added in 0.2.0.
162    pub const WHITE: Self = Self {
163        r: 255,
164        g: 255,
165        b: 255,
166        a: 255,
167    };
168}
169
170/// One render: a page, a scale, an optional tile, a view rotation, flags, a background, the
171/// page appearance and the annotations left out.
172///
173/// Added in 0.2.0.
174#[derive(Debug, Clone, PartialEq)]
175pub struct RenderRequest {
176    /// The page, 0-based (ADR 0027).
177    pub page: u32,
178    /// Output pixels per point, device pixel ratio already applied (1.0 is 72 DPI).
179    pub scale: f32,
180    /// The tile to draw; `None` is the whole page (still bounded by [`RenderLimits`]).
181    pub clip: Option<PixelRect>,
182    /// The view rotation.
183    pub rotation: Rotation,
184    /// What to draw.
185    pub flags: RenderFlags,
186    /// The background; `None` is transparent.
187    pub background: Option<Rgba8>,
188    /// How the page's colours are drawn (default: its own).
189    pub appearance: PageAppearance,
190    /// Annotations left out of this render only, each by its place in the page's `/Annots`
191    /// (default none). An editor hides the annotation it moves, and draws it itself while the
192    /// gesture lasts. The place, not `/NM`, names it: `/NM` is only a hint and two annotations
193    /// may share one. A place past the end of `/Annots` hides nothing.
194    ///
195    /// Added in 0.5.0.
196    pub hidden_annotations: Vec<u32>,
197}
198
199impl RenderRequest {
200    /// The whole of page `page` at `scale`, upright, default flags, on white.
201    ///
202    /// Added in 0.2.0.
203    #[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    /// Only the tile `clip`.
218    ///
219    /// Added in 0.2.0.
220    #[must_use]
221    pub const fn with_clip(mut self, clip: PixelRect) -> Self {
222        self.clip = Some(clip);
223        self
224    }
225
226    /// The view rotation.
227    ///
228    /// Added in 0.2.0.
229    #[must_use]
230    pub const fn with_rotation(mut self, rotation: Rotation) -> Self {
231        self.rotation = rotation;
232        self
233    }
234
235    /// The flags.
236    ///
237    /// Added in 0.2.0.
238    #[must_use]
239    pub const fn with_flags(mut self, flags: RenderFlags) -> Self {
240        self.flags = flags;
241        self
242    }
243
244    /// The background (`None`: transparent).
245    ///
246    /// Added in 0.2.0.
247    #[must_use]
248    pub const fn with_background(mut self, background: Option<Rgba8>) -> Self {
249        self.background = background;
250        self
251    }
252
253    /// The page appearance.
254    ///
255    /// Added in 0.2.0.
256    #[must_use]
257    pub const fn with_appearance(mut self, appearance: PageAppearance) -> Self {
258        self.appearance = appearance;
259        self
260    }
261
262    /// Leaves out the annotations at these places in the page's `/Annots`, for this render
263    /// only (see [`RenderRequest::hidden_annotations`]).
264    ///
265    /// Added in 0.5.0.
266    #[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/// A page as a backend reports it.
274///
275/// Added in 0.2.0.
276#[derive(Debug, Clone, Copy, PartialEq)]
277pub struct RenderPage {
278    /// Displayed width in points: the visible page box with `/Rotate` applied.
279    pub width: f32,
280    /// Displayed height in points.
281    pub height: f32,
282    /// The page's own `/Rotate`.
283    pub rotate: Rotation,
284}
285
286/// The geometry of one validated request: the whole page's pixel size at the scale and view
287/// rotation, and the tile inside it. Both backends render from this, so they agree on sizes.
288///
289/// Added in 0.2.0.
290#[derive(Debug, Clone, Copy, PartialEq, Eq)]
291pub struct TilePlan {
292    /// The whole page's width in pixels, after the view rotation.
293    pub page_width: u32,
294    /// The whole page's height in pixels, after the view rotation.
295    pub page_height: u32,
296    /// The tile.
297    pub tile: PixelRect,
298}
299
300impl TilePlan {
301    /// Validates `request` against `page` and `limits`.
302    ///
303    /// The page's pixel size is `max(1, floor(points × scale))` per side.
304    ///
305    /// # Errors
306    /// `invalid-argument` for a non-finite or non-positive scale, an empty tile or one outside
307    /// the page, or a page too large to address at this scale; `render-too-large` above
308    /// `limits`.
309    ///
310    /// Added in 0.2.0.
311    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    /// The bytes the tile needs: `width × height × 4`.
374    ///
375    /// Added in 0.2.0.
376    #[must_use]
377    pub fn byte_len(&self) -> usize {
378        // Bounded by RenderLimits (u32 sides, at most max_render_pixels): fits usize on every
379        // supported target only when the limit does, so saturate rather than wrap.
380        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    /// The affine matrix from the displayed page space of `page` (points, top-left origin, y down, `/Rotate` applied:
385    /// ADR 0027's page space) to this tile's pixels: scale to the page's integer pixel size,
386    /// apply the view `rotation`, shift the tile to the origin. Both adapters draw with it, so
387    /// their tiles agree.
388    ///
389    /// Added in 0.2.0.
390    #[must_use]
391    pub fn page_to_tile(&self, page: &RenderPage, rotation: Rotation) -> Matrix {
392        // The page's pixel size before the view rotation.
393        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        // Clockwise view rotations of the w0 × h0 bitmap, after scaling, then the tile shift.
401        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    /// Checks that `out` has exactly [`TilePlan::byte_len`] bytes.
410    ///
411    /// # Errors
412    /// `invalid-argument` (`BufferSize`) otherwise.
413    ///
414    /// Added in 0.2.0.
415    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
428/// `max(1, floor(v))` as pixels; a page wider than `i32::MAX` pixels (PDFium's limit) can't
429/// be addressed at this scale.
430fn 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    // In 1..=i32::MAX after the checks above: the cast is exact.
438    #[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            // A 1000× zoom of a letter page as one tile: 612,000 × 792,000 pixels.
532            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            // Clockwise: the top-left corner goes to the top-right of the 100 × 200 bitmap.
570            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}