fractal/contrib/
qr_code.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
// Taken from https://gitlab.gnome.org/msandova/trinket/-/blob/master/src/qr_code.rs
// All credit goes to Maximiliano

use gettextrs::gettext;
use gtk::{glib, prelude::*, subclass::prelude::*};

pub(crate) mod imp {
    use std::cell::{Cell, RefCell};

    use gtk::{gdk, graphene};

    use super::*;

    #[derive(Debug, glib::Properties)]
    #[properties(wrapper_type = super::QRCode)]
    pub struct QRCode {
        pub data: RefCell<QRCodeData>,
        /// The block size of this QR Code.
        ///
        /// Determines the size of the widget.
        #[property(get, set = Self::set_block_size)]
        pub block_size: Cell<u32>,
    }

    impl Default for QRCode {
        fn default() -> Self {
            Self {
                data: Default::default(),
                block_size: Cell::new(6),
            }
        }
    }

    #[glib::object_subclass]
    impl ObjectSubclass for QRCode {
        const NAME: &'static str = "TriQRCode";
        type Type = super::QRCode;
        type ParentType = gtk::Widget;

        fn class_init(klass: &mut Self::Class) {
            klass.set_css_name("qrcode");
            klass.set_accessible_role(gtk::AccessibleRole::Img);
        }
    }

    #[glib::derived_properties]
    impl ObjectImpl for QRCode {
        fn constructed(&self) {
            self.parent_constructed();

            self.obj()
                .update_property(&[gtk::accessible::Property::Label(&gettext("QR Code"))]);
        }
    }

    impl WidgetImpl for QRCode {
        fn snapshot(&self, snapshot: &gtk::Snapshot) {
            let obj = self.obj();
            let square_width = obj.width() as f32 / self.data.borrow().width as f32;
            let square_height = obj.height() as f32 / self.data.borrow().height as f32;

            self.data
                .borrow()
                .items
                .iter()
                .enumerate()
                .for_each(|(y, line)| {
                    line.iter().enumerate().for_each(|(x, is_dark)| {
                        let color = if *is_dark {
                            gdk::RGBA::BLACK
                        } else {
                            gdk::RGBA::WHITE
                        };
                        let position = graphene::Rect::new(
                            (x as f32) * square_width,
                            (y as f32) * square_height,
                            square_width,
                            square_height,
                        );

                        snapshot.append_color(&color, &position);
                    });
                });
        }

        fn measure(&self, orientation: gtk::Orientation, for_size: i32) -> (i32, i32, i32, i32) {
            let stride = i32::try_from(self.obj().block_size()).expect("block size fits into i32");

            let minimum = match orientation {
                gtk::Orientation::Horizontal => self.data.borrow().width * stride,
                gtk::Orientation::Vertical => self.data.borrow().height * stride,
                _ => unreachable!(),
            };
            let natural = std::cmp::max(for_size, minimum);
            (minimum, natural, -1, -1)
        }
    }

    impl QRCode {
        /// Sets the block size of this QR Code.
        fn set_block_size(&self, block_size: u32) {
            self.block_size.set(std::cmp::max(block_size, 1));

            let obj = self.obj();
            obj.queue_draw();
            obj.queue_resize();
        }
    }
}

glib::wrapper! {
    /// A widget that display a QR Code.
    ///
    /// The QR code of [`QRCode`] is set with the [QRCode::set_bytes()]
    /// method. It is recommended for a QR Code to have a quiet zone, in most
    /// contexts, widgets already count with such a margin.
    ///
    /// The code can be themed via css, where a recommended quiet-zone
    /// can be as a padding:
    ///
    /// ```css
    /// qrcode {
    ///     color: black;
    ///     background: white;
    ///     padding: 24px;  /* 4 ⨉ block-size */
    /// }
    /// ```
    pub struct QRCode(ObjectSubclass<imp::QRCode>)
        @extends gtk::Widget, @implements gtk::Accessible;
}

impl QRCode {
    /// Creates a new [`QRCode`].
    pub fn new() -> Self {
        glib::Object::new()
    }

    /// Creates a new [`QRCode`] with a QR code generated from `bytes`.
    pub fn from_bytes(bytes: &[u8]) -> Self {
        let qrcode = Self::new();
        qrcode.set_bytes(bytes);

        qrcode
    }

    /// Sets the displayed code of `self` to a QR code generated from `bytes`.
    pub fn set_bytes(&self, bytes: &[u8]) {
        let data = QRCodeData::try_from(bytes).unwrap_or_else(|_| {
            glib::g_warning!(None, "Could not load QRCode from bytes");
            Default::default()
        });
        self.imp().data.replace(data);

        self.queue_draw();
        self.queue_resize();
    }

    /// Set the `QrCode` to be displayed.
    pub fn set_qrcode(&self, qrcode: qrcode::QrCode) {
        self.imp().data.replace(QRCodeData::from(qrcode));

        self.queue_draw();
        self.queue_resize();
    }
}

impl Default for QRCodeData {
    fn default() -> Self {
        Self::try_from("".as_bytes()).unwrap()
    }
}

#[derive(Debug, Clone)]
pub struct QRCodeData {
    pub width: i32,
    pub height: i32,
    pub items: Vec<Vec<bool>>,
}

impl TryFrom<&[u8]> for QRCodeData {
    type Error = qrcode::types::QrError;

    fn try_from(data: &[u8]) -> Result<Self, Self::Error> {
        Ok(qrcode::QrCode::new(data)?.into())
    }
}

impl From<qrcode::QrCode> for QRCodeData {
    fn from(code: qrcode::QrCode) -> Self {
        let items = code
            .render::<char>()
            .quiet_zone(false)
            .module_dimensions(1, 1)
            .build()
            .split('\n')
            .map(|line| {
                line.chars()
                    .map(|c| !c.is_whitespace())
                    .collect::<Vec<bool>>()
            })
            .collect::<Vec<Vec<bool>>>();

        let size = items
            .len()
            .try_into()
            .expect("count of items fits into i32");
        Self {
            width: size,
            height: size,
            items,
        }
    }
}