Skip to main content

fc_ui/capabilities/media/
qr_code.rs

1//! QR code generator rendering as colored quads.
2
3use gpui::{prelude::FluentBuilder as _, *};
4use qrcode::types::EcLevel;
5use qrcode::QrCode;
6
7use crate::capabilities::foundation::theme::use_theme;
8
9#[derive(Clone)]
10struct QRPaintData {
11    modules: Vec<Vec<bool>>,
12    fg_color: Hsla,
13    bg_color: Hsla,
14}
15
16#[derive(IntoElement)]
17pub struct QRCodeComponent {
18    data: SharedString,
19    size: Pixels,
20    fg_color: Option<Hsla>,
21    bg_color: Option<Hsla>,
22    error_correction: EcLevel,
23    style: StyleRefinement,
24}
25
26impl QRCodeComponent {
27    pub fn new(data: impl Into<SharedString>) -> Self {
28        Self {
29            data: data.into(),
30            size: px(200.0),
31            fg_color: None,
32            bg_color: None,
33            error_correction: EcLevel::M,
34            style: StyleRefinement::default(),
35        }
36    }
37
38    pub fn size(mut self, size: Pixels) -> Self {
39        self.size = size;
40        self
41    }
42
43    pub fn fg_color(mut self, color: Hsla) -> Self {
44        self.fg_color = Some(color);
45        self
46    }
47
48    pub fn bg_color(mut self, color: Hsla) -> Self {
49        self.bg_color = Some(color);
50        self
51    }
52
53    pub fn error_correction(mut self, level: EcLevel) -> Self {
54        self.error_correction = level;
55        self
56    }
57}
58
59impl Styled for QRCodeComponent {
60    fn style(&mut self) -> &mut StyleRefinement {
61        &mut self.style
62    }
63}
64
65fn generate_modules(data: &str, ec_level: EcLevel) -> Vec<Vec<bool>> {
66    match QrCode::with_error_correction_level(data, ec_level) {
67        Ok(code) => {
68            let width = code.width();
69            let colors = code.into_colors();
70            let mut grid = Vec::with_capacity(width);
71            for row in 0..width {
72                let mut row_vec = Vec::with_capacity(width);
73                for col in 0..width {
74                    let idx = row * width + col;
75                    row_vec.push(colors[idx] == qrcode::Color::Dark);
76                }
77                grid.push(row_vec);
78            }
79            grid
80        }
81        Err(_) => vec![vec![false; 21]; 21],
82    }
83}
84
85impl RenderOnce for QRCodeComponent {
86    fn render(self, _window: &mut Window, cx: &mut App) -> impl IntoElement {
87        let theme = use_theme(cx);
88        let user_style = self.style;
89
90        let fg = self.fg_color.unwrap_or(theme.tokens.foreground);
91        let bg = self.bg_color.unwrap_or(theme.tokens.background);
92
93        let modules = generate_modules(&self.data, self.error_correction);
94        let paint_data = QRPaintData {
95            modules,
96            fg_color: fg,
97            bg_color: bg,
98        };
99
100        let qr_size = self.size;
101
102        div()
103            .w(qr_size)
104            .h(qr_size)
105            .child(
106                canvas(
107                    move |_, _, _| paint_data,
108                    move |bounds, data, window, _cx| {
109                        if data.modules.is_empty() {
110                            return;
111                        }
112
113                        let module_count = data.modules.len();
114                        let module_size_w = bounds.size.width / px(1.0) / module_count as f32;
115                        let module_size_h = bounds.size.height / px(1.0) / module_count as f32;
116                        let module_size = module_size_w.min(module_size_h);
117
118                        let total_w = module_size * module_count as f32;
119                        let total_h = module_size * module_count as f32;
120                        let offset_x = (bounds.size.width / px(1.0) - total_w) * 0.5;
121                        let offset_y = (bounds.size.height / px(1.0) - total_h) * 0.5;
122
123                        window.paint_quad(fill(bounds, data.bg_color));
124
125                        for (row_idx, row) in data.modules.iter().enumerate() {
126                            for (col_idx, &is_dark) in row.iter().enumerate() {
127                                if is_dark {
128                                    let x =
129                                        bounds.left() + px(offset_x + col_idx as f32 * module_size);
130                                    let y =
131                                        bounds.top() + px(offset_y + row_idx as f32 * module_size);
132                                    let cell_bounds = Bounds::new(
133                                        point(x, y),
134                                        size(px(module_size), px(module_size)),
135                                    );
136                                    window.paint_quad(fill(cell_bounds, data.fg_color));
137                                }
138                            }
139                        }
140                    },
141                )
142                .size_full(),
143            )
144            .map(|this| {
145                let mut el = this;
146                el.style().refine(&user_style);
147                el
148            })
149    }
150}