exprim 0.4.0

A concurrent, memory-bounded PDF reader and renderer: parse, extract text, and rasterize pages on an immutable document snapshot
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
//! Paper, orientation, margins, and the rectangle type the imposition maths
//! works in.
//!
//! Everything here is in PostScript points (1/72 inch), which is the unit the
//! PDF page boxes and both target spooler APIs agree on.

use crate::print::PrintError;

/// Points per inch.
pub const POINTS_PER_INCH: f64 = 72.0;
/// Points per millimetre.
pub const POINTS_PER_MM: f64 = POINTS_PER_INCH / 25.4;

/// The conservative hardware margin assumed when the driver will not say:
/// 6.35 mm, a quarter inch, on every edge.
///
/// Assuming zero is the classic cause of clipped printouts, so the default
/// errs inward and callers with real driver numbers override it.
pub const DEFAULT_HARDWARE_MARGIN_PT: f64 = 6.35 * POINTS_PER_MM;

/// An axis-aligned rectangle in points, `y` up, as PDF user space has it.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Rect {
    /// Left edge.
    pub x0: f64,
    /// Bottom edge.
    pub y0: f64,
    /// Right edge.
    pub x1: f64,
    /// Top edge.
    pub y1: f64,
}

impl Rect {
    /// The empty rectangle at the origin.
    pub const ZERO: Self = Self {
        x0: 0.0,
        y0: 0.0,
        x1: 0.0,
        y1: 0.0,
    };

    /// A rectangle from its left, bottom, right and top edges.
    #[must_use]
    pub const fn new(x0: f64, y0: f64, x1: f64, y1: f64) -> Self {
        Self { x0, y0, x1, y1 }
    }

    /// A rectangle from a corner and a size.
    #[must_use]
    pub fn from_size(x: f64, y: f64, width: f64, height: f64) -> Self {
        Self::new(x, y, x + width, y + height)
    }

    /// Normalize so `x0 <= x1` and `y0 <= y1`.
    #[must_use]
    pub fn normalized(self) -> Self {
        Self {
            x0: self.x0.min(self.x1),
            y0: self.y0.min(self.y1),
            x1: self.x0.max(self.x1),
            y1: self.y0.max(self.y1),
        }
    }

    /// Width, negative when the rectangle is not normalized.
    #[must_use]
    pub fn width(self) -> f64 {
        self.x1 - self.x0
    }

    /// Height, negative when the rectangle is not normalized.
    #[must_use]
    pub fn height(self) -> f64 {
        self.y1 - self.y0
    }

    /// Whether the rectangle has no area.
    #[must_use]
    pub fn is_empty(self) -> bool {
        !(self.width() > 0.0 && self.height() > 0.0)
    }

    /// The centre point, `(x, y)`.
    #[must_use]
    pub fn center(self) -> (f64, f64) {
        ((self.x0 + self.x1) / 2.0, (self.y0 + self.y1) / 2.0)
    }

    /// Shrink by `dx` horizontally and `dy` vertically on every side.
    #[must_use]
    pub fn inset(self, dx: f64, dy: f64) -> Self {
        Self {
            x0: self.x0 + dx,
            y0: self.y0 + dy,
            x1: self.x1 - dx,
            y1: self.y1 - dy,
        }
    }

    /// The area both rectangles cover. Empty (see [`is_empty`](Self::is_empty))
    /// when they do not overlap.
    #[must_use]
    pub fn intersect(self, other: Self) -> Self {
        Self {
            x0: self.x0.max(other.x0),
            y0: self.y0.max(other.y0),
            x1: self.x1.min(other.x1),
            y1: self.y1.min(other.y1),
        }
    }

    /// Whether `self` lies inside `other`, allowing `epsilon` of float slop.
    #[must_use]
    pub fn contained_by(self, other: Self, epsilon: f64) -> bool {
        self.x0 >= other.x0 - epsilon
            && self.y0 >= other.y0 - epsilon
            && self.x1 <= other.x1 + epsilon
            && self.y1 <= other.y1 + epsilon
    }

