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/// What a recoloured tile keeps as drawn.
227///
228/// Added in 0.2.0.
229#[derive(Debug, Clone, Copy, Default)]
230pub struct Kept<'a> {
231    /// Opaque images: every pixel inside is kept.
232    pub images: &'a [Quad],
233    /// Images that let the page show through (a soft mask, a mask, a blend mode other than
234    /// Normal): inside, only pixels that differ from `background` are kept, so the paper around
235    /// a masked shape is recoloured with the page.
236    pub see_through: &'a [Quad],
237    /// The tile's background (`None`: transparent).
238    pub background: Option<Rgba8>,
239    /// The tile drawn again with its annotations.
240    pub annotated: Option<Annotated<'a>>,
241}
242
243/// The same tile drawn with its annotations, and the rectangles kept whole.
244///
245/// Added in 0.2.0.
246#[derive(Debug, Clone, Copy)]
247pub struct Annotated<'a> {
248    /// The tile with annotations: same size as the one being recoloured.
249    pub pixels: &'a [u8],
250    /// In tile pixels, the rectangles of the annotations [`mostly_changed`] picked: every pixel
251    /// inside comes from `pixels`, so text under a highlight keeps its colour.
252    pub whole: &'a [Quad],
253}
254
255/// Which annotations change at least half of their rectangle (a highlight, a filled shape, a
256/// stamp), decided once for the page: `plain` and `annotated` are the whole page drawn small,
257/// without and with annotations, `width` pixels wide, and `rects` the rectangles in its pixels.
258/// Deciding per tile instead would split an annotation that two tiles share.
259///
260/// Added in 0.2.0.
261#[must_use]
262pub fn mostly_changed(rects: &[Quad], plain: &[u8], annotated: &[u8], width: u32) -> Vec<bool> {
263    let height = u32::try_from(plain.len() / (width as usize * BYTES_PER_PIXEL).max(1)).unwrap_or(u32::MAX);
264    rects
265        .iter()
266        .map(|rect| {
267            let inside = rect.pixels(width, height);
268            let differing = inside.iter().filter(|&&i| changed(plain, annotated, i)).count();
269            // Too small to cover a pixel of the small drawing: kept whole, as a highlight that
270            // small would be (a large page's 256 px drawing can miss a line of text).
271            inside.is_empty() || differing * 2 >= inside.len()
272        })
273        .collect()
274}
275
276/// Whether pixel `i` differs between the two drawings.
277fn changed(plain: &[u8], annotated: &[u8], i: usize) -> bool {
278    let at = i * BYTES_PER_PIXEL..(i + 1) * BYTES_PER_PIXEL;
279    plain.get(at.clone()) != annotated.get(at)
280}
281
282/// What happens to each pixel of a recoloured tile.
283#[derive(Debug, Clone, Copy, PartialEq, Eq)]
284enum Fate {
285    Recolour,
286    /// Inside an image: kept as drawn.
287    Keep,
288    /// Under an annotation: taken from the annotated drawing.
289    Annotation,
290}
291
292/// Recolours a tile drawn without annotations, in place: straight RGBA8 rows of `width × 4`.
293///
294/// Pixels of an opaque image keep their colour, and so do those of a see-through image that
295/// aren't the background. With [`Kept::annotated`], its whole rectangles and every other pixel
296/// the annotations change (an ink stroke, a line) come from the annotated drawing.
297///
298/// Added in 0.2.0.
299pub fn recolour_tile(appearance: PageAppearance, width: u32, pixels: &mut [u8], kept: &Kept<'_>) {
300    if !appearance.recolours() || width == 0 {
301        return;
302    }
303    let row = width as usize * BYTES_PER_PIXEL;
304    let height = u32::try_from(pixels.len() / row.max(1)).unwrap_or(u32::MAX);
305    let mut fates = vec![Fate::Recolour; width as usize * height as usize];
306    for i in kept.images.iter().flat_map(|quad| quad.pixels(width, height)) {
307        if let Some(fate) = fates.get_mut(i) {
308            *fate = Fate::Keep;
309        }
310    }
311    let background = kept.background.map_or([0; 4], |c| [c.r, c.g, c.b, c.a]);
312    for i in kept.see_through.iter().flat_map(|quad| quad.pixels(width, height)) {
313        let shows_paper = pixels.get(i * BYTES_PER_PIXEL..(i + 1) * BYTES_PER_PIXEL) == Some(&background[..]);
314        if let Some(fate) = fates.get_mut(i)
315            && !shows_paper
316        {
317            *fate = Fate::Keep;
318        }
319    }
320    let over = kept.annotated.map_or(&[][..], |a| a.pixels);
321    if let Some(annotated) = kept.annotated {
322        mark_annotations(&mut fates, pixels, annotated, width, height);
323    }
324    for (i, px) in pixels.as_chunks_mut::<BYTES_PER_PIXEL>().0.iter_mut().enumerate() {
325        match fates.get(i) {
326            Some(Fate::Keep) => {}
327            Some(Fate::Annotation) => {
328                if let Some(from) = over.get(i * BYTES_PER_PIXEL..(i + 1) * BYTES_PER_PIXEL) {
329                    px.copy_from_slice(from);
330                }
331            }
332            _ => {
333                let [red, green, blue, _] = px;
334                [*red, *green, *blue] = appearance.recolour_rgb([*red, *green, *blue]);
335            }
336        }
337    }
338}
339
340/// Marks the pixels taken from the annotated drawing: the whole rectangles, and every other
341/// pixel the annotations change.
342fn mark_annotations(fates: &mut [Fate], plain: &[u8], annotated: Annotated<'_>, width: u32, height: u32) {
343    for i in annotated.whole.iter().flat_map(|rect| rect.pixels(width, height)) {
344        if let Some(fate) = fates.get_mut(i) {
345            *fate = Fate::Annotation;
346        }
347    }
348    for (i, fate) in fates.iter_mut().enumerate() {
349        if changed(plain, annotated.pixels, i) {
350            *fate = Fate::Annotation;
351        }
352    }
353}
354
355#[cfg(test)]
356mod tests {
357    use super::{Annotated, DARK, Kept, PageAppearance, Quad, SEPIA, mostly_changed, recolour_tile};
358    use crate::Rgba8;
359
360    const WHITE: [u8; 3] = [255, 255, 255];
361    const BLACK: [u8; 3] = [0, 0, 0];
362
363    fn rgb(c: Rgba8) -> [u8; 3] {
364        [c.r, c.g, c.b]
365    }
366
367    #[test]
368    fn original_keeps_every_colour() {
369        assert_eq!(PageAppearance::Original.recolour_rgb([12, 34, 56]), [12, 34, 56]);
370    }
371
372    #[test]
373    fn white_becomes_paper_and_black_becomes_ink() {
374        for (appearance, palette) in [(PageAppearance::Sepia, SEPIA), (PageAppearance::Dark, DARK)] {
375            assert_eq!(appearance.recolour_rgb(WHITE), rgb(palette.paper), "{appearance:?}");
376            assert_eq!(appearance.recolour_rgb(BLACK), rgb(palette.ink), "{appearance:?}");
377        }
378    }
379
380    #[test]
381    fn dark_keeps_a_colours_tint() {
382        // A blue-grey bar stays bluer than it is red.
383        let [r, _, b] = PageAppearance::Dark.recolour_rgb([0x4E, 0x5A, 0x63]);
384        assert!(b > r);
385    }
386
387    #[test]
388    fn high_contrast_pushes_grey_toward_ink() {
389        let ink = Rgba8 {
390            r: 255,
391            g: 255,
392            b: 0,
393            a: 255,
394        };
395        let paper = Rgba8 {
396            r: 0,
397            g: 0,
398            b: 0,
399            a: 255,
400        };
401        let hc = PageAppearance::HighContrast { ink, paper };
402        assert_eq!(hc.recolour_rgb(BLACK), [255, 255, 0]);
403        assert_eq!(hc.recolour_rgb(WHITE), [0, 0, 0]);
404        // Mid grey lands nearer ink than paper.
405        assert!(hc.recolour_rgb([128, 128, 128])[0] > 128);
406    }
407
408    #[test]
409    fn image_pixels_and_alpha_are_kept() {
410        // 2 × 1: the left pixel under an image quad, the right one half transparent.
411        let mut pixels = [0, 0, 0, 255, 0, 0, 0, 128];
412        let quad = Quad::from_transform([1.0, 0.0, 0.0, 1.0, 0.0, 0.0]);
413        let kept = Kept {
414            images: &[quad],
415            ..Kept::default()
416        };
417        recolour_tile(PageAppearance::Dark, 2, &mut pixels, &kept);
418        let ink = rgb(DARK.ink);
419        assert_eq!(pixels, [0, 0, 0, 255, ink[0], ink[1], ink[2], 128]);
420    }
421
422    #[test]
423    fn annotation_pixels_come_from_the_annotated_drawing() {
424        let mut pixels = [255, 255, 255, 255, 255, 255, 255, 255];
425        let annotated = [255, 255, 0, 255, 255, 255, 255, 255];
426        let annotated = Annotated {
427            pixels: &annotated,
428            whole: &[],
429        };
430        let kept = Kept {
431            annotated: Some(annotated),
432            ..Kept::default()
433        };
434        recolour_tile(PageAppearance::Dark, 2, &mut pixels, &kept);
435        let paper = rgb(DARK.paper);
436        assert_eq!(pixels, [255, 255, 0, 255, paper[0], paper[1], paper[2], 255]);
437    }
438
439    #[test]
440    fn a_mostly_changed_annotation_keeps_its_whole_rectangle() {
441        // 3 × 1 under one annotation: two pixels changed (yellow), the middle one black in both
442        // drawings, like a letter under a highlight.
443        let mut pixels = [255, 255, 255, 255, 0, 0, 0, 255, 255, 255, 255, 255];
444        let over = [255, 255, 0, 255, 0, 0, 0, 255, 255, 255, 0, 255];
445        let rect = Quad::from_transform([3.0, 0.0, 0.0, 1.0, 0.0, 0.0]);
446        let plain = pixels;
447        assert_eq!(mostly_changed(&[rect], &plain, &over, 3), [true]);
448        let annotated = Annotated {
449            pixels: &over,
450            whole: &[rect],
451        };
452        let kept = Kept {
453            annotated: Some(annotated),
454            ..Kept::default()
455        };
456        recolour_tile(PageAppearance::Dark, 3, &mut pixels, &kept);
457        assert_eq!(pixels, over);
458    }
459
460    #[test]
461    fn a_see_through_image_lets_the_paper_be_recoloured() {
462        // 2 × 1 under a masked image: a white (background) pixel and a blue one.
463        let mut pixels = [255, 255, 255, 255, 40, 120, 200, 255];
464        let quad = Quad::from_transform([2.0, 0.0, 0.0, 1.0, 0.0, 0.0]);
465        let kept = Kept {
466            see_through: &[quad],
467            background: Some(Rgba8::WHITE),
468            ..Kept::default()
469        };
470        recolour_tile(PageAppearance::Dark, 2, &mut pixels, &kept);
471        let paper = rgb(DARK.paper);
472        assert_eq!(pixels, [paper[0], paper[1], paper[2], 255, 40, 120, 200, 255]);
473    }
474
475    #[test]
476    fn a_quad_outside_the_tile_keeps_nothing() {
477        let mut pixels = [0, 0, 0, 255];
478        let quad = Quad::from_transform([1.0, 0.0, 0.0, 1.0, 5.0, 5.0]);
479        let kept = Kept {
480            images: &[quad],
481            ..Kept::default()
482        };
483        recolour_tile(PageAppearance::Sepia, 1, &mut pixels, &kept);
484        assert_eq!(pixels[..3], rgb(SEPIA.ink));
485    }
486}