deltachat/
qr_code_generator.rs

1//! # QR code generation module.
2
3use anyhow::Result;
4use base64::Engine as _;
5use qrcodegen::{QrCode, QrCodeEcc};
6
7use crate::blob::BlobObject;
8use crate::chat::{Chat, ChatId};
9use crate::color::color_int_to_hex_string;
10use crate::config::Config;
11use crate::contact::{Contact, ContactId};
12use crate::context::Context;
13use crate::qr::{self, Qr};
14use crate::securejoin;
15use crate::stock_str::{self, backup_transfer_qr};
16
17/// Create a QR code from any input data.
18pub fn create_qr_svg(qrcode_content: &str) -> Result<String> {
19    let all_size = 512.0;
20    let qr_code_size = 416.0;
21    let logo_size = 96.0;
22
23    let qr = QrCode::encode_text(qrcode_content, QrCodeEcc::Medium)?;
24    let mut svg = String::with_capacity(28000);
25    let mut w = tagger::new(&mut svg);
26
27    w.elem("svg", |d| {
28        d.attr("xmlns", "http://www.w3.org/2000/svg")?;
29        d.attr("viewBox", format_args!("0 0 {all_size} {all_size}"))?;
30        d.attr("xmlns:xlink", "http://www.w3.org/1999/xlink")?; // required for enabling xlink:href on browsers
31        Ok(())
32    })?
33    .build(|w| {
34        // background
35        w.single("rect", |d| {
36            d.attr("x", 0)?;
37            d.attr("y", 0)?;
38            d.attr("width", all_size)?;
39            d.attr("height", all_size)?;
40            d.attr("style", "fill:#ffffff")?;
41            Ok(())
42        })?;
43        // QR code
44        w.elem("g", |d| {
45            d.attr(
46                "transform",
47                format!(
48                    "translate({},{})",
49                    (all_size - qr_code_size) / 2.0,
50                    ((all_size - qr_code_size) / 2.0)
51                ),
52            )
53        })?
54        .build(|w| {
55            w.single("path", |d| {
56                let mut path_data = String::with_capacity(0);
57                let scale = qr_code_size / qr.size() as f32;
58
59                for y in 0..qr.size() {
60                    for x in 0..qr.size() {
61                        if qr.get_module(x, y) {
62                            path_data += &format!("M{x},{y}h1v1h-1z");
63                        }
64                    }
65                }
66
67                d.attr("style", "fill:#000000")?;
68                d.attr("d", path_data)?;
69                d.attr("transform", format!("scale({scale})"))
70            })
71        })?;
72        w.elem("g", |d| {
73            d.attr(
74                "transform",
75                format!(
76                    "translate({},{}) scale(2)", // data in qr_overlay_delta.svg-part are 48 x 48, scaling by 2 results in desired logo_size of 96
77                    (all_size - logo_size) / 2.0,
78                    (all_size - logo_size) / 2.0
79                ),
80            )
81        })?
82        .build(|w| w.put_raw_escapable(include_str!("../assets/qr_overlay_delta.svg-part")))
83    })?;
84
85    Ok(svg)
86}
87
88/// Returns SVG of the QR code to join the group or verify contact.
89///
90/// If `chat_id` is `None`, returns verification QR code.
91/// Otherwise, returns secure join QR code.
92pub async fn get_securejoin_qr_svg(context: &Context, chat_id: Option<ChatId>) -> Result<String> {
93    if let Some(chat_id) = chat_id {
94        generate_join_group_qr_code(context, chat_id).await
95    } else {
96        generate_verification_qr(context).await
97    }
98}
99
100async fn generate_join_group_qr_code(context: &Context, chat_id: ChatId) -> Result<String> {
101    let chat = Chat::load_from_db(context, chat_id).await?;
102
103    let avatar = match chat.get_profile_image(context).await? {
104        Some(path) => {
105            let avatar_blob = BlobObject::from_path(context, &path)?;
106            Some(tokio::fs::read(avatar_blob.to_abs_path()).await?)
107        }
108        None => None,
109    };
110
111    inner_generate_secure_join_qr_code(
112        &stock_str::secure_join_group_qr_description(context, &chat).await,
113        &securejoin::get_securejoin_qr(context, Some(chat_id)).await?,
114        &color_int_to_hex_string(chat.get_color(context).await?),
115        avatar,
116        chat.get_name().chars().next().unwrap_or('#'),
117    )
118}
119
120async fn generate_verification_qr(context: &Context) -> Result<String> {
121    let (avatar, displayname, addr, color) = self_info(context).await?;
122
123    inner_generate_secure_join_qr_code(
124        &stock_str::setup_contact_qr_description(context, &displayname, &addr).await,
125        &securejoin::get_securejoin_qr(context, None).await?,
126        &color,
127        avatar,
128        displayname.chars().next().unwrap_or('#'),
129    )
130}
131
132/// Renders a [`Qr::Backup2`] QR code as an SVG image.
133pub async fn generate_backup_qr(context: &Context, qr: &Qr) -> Result<String> {
134    let content = qr::format_backup(qr)?;
135    let (avatar, displayname, _addr, color) = self_info(context).await?;
136    let description = backup_transfer_qr(context).await?;
137
138    inner_generate_secure_join_qr_code(
139        &description,
140        &content,
141        &color,
142        avatar,
143        displayname.chars().next().unwrap_or('#'),
144    )
145}
146
147/// Returns `(avatar, displayname, addr, color) of the configured account.
148async fn self_info(context: &Context) -> Result<(Option<Vec<u8>>, String, String, String)> {
149    let contact = Contact::get_by_id(context, ContactId::SELF).await?;
150
151    let avatar = match contact.get_profile_image(context).await? {
152        Some(path) => {
153            let avatar_blob = BlobObject::from_path(context, &path)?;
154            Some(tokio::fs::read(avatar_blob.to_abs_path()).await?)
155        }
156        None => None,
157    };
158
159    let displayname = match context.get_config(Config::Displayname).await? {
160        Some(name) => name,
161        None => contact.get_addr().to_string(),
162    };
163    let addr = contact.get_addr().to_string();
164    let color = color_int_to_hex_string(contact.get_color());
165    Ok((avatar, displayname, addr, color))
166}
167
168fn inner_generate_secure_join_qr_code(
169    qrcode_description: &str,
170    qrcode_content: &str,
171    color: &str,
172    avatar: Option<Vec<u8>>,
173    avatar_letter: char,
174) -> Result<String> {
175    // config
176    let width = 515.0;
177    let height = 630.0;
178    let logo_offset = 28.0;
179    let qr_code_size = 400.0;
180    let qr_translate_up = 40.0;
181    let text_y_pos = ((height - qr_code_size) / 2.0) + qr_code_size;
182    let avatar_border_size = 9.0;
183    let card_border_size = 2.0;
184    let card_roundness = 40.0;
185
186    let qr = QrCode::encode_text(qrcode_content, QrCodeEcc::Medium)?;
187    let mut svg = String::with_capacity(28000);
188    let mut w = tagger::new(&mut svg);
189
190    w.elem("svg", |d| {
191        d.attr("xmlns", "http://www.w3.org/2000/svg")?;
192        d.attr("viewBox", format_args!("0 0 {width} {height}"))?;
193        d.attr("xmlns:xlink", "http://www.w3.org/1999/xlink")?; // required for enabling xlink:href on browsers
194        Ok(())
195    })?
196    .build(|w| {
197        // White Background appears like a card
198        w.single("rect", |d| {
199            d.attr("x", card_border_size)?;
200            d.attr("y", card_border_size)?;
201            d.attr("rx", card_roundness)?;
202            d.attr("stroke", "#c6c6c6")?;
203            d.attr("stroke-width", card_border_size)?;
204            d.attr("width", width - (card_border_size * 2.0))?;
205            d.attr("height", height - (card_border_size * 2.0))?;
206            d.attr("style", "fill:#f2f2f2")?;
207            Ok(())
208        })?;
209        // Qrcode
210        w.elem("g", |d| {
211            d.attr(
212                "transform",
213                format!(
214                    "translate({},{})",
215                    (width - qr_code_size) / 2.0,
216                    ((height - qr_code_size) / 2.0) - qr_translate_up
217                ),
218            )
219            // If the qr code should be in the wrong place,
220            // we could also translate and scale the points in the path already,
221            // but that would make the resulting svg way bigger in size and might bring up rounding issues,
222            // so better avoid doing it manually if possible
223        })?
224        .build(|w| {
225            w.single("path", |d| {
226                let mut path_data = String::with_capacity(0);
227                let scale = qr_code_size / qr.size() as f32;
228
229                for y in 0..qr.size() {
230                    for x in 0..qr.size() {
231                        if qr.get_module(x, y) {
232                            path_data += &format!("M{x},{y}h1v1h-1z");
233                        }
234                    }
235                }
236
237                d.attr("style", "fill:#000000")?;
238                d.attr("d", path_data)?;
239                d.attr("transform", format!("scale({scale})"))
240            })
241        })?;
242
243        // Text
244        const BIG_TEXT_CHARS_PER_LINE: usize = 32;
245        const SMALL_TEXT_CHARS_PER_LINE: usize = 38;
246        let chars_per_line = if qrcode_description.len() > SMALL_TEXT_CHARS_PER_LINE * 2 {
247            SMALL_TEXT_CHARS_PER_LINE
248        } else {
249            BIG_TEXT_CHARS_PER_LINE
250        };
251        let lines = textwrap::fill(qrcode_description, chars_per_line);
252        let (text_font_size, text_y_shift) = if lines.split('\n').count() <= 2 {
253            (27.0, 0.0)
254        } else {
255            (19.0, -10.0)
256        };
257        for (count, line) in lines.split('\n').enumerate() {
258            w.elem("text", |d| {
259                d.attr(
260                    "y",
261                    (count as f32 * (text_font_size * 1.2)) + text_y_pos + text_y_shift,
262                )?;
263                d.attr("x", width / 2.0)?;
264                d.attr("text-anchor", "middle")?;
265                d.attr(
266                    "style",
267                    format!(
268                        "font-family:sans-serif;\
269                        font-weight:bold;\
270                        font-size:{text_font_size}px;\
271                        fill:#000000;\
272                        stroke:none"
273                    ),
274                )
275            })?
276            .build(|w| w.put_raw(line))?;
277        }
278        // contact avatar in middle of qrcode
279        const LOGO_SIZE: f32 = 94.4;
280        const HALF_LOGO_SIZE: f32 = LOGO_SIZE / 2.0;
281        let logo_position_in_qr = (qr_code_size / 2.0) - HALF_LOGO_SIZE;
282        let logo_position_x = ((width - qr_code_size) / 2.0) + logo_position_in_qr;
283        let logo_position_y =
284            ((height - qr_code_size) / 2.0) - qr_translate_up + logo_position_in_qr;
285
286        w.single("circle", |d| {
287            d.attr("cx", logo_position_x + HALF_LOGO_SIZE)?;
288            d.attr("cy", logo_position_y + HALF_LOGO_SIZE)?;
289            d.attr("r", HALF_LOGO_SIZE + avatar_border_size)?;
290            d.attr("style", "fill:#f2f2f2")
291        })?;
292
293        if let Some(img) = avatar {
294            w.elem("defs", tagger::no_attr())?.build(|w| {
295                w.elem("clipPath", |d| d.attr("id", "avatar-cut"))?
296                    .build(|w| {
297                        w.single("circle", |d| {
298                            d.attr("cx", logo_position_x + HALF_LOGO_SIZE)?;
299                            d.attr("cy", logo_position_y + HALF_LOGO_SIZE)?;
300                            d.attr("r", HALF_LOGO_SIZE)
301                        })
302                    })
303            })?;
304
305            w.single("image", |d| {
306                d.attr("x", logo_position_x)?;
307                d.attr("y", logo_position_y)?;
308                d.attr("width", HALF_LOGO_SIZE * 2.0)?;
309                d.attr("height", HALF_LOGO_SIZE * 2.0)?;
310                d.attr("preserveAspectRatio", "none")?;
311                d.attr("clip-path", "url(#avatar-cut)")?;
312                d.attr(
313                    "xlink:href", /* xlink:href is needed otherwise it won't even display in inkscape not to mention qt's QSvgHandler */
314                    format!(
315                        "data:image/jpeg;base64,{}",
316                        base64::engine::general_purpose::STANDARD.encode(img)
317                    ),
318                )
319            })?;
320        } else {
321            w.single("circle", |d| {
322                d.attr("cx", logo_position_x + HALF_LOGO_SIZE)?;
323                d.attr("cy", logo_position_y + HALF_LOGO_SIZE)?;
324                d.attr("r", HALF_LOGO_SIZE)?;
325                d.attr("style", format!("fill:{}", &color))
326            })?;
327
328            let avatar_font_size = LOGO_SIZE * 0.65;
329            let font_offset = avatar_font_size * 0.1;
330            w.elem("text", |d| {
331                d.attr("y", logo_position_y + HALF_LOGO_SIZE + font_offset)?;
332                d.attr("x", logo_position_x + HALF_LOGO_SIZE)?;
333                d.attr("text-anchor", "middle")?;
334                d.attr("dominant-baseline", "central")?;
335                d.attr("alignment-baseline", "middle")?;
336                d.attr(
337                    "style",
338                    format!(
339                        "font-family:sans-serif;\
340                            font-weight:400;\
341                            font-size:{avatar_font_size}px;\
342                            fill:#ffffff;"
343                    ),
344                )
345            })?
346            .build(|w| w.put_raw(avatar_letter.to_uppercase()))?;
347        }
348
349        // Footer logo
350        const FOOTER_HEIGHT: f32 = 35.0;
351        const FOOTER_WIDTH: f32 = 198.0;
352        w.elem("g", |d| {
353            d.attr(
354                "transform",
355                format!(
356                    "translate({},{})",
357                    (width - FOOTER_WIDTH) / 2.0,
358                    height - logo_offset - FOOTER_HEIGHT - text_y_shift
359                ),
360            )
361        })?
362        .build(|w| w.put_raw(include_str!("../assets/qrcode_logo_footer.svg")))
363    })?;
364
365    Ok(svg)
366}
367
368#[cfg(test)]
369mod tests {
370    use testdir::testdir;
371
372    use crate::imex::BackupProvider;
373    use crate::qr::format_backup;
374    use crate::test_utils::TestContextManager;
375
376    use super::*;
377
378    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
379    async fn test_create_qr_svg() -> Result<()> {
380        let svg = create_qr_svg("this is a test QR code \" < > &")?;
381        assert!(svg.contains("<svg"));
382        assert!(svg.contains("</svg>"));
383        Ok(())
384    }
385
386    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
387    async fn test_svg_escaping() {
388        let svg = inner_generate_secure_join_qr_code(
389            "descr123 \" < > &",
390            "qr-code-content",
391            "#000000",
392            None,
393            'X',
394        )
395        .unwrap();
396        assert!(svg.contains("descr123 &quot; &lt; &gt; &amp;"))
397    }
398
399    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
400    async fn test_generate_backup_qr() {
401        let dir = testdir!();
402        let mut tcm = TestContextManager::new();
403        let ctx = tcm.alice().await;
404        let provider = BackupProvider::prepare(&ctx).await.unwrap();
405        let qr = provider.qr();
406
407        println!("{}", format_backup(&qr).unwrap());
408        let rendered = generate_backup_qr(&ctx, &qr).await.unwrap();
409        tokio::fs::write(dir.join("qr.svg"), &rendered)
410            .await
411            .unwrap();
412        assert_eq!(rendered.get(..4), Some("<svg"));
413    }
414}