Skip to main content

cosmic_applet_avestruz/views/components/
qr_code.rs

1// SPDX-License-Identifier: MIT
2
3//! A QR code, as a picture: for a wallet on another device to scan.
4//!
5//! Always dark on white, whatever the theme: that is what scanners expect,
6//! and a code in the theme's colours may not have the contrast.
7
8use cosmic::widget::image::Handle;
9use qrcode::{Color, QrCode};
10
11/// How many pixels a side each module of the code is in the picture. The
12/// view scales the picture; this only has to be enough for the edges to
13/// stay sharp.
14const MODULE_PIXELS: usize = 8;
15
16/// How many modules of white are left around the code. A scanner needs four
17/// to tell where the code ends.
18const QUIET_MODULES: usize = 4;
19
20/// The code for `data` as square RGBA pixels: how many a side, and the
21/// pixels. `None` if `data` is more than a QR code holds.
22fn pixels(data: &str) -> Option<(usize, Vec<u8>)> {
23    let code = QrCode::new(data).ok()?;
24    let modules = code.width();
25    let dark: Vec<bool> = code.into_colors().into_iter().map(|color| color == Color::Dark).collect();
26
27    let side = (modules + 2 * QUIET_MODULES) * MODULE_PIXELS;
28    let mut pixels = vec![255_u8; side * side * 4];
29    for (index, _) in dark.iter().enumerate().filter(|(_, dark)| **dark) {
30        let (left, top) = ((index % modules + QUIET_MODULES) * MODULE_PIXELS, (index / modules + QUIET_MODULES) * MODULE_PIXELS);
31        for y in top..top + MODULE_PIXELS {
32            let row = (y * side + left) * 4;
33            if let Some(row) = pixels.get_mut(row..row + MODULE_PIXELS * 4) {
34                // Black, and as opaque as the white around it.
35                row.as_chunks_mut::<4>().0.iter_mut().for_each(|pixel| *pixel = [0, 0, 0, 255]);
36            }
37        }
38    }
39    Some((side, pixels))
40}
41
42/// The QR code for `data`, as a picture. `None` if `data` is more than a
43/// code holds.
44pub fn qr_code(data: &str) -> Option<Handle> {
45    let (side, pixels) = pixels(data)?;
46    let side = u32::try_from(side).ok()?;
47    Some(Handle::from_rgba(side, side, pixels))
48}
49
50#[cfg(test)]
51mod tests {
52    use super::{MODULE_PIXELS, QUIET_MODULES, pixels};
53
54    /// Whether the pixel at (`x`, `y`) of a picture `side` wide is dark.
55    fn is_dark(pixels: &[u8], side: usize, x: usize, y: usize) -> bool {
56        pixels[(y * side + x) * 4] == 0
57    }
58
59    #[test]
60    fn a_code_is_square_dark_on_white_with_room_around_it() {
61        // A short text makes the smallest code: 21 modules a side.
62        let (side, pixels) = pixels("LIGHTNING:LNBC1").unwrap();
63        assert_eq!(side, (21 + 2 * QUIET_MODULES) * MODULE_PIXELS);
64        assert_eq!(pixels.len(), side * side * 4);
65        assert!(pixels.chunks_exact(4).all(|pixel| pixel[3] == 255), "nothing shows through");
66
67        // The margin is white all the way round.
68        let margin = QUIET_MODULES * MODULE_PIXELS;
69        assert!((0..side).all(|at| !is_dark(&pixels, side, at, margin - 1) && !is_dark(&pixels, side, margin - 1, at)));
70        assert!((0..side).all(|at| !is_dark(&pixels, side, at, side - margin) && !is_dark(&pixels, side, side - margin, at)));
71
72        // Every code starts with a finder pattern in its top left corner: a
73        // dark ring seven modules wide, a light ring inside it, a dark middle.
74        let module = |x: usize, y: usize| is_dark(&pixels, side, margin + x * MODULE_PIXELS + 3, margin + y * MODULE_PIXELS + 3);
75        assert!((0..7).all(|at| module(at, 0) && module(0, at) && module(at, 6) && module(6, at)));
76        assert!((1..6).all(|at| !module(at, 1) && !module(1, at)));
77        assert!(module(3, 3));
78    }
79
80    #[test]
81    fn a_longer_text_makes_a_larger_code_and_too_long_a_text_none() {
82        let (short, _) = pixels("LNBC1").unwrap();
83        let (long, _) = pixels(&"LNBC210N1PJQ9XYZ".repeat(20)).unwrap();
84        assert!(long > short);
85        assert_eq!(pixels(&"x".repeat(10_000)), None);
86    }
87}