1use crate::request::{BYTES_PER_PIXEL, Rgba8};
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
26pub enum PageAppearance {
27 #[default]
29 Original,
30 Sepia,
32 Dark,
34 HighContrast {
37 ink: Rgba8,
39 paper: Rgba8,
41 },
42}
43
44#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
48pub struct PagePalette {
49 pub paper: Rgba8,
51 pub ink: Rgba8,
53}
54
55pub const SEPIA: PagePalette = PagePalette {
60 paper: rgb(0xF4, 0xEC, 0xD8),
61 ink: rgb(0x3B, 0x2F, 0x20),
62};
63pub 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 #[must_use]
80 pub const fn recolours(self) -> bool {
81 !matches!(self, Self::Original)
82 }
83
84 #[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 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 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 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
128fn 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
134fn 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
140fn 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#[derive(Debug, Clone, Copy, PartialEq)]
153pub struct Quad(pub [[f64; 2]; 4]);
154
155impl Quad {
156 #[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 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 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 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 #[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 #[must_use]
205 pub fn touches(&self, width: u32, height: u32) -> bool {
206 self.bounds(width, height).is_some()
207 }
208
209 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#[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#[derive(Debug, Clone, Copy, Default)]
249pub struct Kept<'a> {
250 pub images: &'a [Quad],
252 pub see_through: &'a [Quad],
256 pub background: Option<Rgba8>,
258 pub annotated: Option<Annotated<'a>>,
260}
261
262#[derive(Debug, Clone, Copy)]
266pub struct Annotated<'a> {
267 pub pixels: &'a [u8],
269 pub whole: &'a [Quad],
272}
273
274#[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 inside.is_empty() || differing * 2 >= inside.len()
291 })
292 .collect()
293}
294
295fn 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
303enum Fate {
304 Recolour,
305 Keep,
307 Annotation,
309}
310
311pub 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
359fn 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 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 assert!(hc.recolour_rgb([128, 128, 128])[0] > 128);
425 }
426
427 #[test]
428 fn image_pixels_and_alpha_are_kept() {
429 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 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 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}