Skip to main content

laminapdf_render/
appearance.rs

1//! Page appearance (ADR 0024 §5, UI/UX plan §5.5): a page drawn in Sepia, Dark or High contrast
2//! instead of its own colours, apart from the UI theme.
3//!
4//! Neither backend can recolour as it paints: PDFium's colour scheme forces every fill to one
5//! colour, which flattens charts and tinted boxes, and hayro's painting device is private. So a
6//! tile is drawn as usual, then recoloured pixel by pixel, except where it shows an image or an
7//! annotation:
8//!
9//! - images keep their pixels: each backend lists where its own parser placed them, as quads in
10//!   tile pixels ([`Quad`]);
11//! - annotations keep their colours: the tile is drawn without annotations, then again with them
12//!   ([`Annotated`]); what they change comes from the second drawing, and so does the whole
13//!   rectangle of one that changes most of it, so text under a highlight keeps its colour.
14//!
15//! The colour maps use integer arithmetic only, so `@laminapdf/render`'s port gives the same
16//! bytes (`fixtures/appearance/colours.json` holds both to it). Text drawn as part of an image
17//! keeps its colours, and so does the area an image's quad covers when the image is clipped
18//! or transparent there.
19
20use crate::request::{BYTES_PER_PIXEL, Rgba8};
21
22/// How the page's colours are drawn. The default keeps them.
23///
24/// Added in 0.2.0.
25#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
26pub enum PageAppearance {
27    /// The page's own colours.
28    #[default]
29    Original,
30    /// Warm paper and brown ink, hue kept.
31    Sepia,
32    /// Light ink on dark paper: lightness inverted, hue kept.
33    Dark,
34    /// Two colours, usually the system's `CanvasText` and `Canvas`: the page's dark colours
35    /// toward `ink`, its light ones toward `paper`, mid-tones pushed toward `ink`.
36    HighContrast {
37        /// What black becomes.
38        ink: Rgba8,
39        /// What white becomes.
40        paper: Rgba8,
41    },
42}
43
44/// An appearance's paper (what white becomes) and ink (what black becomes).
45///
46/// Added in 0.2.0.
47#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
48pub struct PagePalette {
49    /// What white becomes.
50    pub paper: Rgba8,
51    /// What black becomes.
52    pub ink: Rgba8,
53}
54
55/// Sepia's paper and ink: `@laminapdf/tokens`' `PAGE_APPEARANCES.sepia` (`@laminapdf/render`'s
56/// tests hold both to the tokens).
57///
58/// Added in 0.2.0.
59pub const SEPIA: PagePalette = PagePalette {
60    paper: rgb(0xF4, 0xEC, 0xD8),
61    ink: rgb(0x3B, 0x2F, 0x20),
62};
63/// Dark's paper and ink: `@laminapdf/tokens`' `PAGE_APPEARANCES.dark`.
64///
65/// Added in 0.2.0.
66pub const DARK: PagePalette = PagePalette {
67    paper: rgb(0x22, 0x21, 0x1F),
68    ink: rgb(0xE6, 0xE1, 0xD8),
69};
70
71const fn rgb(r: u8, g: u8, b: u8) -> Rgba8 {
72    Rgba8 { r, g, b, a: 255 }
73}
74
75impl PageAppearance {
76    /// Whether this appearance changes any colour.
77    ///
78    /// Added in 0.2.0.
79    #[must_use]
80    pub const fn recolours(self) -> bool {
81        !matches!(self, Self::Original)
82    }
83
84    /// The colour `rgb` (straight, sRGB) becomes; alpha is never changed.
85    ///
86    /// Added in 0.2.0.
87    #[must_use]
88    pub fn recolour_rgb(self, rgb: [u8; 3]) -> [u8; 3] {
89        let [red, green, blue] = rgb;
90        let light = luma(red, green, blue);
91        match self {
92            Self::Original => rgb,
93            // Each channel from ink (0) to paper (255): black is ink, white is paper.
94            Self::Sepia => {
95                let PagePalette { paper, ink } = SEPIA;
96                [
97                    lerp(ink.r, paper.r, red),
98                    lerp(ink.g, paper.g, green),
99                    lerp(ink.b, paper.b, blue),
100                ]
101            }
102            // The lightness from ink (black) to paper (white), plus the colour's own offset from
103            // its lightness, so a blue bar stays bluish.
104            Self::Dark => {
105                let PagePalette { paper, ink } = DARK;
106                let shift = |from: u8, to: u8, channel: u8| {
107                    clamp(i32::from(lerp(from, to, light)) + i32::from(channel) - i32::from(light))
108                };
109                [
110                    shift(ink.r, paper.r, red),
111                    shift(ink.g, paper.g, green),
112                    shift(ink.b, paper.b, blue),
113                ]
114            }
115            // Squaring the lightness pushes greys toward ink, so light-grey text stays readable.
116            Self::HighContrast { ink, paper } => {
117                let at = div255(u32::from(light) * u32::from(light));
118                [
119                    lerp(ink.r, paper.r, at),
120                    lerp(ink.g, paper.g, at),
121                    lerp(ink.b, paper.b, at),
122                ]
123            }
124        }
125    }
126}
127
128/// Rec. 601 luma in 8.8 fixed point: `(77 r + 150 g + 29 b + 128) >> 8`, 0–255.
129fn luma(r: u8, g: u8, b: u8) -> u8 {
130    let v = (77 * u32::from(r) + 150 * u32::from(g) + 29 * u32::from(b) + 128) >> 8;
131    u8::try_from(v.min(255)).unwrap_or(u8::MAX)
132}
133
134/// `a` at `t` = 0 to `b` at `t` = 255, rounded.
135fn lerp(a: u8, b: u8, t: u8) -> u8 {
136    let t = u32::from(t);
137    div255(u32::from(a) * (255 - t) + u32::from(b) * t)
138}
139
140/// `round(v / 255)` for `v` ≤ 255 × 255.
141fn div255(v: u32) -> u8 {
142    u8::try_from(((v + 127) / 255).min(255)).unwrap_or(u8::MAX)
143}
144
145fn clamp(v: i32) -> u8 {
146    u8::try_from(v.clamp(0, 255)).unwrap_or(u8::MAX)
147}
148
149/// A quadrilateral in tile pixels: where an image's unit square or an annotation's rectangle lands.
150///
151/// Added in 0.2.0.
152#[derive(Debug, Clone, Copy, PartialEq)]
153pub struct Quad(pub [[f64; 2]; 4]);
154
155impl Quad {
156    /// The unit square under the affine `[a, b, c, d, e, f]` (to tile pixels).
157    ///
158    /// Added in 0.2.0.
159    #[must_use]
160    pub fn from_transform(matrix: [f64; 6]) -> Self {
161        let [xx, xy, yx, yy, dx, dy] = matrix;
162        let at = |x: f64, y: f64| [xx * x + yx * y + dx, xy * x + yy * y + dy];
163        Self([at(0.0, 0.0), at(1.0, 0.0), at(1.0, 1.0), at(0.0, 1.0)])
164    }
165
166    /// Whether the point is inside the quad (on its edge counts), whichever way it winds.
167    fn contains(&self, x: f64, y: f64) -> bool {
168        let [p0, p1, p2, p3] = self.0;
169        let side = |[ax, ay]: [f64; 2], [bx, by]: [f64; 2]| (bx - ax) * (y - ay) - (by - ay) * (x - ax);
170        let s = [side(p0, p1), side(p1, p2), side(p2, p3), side(p3, p0)];
171        s.iter().all(|&v| v >= 0.0) || s.iter().all(|&v| v <= 0.0)
172    }
173
174    /// The quad's pixel bounds inside a `width` × `height` tile, if it touches it.
175    fn bounds(&self, width: u32, height: u32) -> Option<(u32, u32, u32, u32)> {
176        let xs = self.0.map(|p| p[0]);
177        let ys = self.0.map(|p| p[1]);
178        let lo = |v: [f64; 4]| v.iter().copied().fold(f64::INFINITY, f64::min);
179        let hi = |v: [f64; 4]| v.iter().copied().fold(f64::NEG_INFINITY, f64::max);
180        let (x0, x1, y0, y1) = (lo(xs), hi(xs), lo(ys), hi(ys));
181        if !(x0.is_finite() && x1.is_finite() && y0.is_finite() && y1.is_finite()) {
182            return None;
183        }
184        // Pixel centres at i + 0.5: the first and last columns whose centre can be inside.
185        let first = |v: f64| (v - 0.5).ceil().max(0.0);
186        let last = |v: f64, n: u32| (v - 0.5).floor().min(f64::from(n) - 1.0);
187        let (cx0, cx1, cy0, cy1) = (first(x0), last(x1, width), first(y0), last(y1, height));
188        if cx0 > cx1 || cy0 > cy1 {
189            return None;
190        }
191        // In range by the clamps above: non-negative and below the tile's u32 sides.
192        #[expect(
193            clippy::cast_possible_truncation,
194            clippy::cast_sign_loss,
195            reason = "clamped to 0..width and 0..height"
196        )]
197        Some((cx0 as u32, cx1 as u32, cy0 as u32, cy1 as u32))
198    }
199
200    /// Whether the quad covers the centre of any pixel of a `width` × `height` tile (its bounding
201    /// box does, at least): a cheap test before work on what it covers.
202    ///
203    /// Added in 0.2.0.
204    #[must_use]
205    pub fn touches(&self, width: u32, height: u32) -> bool {
206        self.bounds(width, height).is_some()
207    }
208
209    /// The indices of the pixels whose centres are inside, in a tile `width` × `height`.
210    fn pixels(&self, width: u32, height: u32) -> Vec<usize> {
211        let Some((x0, x1, y0, y1)) = self.bounds(width, height) else {
212            return Vec::new();
213        };
214        let mut out = Vec::new();
215        for y in y0..=y1 {
216            for x in x0..=x1 {
217                if self.contains(f64::from(x) + 0.5, f64::from(y) + 0.5) {
218                    out.push(y as usize * width as usize + x as usize);
219                }
220            }
221        }
222        out
223    }
224}
225
226/// Copies the pixels of `plain` whose centres lie inside `quads` over `out` (both RGBA rows of
227/// `width` pixels): a backend that can't leave an annotation out of a drawing puts back the page
228/// as drawn without annotations over its rectangle.
229#[cfg(feature = "hayro")]
230pub(crate) fn restore_quads(out: &mut [u8], plain: &[u8], quads: &[Quad], width: u32) {
231    let height = u32::try_from(out.len() / BYTES_PER_PIXEL / (width.max(1) as usize)).unwrap_or(u32::MAX);
232    for quad in quads {
233        for pixel in quad.pixels(width, height) {
234            let at = pixel * BYTES_PER_PIXEL;
235            if let (Some(to), Some(from)) = (
236                out.get_mut(at..at + BYTES_PER_PIXEL),
237                plain.get(at..at + BYTES_PER_PIXEL),
238            ) {
239                to.copy_from_slice(from);
240            }
241        }
242    }
243}
244
245/// What a recoloured tile keeps as drawn.
246///
247/// Added in 0.2.0.
248#[derive(Debug, Clone, Copy, Default)]
249pub struct Kept<'a> {
250    /// Opaque images: every pixel inside is kept.
251    pub images: &'a [Quad],
252    /// Images that let the page show through (a soft mask, a mask, a blend mode other than
253    /// Normal): inside, only pixels that differ from `background` are kept, so the paper around
254    /// a masked shape is recoloured with the page.
255    pub see_through: &'a [Quad],
256    /// The tile's background (`None`: transparent).
257    pub background: Option<Rgba8>,
258    /// The tile drawn again with its annotations.
259    pub annotated: Option<Annotated<'a>>,
260}
261
262/// The same tile drawn with its annotations, and the rectangles kept whole.
263///
264/// Added in 0.2.0.
265#[derive(Debug, Clone, Copy)]
266pub struct Annotated<'a> {
267    /// The tile with annotations: same size as the one being recoloured.
268    pub pixels: &'a [u8],
269    /// In tile pixels, the rectangles of the annotations [`mostly_changed`] picked: every pixel
270    /// inside comes from `pixels`, so text under a highlight keeps its colour.
271    pub whole: &'a [Quad],
272}
273
274/// Which annotations change at least half of their rectangle (a highlight, a filled shape, a
275/// stamp), decided once for the page: `plain` and `annotated` are the whole page drawn small,
276/// without and with annotations, `width` pixels wide, and `rects` the rectangles in its pixels.
277/// Deciding per tile instead would split an annotation that two tiles share.
278///
279/// Added in 0.2.0.
280#[must_use]
281pub fn mostly_changed(rects: &[Quad], plain: &[u8], annotated: &[u8], width: u32) -> Vec<bool> {
282    let height = u32::try_from(plain.len() / (width as usize * BYTES_PER_PIXEL).max(1)).unwrap_or(u32::MAX);
283    rects
284        .iter()
285        .map(|rect| {
286            let inside = rect.pixels(width, height);
287            let differing = inside.iter().filter(|&&i| changed(plain, annotated, i)).count();
288            // Too small to cover a pixel of the small drawing: kept whole, as a highlight that
289            // small would be (a large page's 256 px drawing can miss a line of text).
290            inside.is_empty() || differing * 2 >= inside.len()
291        })
292        .collect()
293}
294
295/// Whether pixel `i` differs between the two drawings.
296fn changed(plain: &[u8], annotated: &[u8], i: usize) -> bool {
297    let at = i * BYTES_PER_PIXEL..(i + 1) * BYTES_PER_PIXEL;
298    plain.get(at.clone()) != annotated.get(at)
299}
300
301/// What happens to each pixel of a recoloured tile.
302#[derive(Debug, Clone, Copy, PartialEq, Eq)]
303enum Fate {
304    Recolour,
305    /// Inside an image: kept as drawn.
306    Keep,
307    /// Under an annotation: taken from the annotated drawing.
308    Annotation,
309}
310
311/// Recolours a tile drawn without annotations, in place: straight RGBA8 rows of `width × 4`.
312///
313/// Pixels of an opaque image keep their colour, and so do those of a see-through image that
314/// aren't the background. With [`Kept::annotated`], its whole rectangles and every other pixel
315/// the annotations change (an ink stroke, a line) come from the annotated drawing.
316///
317/// Added in 0.2.0.
318pub fn recolour_tile(appearance: PageAppearance, width: u32, pixels: &mut [u8], kept: &Kept<'_>) {
319    if !appearance.recolours() || width == 0 {
320        return;
321    }
322    let row = width as usize * BYTES_PER_PIXEL;
323    let height = u32::try_from(pixels.len() / row.max(1)).unwrap_or(u32::MAX);
324    let mut fates = vec![Fate::Recolour; width as usize * height as usize];
325    for i in kept.images.iter().flat_map(|quad| quad.pixels(width, height)) {
326        if let Some(fate) = fates.get_mut(i) {
327            *fate = Fate::Keep;
328        }
329    }
330    let background = kept.background.map_or([0; 4], |c| [c.r, c.g, c.b, c.a]);
331    for i in kept.see_through.iter().flat_map(|quad| quad.pixels(width, height)) {
332        let shows_paper = pixels.get(i * BYTES_PER_PIXEL..(i + 1) * BYTES_PER_PIXEL) == Some(&background[..]);
333        if let Some(fate) = fates.get_mut(i)
334            && !shows_paper
335        {
336            *fate = Fate::Keep;
337        }
338    }
339    let over = kept.annotated.map_or(&[][..], |a| a.pixels);
340    if let Some(annotated) = kept.annotated {
341        mark_annotations(&mut fates, pixels, annotated, width, height);
342    }
343    for (i, px) in pixels.as_chunks_mut::<BYTES_PER_PIXEL>().0.iter_mut().enumerate() {
344        match fates.get(i) {
345            Some(Fate::Keep) => {}
346            Some(Fate::Annotation) => {
347                if let Some(from) = over.get(i * BYTES_PER_PIXEL..(i + 1) * BYTES_PER_PIXEL) {
348                    px.copy_from_slice(from);
349                }
350            }
351            _ => {
352                let [red, green, blue, _] = px;
353                [*red, *green, *blue] = appearance.recolour_rgb([*red, *green, *blue]);
354            }
355        }
356    }
357}
358
359/// Marks the pixels taken from the annotated drawing: the whole rectangles, and every other
360/// pixel the annotations change.
361fn mark_annotations(fates: &mut [Fate], plain: &[u8], annotated: Annotated<'_>, width: u32, height: u32) {
362    for i in annotated.whole.iter().flat_map(|rect| rect.pixels(width, height)) {
363        if let Some(fate) = fates.get_mut(i) {
364            *fate = Fate::Annotation;
365        }
366    }
367    for (i, fate) in fates.iter_mut().enumerate() {
368        if changed(plain, annotated.pixels, i) {
369            *fate = Fate::Annotation;
370        }
371    }
372}
373
374#[cfg(test)]
375mod tests {
376    use super::{Annotated, DARK, Kept, PageAppearance, Quad, SEPIA, mostly_changed, recolour_tile};
377    use crate::Rgba8;
378
379    const WHITE: [u8; 3] = [255, 255, 255];
380    const BLACK: [u8; 3] = [0, 0, 0];
381
382    fn rgb(c: Rgba8) -> [u8; 3] {
383        [c.r, c.g, c.b]
384    }
385
386    #[test]
387    fn original_keeps_every_colour() {
388        assert_eq!(PageAppearance::Original.recolour_rgb([12, 34, 56]), [12, 34, 56]);
389    }
390
391    #[test]
392    fn white_becomes_paper_and_black_becomes_ink() {
393        for (appearance, palette) in [(PageAppearance::Sepia, SEPIA), (PageAppearance::Dark, DARK)] {
394            assert_eq!(appearance.recolour_rgb(WHITE), rgb(palette.paper), "{appearance:?}");
395            assert_eq!(appearance.recolour_rgb(BLACK), rgb(palette.ink), "{appearance:?}");
396        }
397    }
398
399    #[test]
400    fn dark_keeps_a_colours_tint() {
401        // A blue-grey bar stays bluer than it is red.
402        let [r, _, b] = PageAppearance::Dark.recolour_rgb([0x4E, 0x5A, 0x63]);
403        assert!(b > r);
404    }
405
406    #[test]
407    fn high_contrast_pushes_grey_toward_ink() {
408        let ink = Rgba8 {
409            r: 255,
410            g: 255,
411            b: 0,
412            a: 255,
413        };
414        let paper = Rgba8 {
415            r: 0,
416            g: 0,
417            b: 0,
418            a: 255,
419        };
420        let hc = PageAppearance::HighContrast { ink, paper };
421        assert_eq!(hc.recolour_rgb(BLACK), [255, 255, 0]);
422        assert_eq!(hc.recolour_rgb(WHITE), [0, 0, 0]);
423        // Mid grey lands nearer ink than paper.
424        assert!(hc.recolour_rgb([128, 128, 128])[0] > 128);
425    }
426
427    #[test]
428    fn image_pixels_and_alpha_are_kept() {
429        // 2 × 1: the left pixel under an image quad, the right one half transparent.
430        let mut pixels = [0, 0, 0, 255, 0, 0, 0, 128];
431        let quad = Quad::from_transform([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]);
432        let kept = Kept {
433            images: &[quad],
434            ..Kept::default()
435        };
436        recolour_tile(PageAppearance::Dark, 2, &mut pixels, &kept);
437        let ink = rgb(DARK.ink);
438        assert_eq!(pixels, [0, 0, 0, 255, ink[0], ink[1], ink[2], 128]);
439    }
440
441    #[test]
442    fn annotation_pixels_come_from_the_annotated_drawing() {
443        let mut pixels = [255, 255, 255, 255, 255, 255, 255, 255];
444        let annotated = [255, 255, 0, 255, 255, 255, 255, 255];
445        let annotated = Annotated {
446            pixels: &annotated,
447            whole: &[],
448        };
449        let kept = Kept {
450            annotated: Some(annotated),
451            ..Kept::default()
452        };
453        recolour_tile(PageAppearance::Dark, 2, &mut pixels, &kept);
454        let paper = rgb(DARK.paper);
455        assert_eq!(pixels, [255, 255, 0, 255, paper[0], paper[1], paper[2], 255]);
456    }
457
458    #[test]
459    fn a_mostly_changed_annotation_keeps_its_whole_rectangle() {
460        // 3 × 1 under one annotation: two pixels changed (yellow), the middle one black in both
461        // drawings, like a letter under a highlight.
462        let mut pixels = [255, 255, 255, 255, 0, 0, 0, 255, 255, 255, 255, 255];
463        let over = [255, 255, 0, 255, 0, 0, 0, 255, 255, 255, 0, 255];
464        let rect = Quad::from_transform([3.0, 0.0, 0.0, 1.0, 0.0, 0.0]);
465        let plain = pixels;
466        assert_eq!(mostly_changed(&[rect], &plain, &over, 3), [true]);
467        let annotated = Annotated {
468            pixels: &over,
469            whole: &[rect],
470        };
471        let kept = Kept {
472            annotated: Some(annotated),
473            ..Kept::default()
474        };
475        recolour_tile(PageAppearance::Dark, 3, &mut pixels, &kept);
476        assert_eq!(pixels, over);
477    }
478
479    #[test]
480    fn a_see_through_image_lets_the_paper_be_recoloured() {
481        // 2 × 1 under a masked image: a white (background) pixel and a blue one.
482        let mut pixels = [255, 255, 255, 255, 40, 120, 200, 255];
483        let quad = Quad::from_transform([2.0, 0.0, 0.0, 1.0, 0.0, 0.0]);
484        let kept = Kept {
485            see_through: &[quad],
486            background: Some(Rgba8::WHITE),
487            ..Kept::default()
488        };
489        recolour_tile(PageAppearance::Dark, 2, &mut pixels, &kept);
490        let paper = rgb(DARK.paper);
491        assert_eq!(pixels, [paper[0], paper[1], paper[2], 255, 40, 120, 200, 255]);
492    }
493
494    #[test]
495    fn a_quad_outside_the_tile_keeps_nothing() {
496        let mut pixels = [0, 0, 0, 255];
497        let quad = Quad::from_transform([1.0, 0.0, 0.0, 1.0, 5.0, 5.0]);
498        let kept = Kept {
499            images: &[quad],
500            ..Kept::default()
501        };
502        recolour_tile(PageAppearance::Sepia, 1, &mut pixels, &kept);
503        assert_eq!(pixels[..3], rgb(SEPIA.ink));
504    }
505}