[qr] QR: payloads, PNG and SVG, centre logo at level H, round-trip tests

This commit is contained in:
2026-11-16 13:15:30 +01:00
parent aec0a77786
commit eae7ef5578
14 changed files with 1335 additions and 0 deletions
+17
View File
@@ -0,0 +1,17 @@
[package]
name = "pictor-qr"
version.workspace = true
edition.workspace = true
license.workspace = true
repository.workspace = true
rust-version.workspace = true
[dependencies]
thiserror.workspace = true
serde.workspace = true
image.workspace = true
qrcode.workspace = true
[dev-dependencies]
rqrr.workspace = true
serde_json.workspace = true
+35
View File
@@ -0,0 +1,35 @@
//! Standard base64 (RFC 4648, with padding), for the SVG logo's data URI.
const ALPHABET: &[u8; 64] = b"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
pub(crate) fn encode(data: &[u8]) -> String {
let mut out = String::with_capacity(data.len().div_ceil(3) * 4);
for chunk in data.chunks(3) {
let b = [chunk[0], chunk.get(1).copied().unwrap_or(0), chunk.get(2).copied().unwrap_or(0)];
let n = (u32::from(b[0]) << 16) | (u32::from(b[1]) << 8) | u32::from(b[2]);
for i in 0..4 {
if i <= chunk.len() {
out.push(ALPHABET[((n >> (18 - 6 * i)) & 0x3f) as usize] as char);
} else {
out.push('=');
}
}
}
out
}
#[cfg(test)]
mod tests {
use super::encode;
#[test]
fn rfc4648_vectors() {
let cases =
[("", ""), ("f", "Zg=="), ("fo", "Zm8="), ("foo", "Zm9v"), ("foob", "Zm9vYg=="), ("fooba", "Zm9vYmE=")];
for (input, expected) in cases {
assert_eq!(encode(input.as_bytes()), expected);
}
assert_eq!(encode(b"foobar"), "Zm9vYmFy");
assert_eq!(encode(&[0xff, 0xfe, 0xfd]), "//79");
}
}
+42
View File
@@ -0,0 +1,42 @@
//! WCAG contrast between the two colours, and the check the renderers run before drawing anything.
use crate::QrError;
/// The least WCAG contrast ratio the renderers accept.
const MIN_CONTRAST: f64 = 3.0;
/// The colour composited over white (a half-transparent colour reads lighter), as linear-light sRGB luminance.
fn luminance([r, g, b, a]: [u8; 4]) -> f64 {
let alpha = f64::from(a) / 255.0;
let channel = |c: u8| {
let c = (f64::from(c) * alpha + 255.0 * (1.0 - alpha)) / 255.0;
if c <= 0.03928 { c / 12.92 } else { ((c + 0.055) / 1.055).powf(2.4) }
};
0.2126 * channel(r) + 0.7152 * channel(g) + 0.0722 * channel(b)
}
/// The WCAG 2 contrast ratio between two RGBA colours (1.0 to 21.0), each composited over white first.
pub fn contrast_ratio(a: [u8; 4], b: [u8; 4]) -> f64 {
let (la, lb) = (luminance(a), luminance(b));
(la.max(lb) + 0.05) / (la.min(lb) + 0.05)
}
/// Whether scanners will read `dark` modules on a `light` background: the dark colour is not fully transparent,
/// is darker than the background, and the WCAG contrast ratio is at least 3:1.
pub fn contrast_ok(dark: [u8; 4], light: [u8; 4]) -> bool {
check(dark, light).is_ok()
}
pub(crate) fn check(dark: [u8; 4], light: [u8; 4]) -> Result<(), QrError> {
if dark[3] == 0 {
return Err(QrError::TransparentDark);
}
if luminance(light) < luminance(dark) {
return Err(QrError::Inverted);
}
let ratio = contrast_ratio(dark, light);
if ratio < MIN_CONTRAST {
return Err(QrError::LowContrast { ratio });
}
Ok(())
}
+144
View File
@@ -0,0 +1,144 @@
//! Text to module matrix, and the geometry shared by the raster and SVG renderers.
use qrcode::bits::Bits;
use qrcode::types::QrError as RawError;
use qrcode::{Color, EcLevel, QrCode, Version};
use crate::{LOGO_FRACTION, Level, MAX_QUIET_ZONE, MAX_SIZE_PX, QrError, Style};
/// The module matrix, row-major, `true` = dark.
pub(crate) struct Matrix {
pub width: u32,
pub dark: Vec<bool>,
}
impl Matrix {
pub fn is_dark(&self, x: u32, y: u32) -> bool {
self.dark[(y * self.width + x) as usize]
}
}
/// Encodes `text` at `level`. ASCII uses the encoder's optimal segmentation (numeric, alphanumeric, byte); anything
/// else is one UTF-8 byte segment, because the optimiser would put some UTF-8 byte pairs in Kanji mode, which phone
/// scanners turn into Japanese characters.
pub(crate) fn encode(text: &str, level: Level, logo: bool) -> Result<Matrix, QrError> {
if text.trim().is_empty() {
return Err(QrError::Empty);
}
let ec = level.ec();
let code = if text.is_ascii() {
QrCode::with_error_correction_level(text.as_bytes(), ec)
} else {
byte_mode(text.as_bytes(), ec)
}
.map_err(|e| match e {
RawError::DataTooLong => QrError::TooLong { level, logo },
other => QrError::Encode(other.to_string()),
})?;
let width = code.width() as u32;
let dark = code.to_colors().into_iter().map(|c| c == Color::Dark).collect();
Ok(Matrix { width, dark })
}
fn byte_mode(data: &[u8], ec: EcLevel) -> qrcode::QrResult<QrCode> {
for v in 1..=40 {
let mut bits = Bits::new(Version::Normal(v));
if bits.push_byte_data(data).is_ok() && bits.push_terminator(ec).is_ok() {
return QrCode::with_bits(bits, ec);
}
}
Err(RawError::DataTooLong)
}
/// Pixel geometry of one rendering.
pub(crate) struct Geometry {
/// Modules across the code, quiet zone excluded.
pub modules: u32,
pub quiet: u32,
/// Pixels per module.
pub scale: u32,
}
impl Geometry {
pub fn new(modules: u32, style: &Style) -> Result<Geometry, QrError> {
if style.quiet_zone > MAX_QUIET_ZONE {
return Err(QrError::QuietZoneTooLarge { max: MAX_QUIET_ZONE });
}
if style.size_px > MAX_SIZE_PX {
return Err(QrError::SizeTooLarge { max_px: MAX_SIZE_PX });
}
let total = modules + 2 * style.quiet_zone;
let scale = style.size_px / total;
if scale == 0 {
return Err(QrError::SizeTooSmall { min_px: total });
}
Ok(Geometry { modules, quiet: style.quiet_zone, scale })
}
/// Modules across the whole image, quiet zone included.
pub fn total_modules(&self) -> u32 {
self.modules + 2 * self.quiet
}
pub fn size_px(&self) -> u32 {
self.total_modules() * self.scale
}
}
/// Where the logo goes. The plate is whole modules (all cleared to the light colour), an odd number across so it
/// sits exactly in the middle, with at least half a module of padding around the logo.
pub(crate) struct Plate {
/// Plate, in modules, relative to the code's top-left corner (quiet zone excluded).
pub x: u32,
pub y: u32,
pub w: u32,
pub h: u32,
/// The logo's box, in pixels, relative to the code's top-left corner (quiet zone excluded).
pub logo_x: u32,
pub logo_y: u32,
pub logo_w: u32,
pub logo_h: u32,
}
impl Plate {
pub fn new(g: &Geometry, logo_w: u32, logo_h: u32) -> Plate {
let code_px = f64::from(g.modules * g.scale);
let max_px = code_px * LOGO_FRACTION;
let k = max_px / f64::from(logo_w.max(logo_h));
let lw = ((f64::from(logo_w) * k).floor() as u32).max(1);
let lh = ((f64::from(logo_h) * k).floor() as u32).max(1);
let s = f64::from(g.scale);
let odd = |n: u32| if n.is_multiple_of(2) { n + 1 } else { n };
let w = odd((f64::from(lw) / s + 1.0).ceil() as u32).min(g.modules);
let h = odd((f64::from(lh) / s + 1.0).ceil() as u32).min(g.modules);
let (x, y) = ((g.modules - w) / 2, (g.modules - h) / 2);
Plate {
x,
y,
w,
h,
logo_x: x * g.scale + (w * g.scale - lw) / 2,
logo_y: y * g.scale + (h * g.scale - lh) / 2,
logo_w: lw,
logo_h: lh,
}
}
pub fn contains(&self, mx: u32, my: u32) -> bool {
mx >= self.x && mx < self.x + self.w && my >= self.y && my < self.y + self.h
}
}
/// Encodes for a rendering: checks the colours, forces level H with a logo, and lays out the pixels.
pub(crate) fn prepare(
text: &str,
level: Level,
style: &Style,
logo: bool,
) -> Result<(Matrix, Geometry, Level), QrError> {
crate::colour::check(style.dark, style.light)?;
let level = if logo { Level::H } else { level };
let matrix = encode(text, level, logo)?;
let geometry = Geometry::new(matrix.width, style)?;
Ok((matrix, geometry, level))
}
+68
View File
@@ -0,0 +1,68 @@
use crate::Level;
/// Everything that can go wrong. `Display` is a plain sentence for the user.
#[derive(Debug, Clone, PartialEq, thiserror::Error)]
#[non_exhaustive]
pub enum QrError {
#[error("There is nothing to put in the QR code yet. Type some text first.")]
Empty,
/// A required field of a payload is empty; `field` is its plain name ("Wi-Fi network name", ...).
#[error("The {field} is empty. Fill it in first.")]
EmptyField { field: &'static str },
/// The content does not fit in a QR code at `level`; `logo` says the level was forced to H by a logo.
#[error("{}", too_long(*level, *logo))]
TooLong { level: Level, logo: bool },
#[error(
"The two colours are too similar for a scanner to tell apart (contrast {ratio:.1}:1, it needs at least 3:1). \
Make the code colour darker or the background lighter."
)]
LowContrast { ratio: f64 },
#[error(
"The code colour is lighter than the background. Many scanners only read dark codes on a light background, \
so swap the two colours."
)]
Inverted,
#[error("The code colour is fully transparent, so the code would be invisible. Choose a solid colour.")]
TransparentDark,
#[error(
"The image is too small for this much content: it needs at least {min_px} pixels across. \
Make it larger or shorten the content."
)]
SizeTooSmall { min_px: u32 },
#[error("The image can be at most {max_px} pixels across. Choose a smaller size.")]
SizeTooLarge { max_px: u32 },
#[error("The quiet zone can be at most {max} modules wide. Choose a narrower one.")]
QuietZoneTooLarge { max: u32 },
/// The logo could not be used; the text says why.
#[error("The logo cannot be used: {0}")]
Logo(String),
/// An internal encoder failed (should not happen); the text is the encoder's.
#[error("The QR code could not be made: {0}")]
Encode(String),
}
fn too_long(level: Level, logo: bool) -> String {
if logo {
"This is too much content for a QR code with a logo. A logo needs the highest error-correction level (H), \
which holds the least. Remove the logo or shorten the content."
.to_string()
} else if level == Level::L {
"This is too much content for one QR code, even at the lowest error-correction level (L). Shorten it."
.to_string()
} else {
format!(
"This is too much content for one QR code at error-correction level {level}. \
Shorten it or choose a lower level."
)
}
}
+89
View File
@@ -0,0 +1,89 @@
//! QR codes for Pictor's Toolbox: payload builders (text, URL, Wi-Fi, contact), raster (RGBA, PNG) and SVG output,
//! an optional centre logo (which forces error-correction level H), and a colour check that refuses combinations
//! scanners will not read.
//!
//! Every error is a [`QrError`] whose `Display` is a plain-English sentence meant to be shown to the user.
mod base64;
mod colour;
mod encode;
mod error;
mod payload;
mod render;
mod svg;
use serde::{Deserialize, Serialize};
pub use colour::{contrast_ok, contrast_ratio};
pub use error::QrError;
pub use payload::{Payload, WifiSecurity, payload_string};
pub use render::{Rendered, encode_png, render_png, render_rgba};
pub use svg::render_svg;
/// The largest output, in pixels across, that the renderers will produce.
pub const MAX_SIZE_PX: u32 = 4096;
/// The widest quiet zone, in modules, that the renderers accept.
pub const MAX_QUIET_ZONE: u32 = 40;
/// The largest logo PNG, in bytes, that [`render_svg`] accepts.
pub const MAX_LOGO_BYTES: usize = 8 * 1024 * 1024;
/// The largest logo, in pixels across either side, that the renderers accept.
pub const MAX_LOGO_PX: u32 = 4096;
/// The logo's largest side, as a fraction of the code's width (quiet zone excluded).
pub const LOGO_FRACTION: f64 = 0.22;
/// Error-correction level: how much of the code can be damaged or covered and still read.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
pub enum Level {
/// About 7% recoverable; the most content.
L,
/// About 15% recoverable; the usual choice.
#[default]
M,
/// About 25% recoverable.
Q,
/// About 30% recoverable; the least content. Forced when a logo is drawn.
H,
}
impl Level {
pub(crate) fn ec(self) -> qrcode::EcLevel {
match self {
Level::L => qrcode::EcLevel::L,
Level::M => qrcode::EcLevel::M,
Level::Q => qrcode::EcLevel::Q,
Level::H => qrcode::EcLevel::H,
}
}
}
impl std::fmt::Display for Level {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Level::L => "L",
Level::M => "M",
Level::Q => "Q",
Level::H => "H",
})
}
}
/// How the code looks.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
#[serde(default)]
pub struct Style {
/// Target width and height in pixels. Modules are scaled by a whole number of pixels, so the output may be a
/// little smaller; [`Rendered::size_px`] reports the real size.
pub size_px: u32,
/// Light border around the code, in modules. Scanners want 4; less works on most phones.
pub quiet_zone: u32,
/// The modules' colour, RGBA.
pub dark: [u8; 4],
/// The background (and quiet zone, and logo plate) colour, RGBA. May be transparent.
pub light: [u8; 4],
}
impl Default for Style {
fn default() -> Self {
Style { size_px: 512, quiet_zone: 4, dark: [0, 0, 0, 255], light: [255, 255, 255, 255] }
}
}
+227
View File
@@ -0,0 +1,227 @@
//! What goes inside the code: plain text, a web address, a Wi-Fi login, or a contact card.
use serde::{Deserialize, Serialize};
use crate::{Level, QrError};
/// Wi-Fi security, as the `T:` field of the Wi-Fi payload names it.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum WifiSecurity {
/// WPA, WPA2 or WPA3 personal (phones read `T:WPA` for all of them).
#[default]
Wpa,
/// The old WEP.
Wep,
/// No password.
Open,
}
/// The content of a code, before it is turned into the string that is encoded.
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum Payload {
/// Any text, kept exactly as given.
Text(String),
/// A web address; `https://` is added when it has no scheme.
Url(String),
/// A Wi-Fi login. The password is ignored for [`WifiSecurity::Open`].
Wifi {
ssid: String,
#[serde(default)]
password: String,
#[serde(default)]
security: WifiSecurity,
#[serde(default)]
hidden: bool,
},
/// A contact card (vCard 3.0). Empty optional fields are left out.
Contact {
name: String,
#[serde(default)]
phone: Option<String>,
#[serde(default)]
email: Option<String>,
#[serde(default)]
organisation: Option<String>,
#[serde(default)]
url: Option<String>,
#[serde(default)]
address: Option<String>,
#[serde(default)]
note: Option<String>,
},
}
/// The string to encode for `payload`. Fails on empty required fields and on content that no QR code can hold
/// (even at level L); whether it fits at a higher level is checked when it is rendered.
pub fn payload_string(payload: &Payload) -> Result<String, QrError> {
let s = match payload {
Payload::Text(t) => {
if t.trim().is_empty() {
return Err(QrError::Empty);
}
t.clone()
}
Payload::Url(u) => url(u)?,
Payload::Wifi { ssid, password, security, hidden } => wifi(ssid, password, *security, *hidden)?,
Payload::Contact { name, phone, email, organisation, url, address, note } => {
let field = |f: &Option<String>| f.as_deref().map(str::trim).filter(|s| !s.is_empty()).map(str::to_owned);
vcard(&Contact {
name: name.trim(),
phone: field(phone),
email: field(email),
organisation: field(organisation),
url: field(url),
address: field(address),
note: field(note),
})?
}
};
crate::encode::encode(&s, Level::L, false)?;
Ok(s)
}
fn url(u: &str) -> Result<String, QrError> {
let u = u.trim();
if u.is_empty() {
return Err(QrError::EmptyField { field: "web address" });
}
Ok(if has_scheme(u) { u.to_string() } else { format!("https://{u}") })
}
/// RFC 3986 `scheme ":"`, where the colon is not followed by a digit (so `localhost:8080` is a host and a port).
fn has_scheme(u: &str) -> bool {
let Some((scheme, rest)) = u.split_once(':') else { return false };
let mut chars = scheme.chars();
let first_ok = chars.next().is_some_and(|c| c.is_ascii_alphabetic());
first_ok
&& chars.all(|c| c.is_ascii_alphanumeric() || matches!(c, '+' | '-' | '.'))
&& !rest.starts_with(|c: char| c.is_ascii_digit())
}
/// The de-facto Wi-Fi format (`WIFI:T:WPA;S:<ssid>;P:<password>;H:true;;`), with `\ ; , : "` backslash-escaped.
fn wifi(ssid: &str, password: &str, security: WifiSecurity, hidden: bool) -> Result<String, QrError> {
fn esc(s: &str) -> String {
let mut out = String::with_capacity(s.len());
for c in s.chars() {
if matches!(c, '\\' | ';' | ',' | ':' | '"') {
out.push('\\');
}
out.push(c);
}
out
}
if ssid.is_empty() {
return Err(QrError::EmptyField { field: "Wi-Fi network name" });
}
let t = match security {
WifiSecurity::Wpa => "WPA",
WifiSecurity::Wep => "WEP",
WifiSecurity::Open => "nopass",
};
let mut s = format!("WIFI:T:{t};S:{};", esc(ssid));
if security != WifiSecurity::Open {
if password.is_empty() {
return Err(QrError::EmptyField { field: "Wi-Fi password (choose \"Open\" for a network without one)" });
}
s.push_str(&format!("P:{};", esc(password)));
}
if hidden {
s.push_str("H:true;");
}
s.push(';');
Ok(s)
}
struct Contact<'a> {
name: &'a str,
phone: Option<String>,
email: Option<String>,
organisation: Option<String>,
url: Option<String>,
address: Option<String>,
note: Option<String>,
}
/// vCard text value escaping (RFC 2426 / 6350): `\` `,` `;` get a backslash, every line break becomes `\n`.
fn esc_text(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let mut chars = s.chars().peekable();
while let Some(c) = chars.next() {
match c {
'\\' | ',' | ';' => {
out.push('\\');
out.push(c);
}
'\r' => {
chars.next_if_eq(&'\n');
out.push_str("\\n");
}
'\n' => out.push_str("\\n"),
_ => out.push(c),
}
}
out
}
/// A value that is not text (telephone, e-mail, URI): kept as given, but on one line.
fn one_line(s: &str) -> String {
s.split(['\r', '\n']).filter(|p| !p.is_empty()).collect::<Vec<_>>().join(" ")
}
/// vCard 3.0 with CRLF line endings. `N` is split at the last space into given and family name. Lines are not
/// folded at 75 octets: every scanner reads long lines, and some do not unfold.
fn vcard(c: &Contact) -> Result<String, QrError> {
if c.name.is_empty() {
return Err(QrError::EmptyField { field: "contact name" });
}
let (given, family) = match c.name.rsplit_once(char::is_whitespace) {
Some((g, f)) => (g.trim_end(), f),
None => ("", c.name),
};
let mut lines = vec![
"BEGIN:VCARD".to_string(),
"VERSION:3.0".to_string(),
format!("N:{};{};;;", esc_text(family), esc_text(given)),
format!("FN:{}", esc_text(c.name)),
];
if let Some(v) = &c.organisation {
lines.push(format!("ORG:{}", esc_text(v)));
}
if let Some(v) = &c.phone {
lines.push(format!("TEL:{}", one_line(v)));
}
if let Some(v) = &c.email {
lines.push(format!("EMAIL:{}", one_line(v)));
}
if let Some(v) = &c.url {
lines.push(format!("URL:{}", one_line(v)));
}
if let Some(v) = &c.address {
lines.push(format!("ADR:;;{};;;;", esc_text(v)));
}
if let Some(v) = &c.note {
lines.push(format!("NOTE:{}", esc_text(v)));
}
lines.push("END:VCARD".to_string());
let mut s = lines.join("\r\n");
s.push_str("\r\n");
Ok(s)
}
#[cfg(test)]
mod tests {
use super::has_scheme;
#[test]
fn scheme_detection() {
assert!(has_scheme("https://a"));
assert!(has_scheme("mailto:x@y"));
assert!(has_scheme("tel:+420"));
assert!(!has_scheme("example.com"));
assert!(!has_scheme("example.com:8080/x"));
assert!(!has_scheme("1http://x"));
assert!(!has_scheme("ex ample:x"));
}
}
+94
View File
@@ -0,0 +1,94 @@
//! Raster output: an RGBA image, and PNG bytes.
use image::{ImageEncoder, Rgba, RgbaImage, imageops};
use crate::encode::{Plate, prepare};
use crate::{Level, MAX_LOGO_PX, QrError, Style};
/// A rendered code.
#[derive(Debug, Clone)]
pub struct Rendered {
/// The code, `size_px` square, quiet zone included.
pub image: RgbaImage,
/// The error-correction level actually used: H whenever a logo was drawn, whatever was asked.
pub level_used: Level,
/// Modules across the code, quiet zone excluded (21 for version 1, up to 177).
pub modules: u32,
/// Pixels per module.
pub module_px: u32,
/// The real width and height in pixels: `(modules + 2 * quiet_zone) * module_px`, at most the asked size.
pub size_px: u32,
}
/// Renders `text` as an RGBA image. With a `logo` the level is forced to H and the logo (aspect kept, its largest
/// side about 22% of the code's width) is drawn centred on a plate of cleared, light-coloured modules.
pub fn render_rgba(text: &str, level: Level, style: &Style, logo: Option<&RgbaImage>) -> Result<Rendered, QrError> {
if let Some(l) = logo {
check_logo_size(l.width(), l.height())?;
}
let (matrix, g, level_used) = prepare(text, level, style, logo.is_some())?;
let plate = logo.map(|l| Plate::new(&g, l.width(), l.height()));
let size = g.size_px();
let mut img = RgbaImage::from_pixel(size, size, Rgba(style.light));
let dark = Rgba(style.dark);
for my in 0..g.modules {
for mx in 0..g.modules {
if !matrix.is_dark(mx, my) || plate.as_ref().is_some_and(|p| p.contains(mx, my)) {
continue;
}
let (x0, y0) = ((g.quiet + mx) * g.scale, (g.quiet + my) * g.scale);
for y in y0..y0 + g.scale {
for x in x0..x0 + g.scale {
img.put_pixel(x, y, dark);
}
}
}
}
if let (Some(logo), Some(p)) = (logo, &plate) {
let scaled = imageops::resize(logo, p.logo_w, p.logo_h, imageops::FilterType::Lanczos3);
let (ox, oy) = (g.quiet * g.scale + p.logo_x, g.quiet * g.scale + p.logo_y);
for (x, y, src) in scaled.enumerate_pixels() {
let dst = img.get_pixel_mut(ox + x, oy + y);
*dst = over(*src, *dst);
}
}
Ok(Rendered { image: img, level_used, modules: g.modules, module_px: g.scale, size_px: size })
}
/// [`render_rgba`], encoded as PNG.
pub fn render_png(text: &str, level: Level, style: &Style, logo: Option<&RgbaImage>) -> Result<Vec<u8>, QrError> {
encode_png(&render_rgba(text, level, style, logo)?.image)
}
/// Encodes an RGBA image (a [`Rendered::image`]) as PNG.
pub fn encode_png(image: &RgbaImage) -> Result<Vec<u8>, QrError> {
let mut out = Vec::new();
image::codecs::png::PngEncoder::new(&mut out)
.write_image(image.as_raw(), image.width(), image.height(), image::ExtendedColorType::Rgba8)
.map_err(|e| QrError::Encode(e.to_string()))?;
Ok(out)
}
pub(crate) fn check_logo_size(w: u32, h: u32) -> Result<(), QrError> {
if w == 0 || h == 0 {
return Err(QrError::Logo("the image is empty.".into()));
}
if w > MAX_LOGO_PX || h > MAX_LOGO_PX {
return Err(QrError::Logo(format!(
"it is {w} x {h} pixels; at most {MAX_LOGO_PX} pixels on each side is allowed. Use a smaller image."
)));
}
Ok(())
}
/// Straight-alpha "source over destination".
fn over(src: Rgba<u8>, dst: Rgba<u8>) -> Rgba<u8> {
let sa = f32::from(src[3]) / 255.0;
let da = f32::from(dst[3]) / 255.0;
let oa = sa + da * (1.0 - sa);
if oa <= 0.0 {
return Rgba([0, 0, 0, 0]);
}
let mix = |s: u8, d: u8| ((f32::from(s) * sa + f32::from(d) * da * (1.0 - sa)) / oa).round() as u8;
Rgba([mix(src[0], dst[0]), mix(src[1], dst[1]), mix(src[2], dst[2]), (oa * 255.0).round() as u8])
}
+105
View File
@@ -0,0 +1,105 @@
//! SVG output: one path of dark-module runs, a background rect, and the logo as a base64 PNG data URI.
use std::fmt::Write as _;
use std::io::Cursor;
use crate::encode::{Plate, prepare};
use crate::render::check_logo_size;
use crate::{Level, MAX_LOGO_BYTES, MAX_LOGO_PX, QrError, Style};
/// Renders `text` as SVG. The view box is in modules (quiet zone included); `width` and `height` are the same pixel
/// size [`crate::render_rgba`] would produce. Dark modules are one `<path>` of horizontal runs
/// (`M{x} {y}h{n}v1h-{n}z`). With `logo_png` (PNG bytes) the level is forced to H, the modules under the logo's
/// plate are left out, and the PNG is embedded unchanged as an `<image>` data URI.
pub fn render_svg(text: &str, level: Level, style: &Style, logo_png: Option<&[u8]>) -> Result<String, QrError> {
let logo_size = logo_png.map(logo_dimensions).transpose()?;
let (matrix, g, _) = prepare(text, level, style, logo_png.is_some())?;
let plate = logo_size.map(|(w, h)| Plate::new(&g, w, h));
let total = g.total_modules();
let size = g.size_px();
let mut svg = String::with_capacity(256 + (g.modules * g.modules) as usize * 4);
let _ = writeln!(
svg,
"<svg xmlns=\"http://www.w3.org/2000/svg\" xmlns:xlink=\"http://www.w3.org/1999/xlink\" version=\"1.1\" \
width=\"{size}\" height=\"{size}\" viewBox=\"0 0 {total} {total}\" shape-rendering=\"crispEdges\">\n"
);
if style.light[3] > 0 {
let _ = writeln!(svg, "<rect width=\"{total}\" height=\"{total}\"{}/>", fill(style.light));
}
let _ = write!(svg, "<path{} d=\"", fill(style.dark));
for my in 0..g.modules {
let mut mx = 0;
while mx < g.modules {
let on = |x: u32| matrix.is_dark(x, my) && !plate.as_ref().is_some_and(|p| p.contains(x, my));
if !on(mx) {
mx += 1;
continue;
}
let start = mx;
while mx < g.modules && on(mx) {
mx += 1;
}
let n = mx - start;
let _ = write!(svg, "M{} {}h{n}v1h-{n}z", g.quiet + start, g.quiet + my);
}
}
svg.push_str("\"/>\n");
if let (Some(png), Some(p)) = (logo_png, &plate) {
let s = f64::from(g.scale);
let q = f64::from(g.quiet);
let _ = writeln!(
svg,
"<image x=\"{}\" y=\"{}\" width=\"{}\" height=\"{}\" preserveAspectRatio=\"xMidYMid meet\" \
xlink:href=\"data:image/png;base64,{}\"/>",
num(q + f64::from(p.logo_x) / s),
num(q + f64::from(p.logo_y) / s),
num(f64::from(p.logo_w) / s),
num(f64::from(p.logo_h) / s),
crate::base64::encode(png)
);
}
svg.push_str("</svg>\n");
Ok(svg)
}
/// Decodes the logo PNG (with caps on bytes, pixels and memory) to check it and read its size.
fn logo_dimensions(png: &[u8]) -> Result<(u32, u32), QrError> {
if png.len() > MAX_LOGO_BYTES {
return Err(QrError::Logo(format!(
"the file is {} MB; at most {} MB is allowed.",
png.len().div_ceil(1024 * 1024),
MAX_LOGO_BYTES / (1024 * 1024)
)));
}
let mut reader = image::ImageReader::with_format(Cursor::new(png), image::ImageFormat::Png);
let mut limits = image::Limits::default();
limits.max_image_width = Some(MAX_LOGO_PX);
limits.max_image_height = Some(MAX_LOGO_PX);
limits.max_alloc = Some(u64::from(MAX_LOGO_PX) * u64::from(MAX_LOGO_PX) * 8);
reader.limits(limits);
let img = reader.decode().map_err(|e| match e {
image::ImageError::Limits(_) => {
QrError::Logo(format!("it is larger than {MAX_LOGO_PX} pixels on a side. Use a smaller image."))
}
_ => QrError::Logo("it is not a readable PNG image.".into()),
})?;
check_logo_size(img.width(), img.height())?;
Ok((img.width(), img.height()))
}
/// ` fill="#rrggbb"`, plus ` fill-opacity` when the colour is not opaque.
fn fill([r, g, b, a]: [u8; 4]) -> String {
let mut s = format!(" fill=\"#{r:02x}{g:02x}{b:02x}\"");
if a < 255 {
let _ = write!(s, " fill-opacity=\"{}\"", num(f64::from(a) / 255.0));
}
s
}
/// A number with at most three decimals and no trailing zeros.
fn num(v: f64) -> String {
let s = format!("{v:.3}");
let s = s.trim_end_matches('0').trim_end_matches('.');
if s.is_empty() || s == "-" { "0".into() } else { s.to_string() }
}
+58
View File
@@ -0,0 +1,58 @@
//! Helpers shared by the integration tests: decoding a rendered code back with rqrr.
#![allow(dead_code)]
use image::{DynamicImage, GrayImage, Rgba, RgbaImage};
/// Decodes the single QR code in `img` and returns its text and the ECC level rqrr read (0 = M, 1 = L, 2 = H, 3 = Q).
pub fn decode_gray(gray: GrayImage) -> (String, u16) {
let mut prepared = rqrr::PreparedImage::prepare(gray);
let grids = prepared.detect_grids();
assert_eq!(grids.len(), 1, "expected exactly one QR code in the image, found {}", grids.len());
let (meta, content) = grids[0].decode().expect("the QR code should decode");
(content, meta.ecc_level)
}
pub fn decode(img: &RgbaImage) -> String {
decode_with_level(img).0
}
pub fn decode_with_level(img: &RgbaImage) -> (String, u16) {
decode_gray(DynamicImage::ImageRgba8(img.clone()).to_luma8())
}
/// rqrr's `ecc_level` numbering is the format-information encoding: M = 0, L = 1, H = 2, Q = 3.
pub fn rqrr_level(level: pictor_qr::Level) -> u16 {
match level {
pictor_qr::Level::M => 0,
pictor_qr::Level::L => 1,
pictor_qr::Level::H => 2,
pictor_qr::Level::Q => 3,
}
}
/// A logo: a filled red circle on a yellow square, with a transparent border.
pub fn logo(w: u32, h: u32) -> RgbaImage {
let mut img = RgbaImage::from_pixel(w, h, Rgba([0, 0, 0, 0]));
let (cx, cy) = (w as f64 / 2.0, h as f64 / 2.0);
let r = (w.min(h) as f64) * 0.35;
for y in 0..h {
for x in 0..w {
let border = x < w / 10 || y < h / 10 || x >= w - w / 10 || y >= h - h / 10;
let (dx, dy) = (x as f64 + 0.5 - cx, y as f64 + 0.5 - cy);
let px = if dx * dx + dy * dy <= r * r {
Rgba([200, 20, 40, 255])
} else if border {
Rgba([0, 0, 0, 0])
} else {
Rgba([240, 200, 30, 255])
};
img.put_pixel(x, y, px);
}
}
img
}
pub fn logo_png(w: u32, h: u32) -> Vec<u8> {
pictor_qr::encode_png(&logo(w, h)).expect("logo PNG")
}
+84
View File
@@ -0,0 +1,84 @@
//! Colour checks and input errors: typed, with a plain message.
mod common;
use common::logo;
use pictor_qr::{Level, QrError, Style, contrast_ok, contrast_ratio, render_png, render_rgba, render_svg};
#[test]
fn contrast_ratio_matches_wcag() {
assert!((contrast_ratio([0, 0, 0, 255], [255, 255, 255, 255]) - 21.0).abs() < 1e-9);
assert!((contrast_ratio([255, 255, 255, 255], [255, 255, 255, 255]) - 1.0).abs() < 1e-9);
// #777777 on white is about 4.48:1.
assert!((contrast_ratio([0x77, 0x77, 0x77, 255], [255, 255, 255, 255]) - 4.48).abs() < 0.01);
}
#[test]
fn contrast_ok_cases() {
assert!(contrast_ok([0, 0, 0, 255], [255, 255, 255, 255]));
assert!(contrast_ok([16, 32, 96, 255], [255, 250, 225, 255]));
assert!(!contrast_ok([200, 200, 200, 255], [255, 255, 255, 255]), "too light");
assert!(!contrast_ok([255, 255, 255, 255], [0, 0, 0, 255]), "inverted");
assert!(!contrast_ok([0, 0, 0, 0], [255, 255, 255, 255]), "transparent dark");
assert!(contrast_ok([0, 0, 0, 255], [255, 255, 255, 0]), "a transparent background is allowed");
}
#[test]
fn low_contrast_is_refused() {
let style = Style { dark: [180, 180, 180, 255], light: [255, 255, 255, 255], ..Style::default() };
let err = render_rgba("hello", Level::M, &style, None).unwrap_err();
assert!(matches!(err, QrError::LowContrast { .. }), "{err:?}");
assert!(err.to_string().contains("contrast"), "{err}");
assert!(matches!(render_svg("hello", Level::M, &style, None), Err(QrError::LowContrast { .. })));
assert!(matches!(render_png("hello", Level::M, &style, None), Err(QrError::LowContrast { .. })));
}
#[test]
fn inverted_and_transparent_are_refused() {
let inverted = Style { dark: [255, 255, 255, 255], light: [0, 0, 0, 255], ..Style::default() };
assert_eq!(render_rgba("x", Level::M, &inverted, None).unwrap_err(), QrError::Inverted);
let invisible = Style { dark: [0, 0, 0, 0], ..Style::default() };
assert_eq!(render_rgba("x", Level::M, &invisible, None).unwrap_err(), QrError::TransparentDark);
}
#[test]
fn empty_input_is_refused() {
assert_eq!(render_rgba("", Level::M, &Style::default(), None).unwrap_err(), QrError::Empty);
assert_eq!(render_svg(" ", Level::M, &Style::default(), None).unwrap_err(), QrError::Empty);
assert!(!QrError::Empty.to_string().is_empty());
}
#[test]
fn data_too_long_is_refused() {
let text = "ž".repeat(700); // 1400 bytes: fits at L, not at H (max 1273 bytes)
let err = render_rgba(&text, Level::H, &Style::default(), None).unwrap_err();
assert_eq!(err, QrError::TooLong { level: Level::H, logo: false });
assert!(err.to_string().contains("too much"), "{err}");
let style = Style { size_px: 2000, ..Style::default() };
assert!(render_rgba(&text, Level::L, &style, None).is_ok());
// With a logo the level is H whatever was asked, and the message says why.
let err = render_rgba(&text, Level::L, &style, Some(&logo(32, 32))).unwrap_err();
assert_eq!(err, QrError::TooLong { level: Level::H, logo: true });
assert!(err.to_string().contains("logo"), "{err}");
let err = render_rgba(&"a".repeat(5000), Level::L, &Style::default(), None).unwrap_err();
assert_eq!(err, QrError::TooLong { level: Level::L, logo: false });
}
#[test]
fn size_too_small_is_refused() {
let style = Style { size_px: 20, ..Style::default() };
let err = render_rgba("hello", Level::M, &style, None).unwrap_err();
assert!(matches!(err, QrError::SizeTooSmall { min_px: 29 }), "{err:?}");
}
#[test]
fn size_too_large_is_refused() {
let style = Style { size_px: 100_000, ..Style::default() };
assert!(matches!(render_rgba("hello", Level::M, &style, None), Err(QrError::SizeTooLarge { .. })));
}
#[test]
fn empty_logo_is_refused() {
let empty = image::RgbaImage::new(0, 0);
assert!(matches!(render_rgba("x", Level::M, &Style::default(), Some(&empty)), Err(QrError::Logo(_))));
}
+114
View File
@@ -0,0 +1,114 @@
//! Payload builders: the exact strings, escaping, and the input errors.
use pictor_qr::{Level, Payload, QrError, WifiSecurity, payload_string};
fn contact(name: &str) -> Payload {
Payload::Contact {
name: name.into(),
phone: None,
email: None,
organisation: None,
url: None,
address: None,
note: None,
}
}
#[test]
fn text_is_kept_exactly() {
let s = payload_string(&Payload::Text(" Příliš žluťoučký kůň\n".into())).unwrap();
assert_eq!(s, " Příliš žluťoučký kůň\n");
}
#[test]
fn url_without_scheme_gets_https() {
assert_eq!(payload_string(&Payload::Url("example.com/a?b=1".into())).unwrap(), "https://example.com/a?b=1");
assert_eq!(payload_string(&Payload::Url(" localhost:8080/x ".into())).unwrap(), "https://localhost:8080/x");
}
#[test]
fn url_with_scheme_is_kept() {
assert_eq!(payload_string(&Payload::Url("http://example.com".into())).unwrap(), "http://example.com");
assert_eq!(payload_string(&Payload::Url("mailto:a@b.cz".into())).unwrap(), "mailto:a@b.cz");
assert_eq!(payload_string(&Payload::Url("HTTPS://X.CZ".into())).unwrap(), "HTTPS://X.CZ");
}
#[test]
fn wifi_escapes_special_characters() {
let p = Payload::Wifi {
ssid: r#"Café;"Net",1:2\x"#.into(),
password: "pa;ss:wo,rd\"\\".into(),
security: WifiSecurity::Wpa,
hidden: true,
};
assert_eq!(payload_string(&p).unwrap(), r#"WIFI:T:WPA;S:Café\;\"Net\"\,1\:2\\x;P:pa\;ss\:wo\,rd\"\\;H:true;;"#);
}
#[test]
fn wifi_open_and_wep() {
let open =
Payload::Wifi { ssid: "Guest".into(), password: "ignored".into(), security: WifiSecurity::Open, hidden: false };
assert_eq!(payload_string(&open).unwrap(), "WIFI:T:nopass;S:Guest;;");
let wep =
Payload::Wifi { ssid: "Old".into(), password: "12345".into(), security: WifiSecurity::Wep, hidden: false };
assert_eq!(payload_string(&wep).unwrap(), "WIFI:T:WEP;S:Old;P:12345;;");
}
#[test]
fn wifi_needs_ssid_and_password() {
let no_ssid = Payload::Wifi { ssid: "".into(), password: "x".into(), security: WifiSecurity::Wpa, hidden: false };
assert!(matches!(payload_string(&no_ssid), Err(QrError::EmptyField { .. })));
let no_pass =
Payload::Wifi { ssid: "Home".into(), password: "".into(), security: WifiSecurity::Wpa, hidden: false };
let err = payload_string(&no_pass).unwrap_err();
assert!(matches!(err, QrError::EmptyField { .. }));
assert!(err.to_string().contains("password"), "{err}");
}
#[test]
fn vcard_full_contact() {
let p = Payload::Contact {
name: " Jan Novák ".into(),
phone: Some("+420 777 123 456".into()),
email: Some("jan@example.cz".into()),
organisation: Some("Firma, s.r.o.; IT".into()),
url: Some("https://example.cz/a,b".into()),
address: Some("Dlouhá 1\nPraha".into()),
note: Some("Back\\slash; and, comma\r\nnew line".into()),
};
let expected = "BEGIN:VCARD\r\nVERSION:3.0\r\nN:Novák;Jan;;;\r\nFN:Jan Novák\r\nORG:Firma\\, s.r.o.\\; IT\r\n\
TEL:+420 777 123 456\r\nEMAIL:jan@example.cz\r\nURL:https://example.cz/a,b\r\n\
ADR:;;Dlouhá 1\\nPraha;;;;\r\nNOTE:Back\\\\slash\\; and\\, comma\\nnew line\r\nEND:VCARD\r\n";
assert_eq!(payload_string(&p).unwrap(), expected);
}
#[test]
fn vcard_name_only_skips_empty_fields() {
let mut p = contact("Acme");
if let Payload::Contact { phone, .. } = &mut p {
*phone = Some(" ".into());
}
assert_eq!(payload_string(&p).unwrap(), "BEGIN:VCARD\r\nVERSION:3.0\r\nN:Acme;;;;\r\nFN:Acme\r\nEND:VCARD\r\n");
}
#[test]
fn empty_inputs_are_rejected() {
assert_eq!(payload_string(&Payload::Text("".into())), Err(QrError::Empty));
assert_eq!(payload_string(&Payload::Text(" \n ".into())), Err(QrError::Empty));
assert!(matches!(payload_string(&Payload::Url(" ".into())), Err(QrError::EmptyField { .. })));
assert!(matches!(payload_string(&contact(" ")), Err(QrError::EmptyField { .. })));
}
#[test]
fn payload_too_long_for_any_qr_code() {
let err = payload_string(&Payload::Text("a".repeat(8000))).unwrap_err();
assert_eq!(err, QrError::TooLong { level: Level::L, logo: false });
assert!(!err.to_string().is_empty());
}
#[test]
fn payload_serde_round_trip() {
let p = Payload::Wifi { ssid: "A".into(), password: "B".into(), security: WifiSecurity::Wep, hidden: true };
let json = serde_json::to_string(&p).unwrap();
assert_eq!(serde_json::from_str::<Payload>(&json).unwrap(), p);
}
+145
View File
@@ -0,0 +1,145 @@
//! Every generated code must decode back to the exact payload string (rqrr), at every level, in colour and with a
//! logo.
mod common;
use common::{decode, decode_with_level, logo, rqrr_level};
use pictor_qr::{Level, Payload, Style, WifiSecurity, payload_string, render_png, render_rgba};
const LEVELS: [Level; 4] = [Level::L, Level::M, Level::Q, Level::H];
fn payloads() -> Vec<(&'static str, String)> {
vec![
("czech text", payload_string(&Payload::Text("Příliš žluťoučký kůň úpěl ďábelské ódy".into())).unwrap()),
("url", payload_string(&Payload::Url("www.example.cz/cesta?q=žluť&x=1".into())).unwrap()),
(
"wifi",
payload_string(&Payload::Wifi {
ssid: r#"Domov; "5G", 2:4\x"#.into(),
password: r#"heslo;:,"\ž"#.into(),
security: WifiSecurity::Wpa,
hidden: true,
})
.unwrap(),
),
(
"vcard",
payload_string(&Payload::Contact {
name: "Jan Novák".into(),
phone: Some("+420 777 123 456".into()),
email: Some("jan.novak@example.cz".into()),
organisation: Some("Domi, s.r.o.".into()),
url: Some("https://example.cz".into()),
address: Some("Dlouhá 12\n110 00 Praha 1".into()),
note: Some("Poznámka; s čárkou, a\nřádkem".into()),
})
.unwrap(),
),
("ascii", "HELLO 12345 hello".to_string()),
]
}
fn navy_on_cream() -> Style {
Style { dark: [16, 32, 96, 255], light: [255, 250, 225, 255], ..Style::default() }
}
#[test]
fn all_payloads_all_levels_black_on_white() {
for (name, text) in payloads() {
for level in LEVELS {
let r = render_rgba(&text, level, &Style::default(), None).unwrap();
assert_eq!(r.level_used, level);
let (decoded, ecc) = decode_with_level(&r.image);
assert_eq!(decoded, text, "{name} at {level:?}");
assert_eq!(ecc, rqrr_level(level), "{name} at {level:?}");
}
}
}
#[test]
fn all_payloads_all_levels_navy_on_cream() {
for (name, text) in payloads() {
for level in LEVELS {
let r = render_rgba(&text, level, &navy_on_cream(), None).unwrap();
assert_eq!(r.image.get_pixel(0, 0).0, [255, 250, 225, 255], "the quiet zone is the light colour");
assert_eq!(decode(&r.image), text, "{name} at {level:?}");
}
}
}
#[test]
fn with_logo_forces_level_h_and_still_decodes() {
let logos = [logo(200, 200), logo(300, 120), logo(40, 90)];
for (name, text) in payloads() {
for lg in &logos {
for level in [Level::L, Level::M] {
let r = render_rgba(&text, level, &navy_on_cream(), Some(lg)).unwrap();
assert_eq!(r.level_used, Level::H, "a logo forces level H");
let (decoded, ecc) = decode_with_level(&r.image);
assert_eq!(decoded, text, "{name} with a {}x{} logo", lg.width(), lg.height());
assert_eq!(ecc, rqrr_level(Level::H));
}
}
}
}
#[test]
fn logo_is_drawn_centred_and_bounded() {
let text = payloads()[0].1.clone();
let style = Style { size_px: 600, ..Style::default() };
let r = render_rgba(&text, Level::M, &style, Some(&logo(100, 100))).unwrap();
let size = r.image.width();
let module_px = r.module_px;
let code_px = r.modules * module_px;
// The logo's red circle is in the middle of the image.
let centre = r.image.get_pixel(size / 2, size / 2).0;
assert_eq!(centre, [200, 20, 40, 255]);
// Nothing red farther than 22% of the code's width / 2 from the centre (plus a pixel of resampling).
let half = (code_px as f64 * 0.22 / 2.0).ceil() as i64 + 1;
for (x, y, p) in r.image.enumerate_pixels() {
if p.0[0] > 150 && p.0[1] < 100 {
let (dx, dy) = (x as i64 - size as i64 / 2, y as i64 - size as i64 / 2);
assert!(dx.abs() <= half && dy.abs() <= half, "logo pixel at {x},{y} outside the 22% box");
}
}
}
#[test]
fn small_payload_with_logo_still_decodes() {
for text in ["Hi", "https://x.cz", "1234567890"] {
let r = render_rgba(text, Level::L, &Style::default(), Some(&logo(64, 64))).unwrap();
assert_eq!(r.level_used, Level::H);
assert_eq!(decode(&r.image), text);
}
}
#[test]
fn size_is_integer_scaled_and_reported() {
let style = Style { size_px: 500, quiet_zone: 4, ..Style::default() };
let r = render_rgba("hello", Level::M, &style, None).unwrap();
let total = r.modules + 2 * 4;
assert_eq!(r.image.width(), r.image.height());
assert_eq!(r.image.width(), r.size_px);
assert_eq!(r.size_px, total * r.module_px);
assert!(r.size_px <= 500 && r.size_px > 500 - total, "{} px", r.size_px);
assert_eq!(r.module_px, 500 / total);
}
#[test]
fn png_decodes_back() {
let text = payloads()[3].1.clone();
let png = render_png(&text, Level::Q, &navy_on_cream(), Some(&logo(50, 50))).unwrap();
assert_eq!(&png[..8], b"\x89PNG\r\n\x1a\n");
let img = image::load_from_memory_with_format(&png, image::ImageFormat::Png).unwrap().to_rgba8();
assert_eq!(decode(&img), text);
}
#[test]
fn quiet_zone_widths_decode() {
for qz in [1, 4, 10] {
let style = Style { quiet_zone: qz, ..Style::default() };
let r = render_rgba("quiet zone", Level::M, &style, None).unwrap();
assert_eq!(r.size_px, (r.modules + 2 * qz) * r.module_px);
assert_eq!(decode(&r.image), "quiet zone");
}
}
+113
View File
@@ -0,0 +1,113 @@
//! SVG output: the structure, and a rasterisation of its module path that must decode back.
mod common;
use common::{decode_gray, logo_png};
use image::{GrayImage, Luma};
use pictor_qr::{Level, QrError, Style, render_rgba, render_svg};
/// The SVG's dark modules as horizontal runs `(x, y, len)` in module units (quiet zone included), parsed from the
/// path's `M{x} {y}h{len}v1h-{len}z` segments.
fn runs(svg: &str) -> Vec<(u32, u32, u32)> {
let start = svg.find(" d=\"").expect("a path with d") + 4;
let end = start + svg[start..].find('"').unwrap();
let d = &svg[start..end];
d.split('M')
.filter(|s| !s.is_empty())
.map(|seg| {
let (xy, rest) = seg.split_once('h').expect("h after M");
let (x, y) = xy.split_once(' ').expect("x y");
let (len, tail) = rest.split_once('v').expect("v after h");
assert_eq!(tail, format!("1h-{len}z"), "segment {seg}");
(x.parse().unwrap(), y.parse().unwrap(), len.parse().unwrap())
})
.collect()
}
fn view_box_size(svg: &str) -> u32 {
let start = svg.find("viewBox=\"0 0 ").unwrap() + 13;
let rest = &svg[start..];
rest[..rest.find(' ').unwrap()].parse().unwrap()
}
fn rasterise(svg: &str, scale: u32) -> GrayImage {
let n = view_box_size(svg);
let mut img = GrayImage::from_pixel(n * scale, n * scale, Luma([255]));
for (x, y, len) in runs(svg) {
for py in y * scale..(y + 1) * scale {
for px in x * scale..(x + len) * scale {
img.put_pixel(px, py, Luma([0]));
}
}
}
img
}
#[test]
fn svg_structure() {
let text = "Příliš žluťoučký kůň";
let style = Style { size_px: 400, ..Style::default() };
let svg = render_svg(text, Level::M, &style, None).unwrap();
assert!(svg.starts_with("<svg "), "{}", &svg[..40]);
assert!(svg.trim_end().ends_with("</svg>"));
assert!(svg.contains("xmlns=\"http://www.w3.org/2000/svg\""));
assert_eq!(svg.matches("<path").count(), 1);
assert!(!svg.contains("<image"));
// Same geometry as the raster output, and as many dark modules as the raster has.
let r = render_rgba(text, Level::M, &style, None).unwrap();
assert_eq!(view_box_size(&svg), r.modules + 8);
assert!(svg.contains(&format!("width=\"{}\" height=\"{}\"", r.size_px, r.size_px)));
let dark_svg: u32 = runs(&svg).iter().map(|r| r.2).sum();
let mut dark_png = 0;
for my in 0..r.modules + 8 {
for mx in 0..r.modules + 8 {
let p = r.image.get_pixel(mx * r.module_px + r.module_px / 2, my * r.module_px + r.module_px / 2);
if p.0[0] < 128 {
dark_png += 1;
}
}
}
assert_eq!(dark_svg, dark_png);
}
#[test]
fn svg_rasterised_decodes_at_all_levels() {
let text = "WIFI:T:WPA;S:Domov\\;5G;P:heslo\\:x;;";
for level in [Level::L, Level::M, Level::Q, Level::H] {
let svg = render_svg(text, level, &Style::default(), None).unwrap();
assert_eq!(decode_gray(rasterise(&svg, 6)).0, text, "{level:?}");
}
}
#[test]
fn svg_colours() {
let style = Style { dark: [16, 32, 96, 255], light: [255, 250, 225, 128], ..Style::default() };
let svg = render_svg("colour", Level::M, &style, None).unwrap();
assert!(svg.contains("fill=\"#102060\""), "{svg}");
assert!(svg.contains("fill=\"#fffae1\" fill-opacity=\"0.502\""), "{svg}");
}
#[test]
fn svg_with_logo_embeds_data_uri_and_clears_modules() {
let text = "https://example.cz/logo";
let png = logo_png(120, 60);
let with = render_svg(text, Level::L, &Style::default(), Some(&png)).unwrap();
let without_h = render_svg(text, Level::H, &Style::default(), None).unwrap();
assert_eq!(with.matches("<image").count(), 1);
assert!(with.contains("xlink:href=\"data:image/png;base64,iVBORw0KGgo"), "a base64 PNG data URI");
assert!(with.contains("preserveAspectRatio=\"xMidYMid meet\""));
// Level H was used (same module count as an H code without a logo), and modules under the plate are gone.
assert_eq!(view_box_size(&with), view_box_size(&without_h));
let dark_with: u32 = runs(&with).iter().map(|r| r.2).sum();
let dark_without: u32 = runs(&without_h).iter().map(|r| r.2).sum();
assert!(dark_with < dark_without);
// The cleared code (without drawing the logo) still decodes.
assert_eq!(decode_gray(rasterise(&with, 6)).0, text);
}
#[test]
fn svg_rejects_a_broken_logo() {
let err = render_svg("x", Level::M, &Style::default(), Some(b"not a png")).unwrap_err();
assert!(matches!(err, QrError::Logo(_)), "{err:?}");
}