    /// Whether two rectangles share any area beyond `epsilon`.
    #[must_use]
    pub fn overlaps(self, other: Self, epsilon: f64) -> bool {
        let overlap = self.intersect(other);
        overlap.width() > epsilon && overlap.height() > epsilon
    }
}

/// Which way the sheet is turned.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub enum Orientation {
    /// Taller than wide.
    Portrait,
    /// Wider than tall.
    Landscape,
    /// Rotate each page whichever way fits more of it on the sheet.
    #[default]
    Auto,
}

/// Margins in points, one per paper edge.
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct Margins {
    /// Left margin.
    pub left: f64,
    /// Right margin.
    pub right: f64,
    /// Top margin.
    pub top: f64,
    /// Bottom margin.
    pub bottom: f64,
}

impl Margins {
    /// No margin on any edge.
    pub const ZERO: Self = Self {
        left: 0.0,
        right: 0.0,
        top: 0.0,
        bottom: 0.0,
    };

    /// The same margin, in points, on every edge.
    #[must_use]
    pub const fn uniform(points: f64) -> Self {
        Self {
            left: points,
            right: points,
            top: points,
            bottom: points,
        }
    }

    /// The same margin, in millimetres, on every edge.
    #[must_use]
    pub fn millimetres(mm: f64) -> Self {
        Self::uniform(mm * POINTS_PER_MM)
    }

    /// The same margin, in inches, on every edge.
    #[must_use]
    pub fn inches(inches: f64) -> Self {
        Self::uniform(inches * POINTS_PER_INCH)
    }

    /// The larger of `self` and `other` on each edge.
    ///
    /// This is how user margins and hardware margins combine: a user margin
    /// narrower than the printer's unprintable border is silently widened to
    /// it, because the alternative is content that vanishes on paper.
    #[must_use]
    pub fn max_with(self, other: Self) -> Self {
        Self {
            left: self.left.max(other.left),
            right: self.right.max(other.right),
            top: self.top.max(other.top),
            bottom: self.bottom.max(other.bottom),
        }
    }

    /// Rotate the margins with the sheet: a quarter turn counter-clockwise
    /// sends the left edge to the bottom.
    #[must_use]
    pub fn rotated_quarter_turns(self, turns: i32) -> Self {
        match turns.rem_euclid(4) {
            0 => self,
            1 => Self {
                left: self.top,
                top: self.right,
                right: self.bottom,
                bottom: self.left,
            },
            2 => Self {
                left: self.right,
                right: self.left,
                top: self.bottom,
                bottom: self.top,
            },
            _ => Self {
                left: self.bottom,
                bottom: self.right,
                right: self.top,
                top: self.left,
            },
        }
    }

    /// Mirror left and right. Duplex long-edge binding needs this on back
    /// sides so that the binding margin stays on the binding side.
    #[must_use]
    pub fn mirrored_horizontally(self) -> Self {
        Self {
            left: self.right,
            right: self.left,
            ..self
        }
    }

    /// Mirror top and bottom, for short-edge duplex binding.
    #[must_use]
    pub fn mirrored_vertically(self) -> Self {
        Self {
            top: self.bottom,
            bottom: self.top,
            ..self
        }
    }

    /// Reject margins that are negative or not finite.
    pub fn validate(&self) -> Result<(), PrintError> {
        for (name, value) in [
            ("left", self.left),
            ("right", self.right),
            ("top", self.top),
            ("bottom", self.bottom),
        ] {
            if !value.is_finite() || value < 0.0 {
                return Err(PrintError::InvalidOptions(format!(
                    "{name} margin {value} is not a non-negative finite number"
                )));
            }
        }
        Ok(())
    }
}

impl Default for Margins {
    fn default() -> Self {
        Self::ZERO
    }
}

