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#[derive(Debug, Clone, Copy, Default)]
230pub struct Kept<'a> {
231 pub images: &'a [Quad],
233 pub see_through: &'a [Quad],
237 pub background: Option<Rgba8>,
239 pub annotated: Option<Annotated<'a>>,
241}
242
243#[derive(Debug, Clone, Copy)]
247pub struct Annotated<'a> {
248 pub pixels: &'a [u8],
250 pub whole: &'a [Quad],
253}
254
255#[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 inside.is_empty() || differing * 2 >= inside.len()
272 })
273 .collect()
274}
275
276fn 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
284enum Fate {
285 Recolour,
286 Keep,
288 Annotation,
290}
291
292pub 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
340fn 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 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 assert!(hc.recolour_rgb([128, 128, 128])[0] > 128);
406 }
407
408 #[test]
409 fn image_pixels_and_alpha_are_kept() {
410 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 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 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}