[qr] QR: payloads, PNG and SVG, centre logo at level H, round-trip tests
This commit is contained in:
@@ -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");
|
||||
}
|
||||
}
|
||||
@@ -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(())
|
||||
}
|
||||
@@ -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))
|
||||
}
|
||||
@@ -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."
|
||||
)
|
||||
}
|
||||
}
|
||||
@@ -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] }
|
||||
}
|
||||
}
|
||||
@@ -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"));
|
||||
}
|
||||
}
|
||||
@@ -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])
|
||||
}
|
||||
@@ -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() }
|
||||
}
|
||||
Reference in New Issue
Block a user