/// A sheet of paper, either a named standard size or explicit dimensions.
///
/// Named sizes carry their *portrait* extent; [`PaperSize::size`] returns it
/// that way and callers swap for landscape.
#[derive(Debug, Clone, Copy, PartialEq)]
#[non_exhaustive]
pub enum PaperSize {
    /// ISO A3, 297 x 420 mm.
    A3,
    /// ISO A4, 210 x 297 mm.
    A4,
    /// ISO A5, 148 x 210 mm.
    A5,
    /// ISO A6, 105 x 148 mm.
    A6,
    /// ISO B5, 176 x 250 mm.
    B5,
    /// US Letter, 8.5 x 11 in.
    Letter,
    /// US Legal, 8.5 x 14 in.
    Legal,
    /// Tabloid, 11 x 17 in.
    Tabloid,
    /// Executive, 7.25 x 10.5 in.
    Executive,
    /// Explicit portrait dimensions in points.
    Custom {
        /// Width in points.
        width: f64,
        /// Height in points.
        height: f64,
    },
}

impl PaperSize {
    /// Portrait `(width, height)` in points.
    #[must_use]
    pub fn size(self) -> (f64, f64) {
        // ISO sizes are the exact millimetre dimensions converted to points;
        // the imperial ones are exact in inches.
        match self {
            Self::A3 => (297.0 * POINTS_PER_MM, 420.0 * POINTS_PER_MM),
            Self::A4 => (210.0 * POINTS_PER_MM, 297.0 * POINTS_PER_MM),
            Self::A5 => (148.0 * POINTS_PER_MM, 210.0 * POINTS_PER_MM),
            Self::A6 => (105.0 * POINTS_PER_MM, 148.0 * POINTS_PER_MM),
            Self::B5 => (176.0 * POINTS_PER_MM, 250.0 * POINTS_PER_MM),
            Self::Letter => (612.0, 792.0),
            Self::Legal => (612.0, 1008.0),
            Self::Tabloid => (792.0, 1224.0),
            Self::Executive => (522.0, 756.0),
            Self::Custom { width, height } => (width, height),
        }
    }

    /// Portrait width in points.
    #[must_use]
    pub fn width(self) -> f64 {
        self.size().0
    }

    /// Portrait height in points.
    #[must_use]
    pub fn height(self) -> f64 {
        self.size().1
    }

    /// The sheet rectangle at `orientation`, with its origin at (0, 0).
    ///
    /// [`Orientation::Auto`] is resolved by the imposition code against the
    /// pages being placed, so it is treated as portrait here.
    #[must_use]
    pub fn rect(self, orientation: Orientation) -> Rect {
        let (w, h) = self.size();
        match orientation {
            Orientation::Landscape => Rect::from_size(0.0, 0.0, h, w),
            Orientation::Portrait | Orientation::Auto => Rect::from_size(0.0, 0.0, w, h),
        }
    }

    /// The CUPS/IPP media name, when one exists. Used by the pass-through
    /// path to name the paper without rasterizing.
    #[must_use]
    pub fn ipp_name(self) -> Option<&'static str> {
        Some(match self {
            Self::A3 => "iso_a3_297x420mm",
            Self::A4 => "iso_a4_210x297mm",
            Self::A5 => "iso_a5_148x210mm",
            Self::A6 => "iso_a6_105x148mm",
            Self::B5 => "iso_b5_176x250mm",
            Self::Letter => "na_letter_8.5x11in",
            Self::Legal => "na_legal_8.5x14in",
            Self::Tabloid => "na_ledger_11x17in",
            Self::Executive => "na_executive_7.25x10.5in",
            Self::Custom { .. } => return None,
        })
    }

    /// Parse a paper name, case-insensitively. Also accepts explicit sizes as
    /// `210x297mm`, `8.5x11in`, or `612x792pt`.
    pub fn parse(text: &str) -> Result<Self, PrintError> {
        let trimmed = text.trim();
        let lower = trimmed.to_ascii_lowercase();
        let named = match lower.as_str() {
            "a3" => Some(Self::A3),
            "a4" => Some(Self::A4),
            "a5" => Some(Self::A5),
            "a6" => Some(Self::A6),
            "b5" => Some(Self::B5),
            "letter" | "us-letter" | "na_letter" => Some(Self::Letter),
            "legal" | "us-legal" => Some(Self::Legal),
            "tabloid" | "ledger" => Some(Self::Tabloid),
            "executive" => Some(Self::Executive),
            _ => None,
        };
        if let Some(named) = named {
            return Ok(named);
        }

        let (body, scale) = if let Some(rest) = lower.strip_suffix("mm") {
            (rest, POINTS_PER_MM)
        } else if let Some(rest) = lower.strip_suffix("in") {
            (rest, POINTS_PER_INCH)
        } else if let Some(rest) = lower.strip_suffix("pt") {
            (rest, 1.0)
        } else {
            (lower.as_str(), 1.0)
        };
        let (w, h) = body
            .split_once('x')
            .ok_or_else(|| PrintError::InvalidOptions(format!("unknown paper size {text:?}")))?;
        let parse = |s: &str| {
            s.trim()
                .parse::<f64>()
                .map_err(|_| PrintError::InvalidOptions(format!("unknown paper size {text:?}")))
        };
        let paper = Self::Custom {
            width: parse(w)? * scale,
            height: parse(h)? * scale,
        };
        paper.validate()?;
        Ok(paper)
    }

    /// Reject a size that is not positive and finite.
    pub fn validate(&self) -> Result<(), PrintError> {
        let (w, h) = self.size();
        if !w.is_finite() || !h.is_finite() || w <= 0.0 || h <= 0.0 {
            return Err(PrintError::InvalidOptions(format!(
                "paper size {w}x{h}pt is not positive and finite"
            )));
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::expect_used, clippy::unwrap_used)]

    use super::*;

    #[test]
    fn a4_is_210_by_297_millimetres() {
        let (w, h) = PaperSize::A4.size();
        assert!((w - 595.276).abs() < 0.01, "{w}");
        assert!((h - 841.89).abs() < 0.01, "{h}");
    }

    #[test]
    fn landscape_swaps_the_axes() {
        let portrait = PaperSize::A4.rect(Orientation::Portrait);
        let landscape = PaperSize::A4.rect(Orientation::Landscape);
        assert_eq!(portrait.width(), landscape.height());
        assert_eq!(portrait.height(), landscape.width());
    }

    #[test]
    fn parse_accepts_names_and_explicit_sizes() {
        assert_eq!(PaperSize::parse("A4").unwrap(), PaperSize::A4);
        assert_eq!(PaperSize::parse(" letter ").unwrap(), PaperSize::Letter);
        let custom = PaperSize::parse("100x200pt").unwrap();
        assert_eq!(custom.size(), (100.0, 200.0));
        let inches = PaperSize::parse("8.5x11in").unwrap();
        assert_eq!(inches.size(), (612.0, 792.0));
        assert!(PaperSize::parse("nonsense").is_err());
        assert!(PaperSize::parse("0x10pt").is_err());
    }

    #[test]
    fn margins_take_the_wider_of_user_and_hardware() {
        let user = Margins::uniform(4.0);
        let hardware = Margins {
            left: 10.0,
            right: 2.0,
            top: 0.0,
            bottom: 18.0,
        };
        let combined = user.max_with(hardware);
        assert_eq!(combined.left, 10.0);
        assert_eq!(combined.right, 4.0);
        assert_eq!(combined.top, 4.0);
        assert_eq!(combined.bottom, 18.0);
    }

    #[test]
    fn quarter_turn_moves_top_margin_to_the_left_edge() {
        let m = Margins {
            left: 1.0,
            right: 2.0,
            top: 3.0,
            bottom: 4.0,
        };
        let turned = m.rotated_quarter_turns(1);
        assert_eq!(turned.left, 3.0);
        assert_eq!(turned.top, 2.0);
        assert_eq!(turned.right, 4.0);
        assert_eq!(turned.bottom, 1.0);
        assert_eq!(turned.rotated_quarter_turns(3), m);
    }
}