Skip to main content

qrcode_eps/
lib.rs

1//! EPS rendering support.
2//!
3//! # Example
4//!
5//! ```
6//! use qrcode_core::Color as ModuleColor;
7//! use qrcode_eps::Color;
8//! use qrcode_render::Renderer;
9//!
10//! let modules = [ModuleColor::Dark, ModuleColor::Light, ModuleColor::Light, ModuleColor::Dark];
11//! let eps = Renderer::<Color>::new(&modules, 2, 1).build();
12//! println!("{eps}");
13//! ```
14
15#![cfg_attr(not(feature = "std"), no_std)]
16
17#[cfg(not(feature = "std"))]
18extern crate alloc;
19
20#[cfg(not(feature = "std"))]
21#[allow(unused_imports)]
22use alloc::{
23    borrow::ToOwned,
24    format,
25    string::{String, ToString},
26    vec,
27    vec::Vec,
28};
29
30use core::fmt::Write;
31
32use qrcode_core::Color as ModuleColor;
33use qrcode_render::colors::{CmykColor as SharedCmykColor, ColorSpace, RgbColor};
34use qrcode_render::{Canvas as RenderCanvas, Pixel, StyledPixel};
35
36const MAX_STREAM_PREALLOC: usize = 8 * 1024 * 1024;
37
38fn stream_capacity(width: u32, height: u32) -> usize {
39    // Scaled vector output can cover many pixels with a single rectangle.
40    (width as usize).saturating_mul(height as usize).saturating_mul(20).min(MAX_STREAM_PREALLOC)
41}
42
43fn normalized_component(value: f64) -> f64 {
44    if value.is_nan() || value < 0.0 {
45        0.0
46    } else if value > 1.0 {
47        1.0
48    } else {
49        value
50    }
51}
52
53/// An EPS color (`[R, G, B]`).
54///
55/// Rendering clips components to `0.0..=1.0`, including infinities. NaN is
56/// rendered as `0.0`. Values already in range, including signed zero, are kept.
57#[derive(Copy, Clone, Default, PartialEq, PartialOrd)]
58pub struct Color(pub [f64; 3]);
59
60/// An EPS CMYK color (`[C, M, Y, K]`).
61///
62/// Rendering uses the same component normalization as [`Color`].
63#[derive(Copy, Clone, Default, PartialEq, PartialOrd)]
64pub struct CmykColor(pub [f64; 4]);
65
66impl Pixel for Color {
67    type Canvas = Canvas;
68    type Image = String;
69
70    fn default_color(color: ModuleColor) -> Self {
71        Self(color.select(Default::default(), [1.0; 3]))
72    }
73}
74
75impl StyledPixel for Color {
76    fn from_hex(hex: &str) -> Self {
77        let (r, g, b) = qrcode_render::colors::hex_to_rgb(hex).unwrap_or((0, 0, 0));
78        Self([r as f64 / 255.0, g as f64 / 255.0, b as f64 / 255.0])
79    }
80}
81
82impl From<RgbColor> for Color {
83    fn from(color: RgbColor) -> Self {
84        Self(color.to_array())
85    }
86}
87
88impl Pixel for CmykColor {
89    type Canvas = CmykCanvas;
90    type Image = String;
91
92    fn default_color(color: ModuleColor) -> Self {
93        Self(color.select([0.0, 0.0, 0.0, 1.0], [0.0, 0.0, 0.0, 0.0]))
94    }
95}
96
97impl StyledPixel for CmykColor {
98    fn from_hex(hex: &str) -> Self {
99        let (r, g, b) = qrcode_render::colors::hex_to_rgb(hex).unwrap_or((0, 0, 0));
100        SharedCmykColor::from_rgb(RgbColor::new(r, g, b)).into()
101    }
102}
103
104impl From<SharedCmykColor> for CmykColor {
105    fn from(color: SharedCmykColor) -> Self {
106        Self(color.to_array())
107    }
108}
109
110#[doc(hidden)]
111pub struct Canvas {
112    eps: String,
113    height: u32,
114}
115
116#[doc(hidden)]
117pub struct CmykCanvas {
118    eps: String,
119    height: u32,
120}
121
122impl RenderCanvas for Canvas {
123    type Pixel = Color;
124    type Image = String;
125
126    fn new(width: u32, height: u32, dark_pixel: Color, light_pixel: Color) -> Self {
127        let dark_pixel = Color(dark_pixel.0.map(normalized_component));
128        let light_pixel = Color(light_pixel.0.map(normalized_component));
129        let mut eps = format!(
130            concat!(
131                "%!PS-Adobe-3.0 EPSF-3.0\n",
132                "%%BoundingBox: 0 0 {w} {h}\n",
133                "%%Pages: 1\n",
134                "%%EndComments\n",
135                "gsave\n",
136                "{bgr} {bgg} {bgb} setrgbcolor\n",
137                "0 0 {w} {h} rectfill\n",
138                "grestore\n",
139                "{fgr} {fgg} {fgb} setrgbcolor\n"
140            ),
141            w = width,
142            h = height,
143            fgr = dark_pixel.0[0],
144            fgg = dark_pixel.0[1],
145            fgb = dark_pixel.0[2],
146            bgr = light_pixel.0[0],
147            bgg = light_pixel.0[1],
148            bgb = light_pixel.0[2],
149        );
150        eps.reserve(stream_capacity(width, height));
151        Self { eps, height }
152    }
153
154    fn draw_dark_pixel(&mut self, x: u32, y: u32) {
155        self.draw_dark_rect(x, y, 1, 1);
156    }
157
158    fn draw_dark_rect(&mut self, left: u32, top: u32, width: u32, height: u32) {
159        let bottom = self.height - top - height;
160        writeln!(self.eps, "{left} {bottom} {width} {height} rectfill").unwrap();
161    }
162
163    fn into_image(mut self) -> String {
164        self.eps.push_str("%%EOF");
165        self.eps
166    }
167}
168
169impl RenderCanvas for CmykCanvas {
170    type Pixel = CmykColor;
171    type Image = String;
172
173    fn new(width: u32, height: u32, dark_pixel: CmykColor, light_pixel: CmykColor) -> Self {
174        let dark_pixel = CmykColor(dark_pixel.0.map(normalized_component));
175        let light_pixel = CmykColor(light_pixel.0.map(normalized_component));
176        let mut eps = format!(
177            concat!(
178                "%!PS-Adobe-3.0 EPSF-3.0\n",
179                "%%BoundingBox: 0 0 {w} {h}\n",
180                "%%Pages: 1\n",
181                "%%EndComments\n",
182                "gsave\n",
183                "{bc} {bm} {by} {bk} setcmykcolor\n",
184                "0 0 {w} {h} rectfill\n",
185                "grestore\n",
186                "{fc} {fm} {fy} {fk} setcmykcolor\n"
187            ),
188            w = width,
189            h = height,
190            fc = dark_pixel.0[0],
191            fm = dark_pixel.0[1],
192            fy = dark_pixel.0[2],
193            fk = dark_pixel.0[3],
194            bc = light_pixel.0[0],
195            bm = light_pixel.0[1],
196            by = light_pixel.0[2],
197            bk = light_pixel.0[3],
198        );
199        eps.reserve(stream_capacity(width, height));
200        Self { eps, height }
201    }
202
203    fn draw_dark_pixel(&mut self, x: u32, y: u32) {
204        self.draw_dark_rect(x, y, 1, 1);
205    }
206
207    fn draw_dark_rect(&mut self, left: u32, top: u32, width: u32, height: u32) {
208        let bottom = self.height - top - height;
209        writeln!(self.eps, "{left} {bottom} {width} {height} rectfill").unwrap();
210    }
211
212    fn into_image(mut self) -> String {
213        self.eps.push_str("%%EOF");
214        self.eps
215    }
216}
217
218#[cfg(test)]
219mod tests {
220    use super::{Canvas, CmykCanvas, CmykColor, Color, MAX_STREAM_PREALLOC, normalized_component, stream_capacity};
221    use qrcode_render::{Canvas as RenderCanvas, Renderer, StyledPixel};
222
223    #[test]
224    fn eps_renderer_outputs_bounding_box_and_rects() {
225        let modules =
226            [qrcode_core::Color::Dark, qrcode_core::Color::Light, qrcode_core::Color::Light, qrcode_core::Color::Dark];
227
228        let eps =
229            qrcode_render::Renderer::<Color>::new(&modules, 2, 1).quiet_zone(false).module_dimensions(1, 1).build();
230
231        assert!(eps.starts_with("%!PS-Adobe-3.0 EPSF-3.0"));
232        assert!(eps.contains("%%BoundingBox: 0 0 2 2"));
233        assert!(eps.contains("0 1 1 1 rectfill"));
234        assert!(eps.contains("1 0 1 1 rectfill"));
235        assert!(eps.ends_with("%%EOF"));
236    }
237
238    #[test]
239    fn eps_color_parses_hex_for_templates() {
240        let color = Color::from_hex("#336699");
241
242        assert!((color.0[0] - 0.2).abs() < f64::EPSILON);
243        assert!((color.0[1] - 0.4).abs() < f64::EPSILON);
244        assert!((color.0[2] - 0.6).abs() < f64::EPSILON);
245    }
246
247    #[test]
248    fn eps_cmyk_renderer_outputs_native_cmyk_commands() {
249        let modules =
250            [qrcode_core::Color::Dark, qrcode_core::Color::Light, qrcode_core::Color::Light, qrcode_core::Color::Dark];
251
252        let eps = Renderer::<CmykColor>::new(&modules, 2, 1)
253            .dark_color(CmykColor([1.0, 0.0, 0.0, 0.25]))
254            .light_color(CmykColor([0.0, 0.0, 0.0, 0.0]))
255            .quiet_zone(false)
256            .module_dimensions(1, 1)
257            .build();
258
259        assert!(eps.contains("0 0 0 0 setcmykcolor"));
260        assert!(eps.contains("1 0 0 0.25 setcmykcolor"));
261        assert!(!eps.contains("setrgbcolor"));
262    }
263
264    #[test]
265    fn eps_rgb_rectangles_stay_inside_vertical_bounds() {
266        let mut canvas = Canvas::new(8, 12, Color([0.0; 3]), Color([1.0; 3]));
267        canvas.draw_dark_rect(1, 0, 4, 3);
268        canvas.draw_dark_rect(2, 10, 3, 2);
269        canvas.draw_dark_pixel(0, 11);
270
271        assert!(canvas.into_image().ends_with("1 9 4 3 rectfill\n2 0 3 2 rectfill\n0 0 1 1 rectfill\n%%EOF"));
272    }
273
274    #[test]
275    fn eps_cmyk_rectangles_stay_inside_vertical_bounds() {
276        let mut canvas = CmykCanvas::new(8, 12, CmykColor([0.0, 0.0, 0.0, 1.0]), CmykColor([0.0; 4]));
277        canvas.draw_dark_rect(1, 0, 4, 3);
278        canvas.draw_dark_rect(2, 10, 3, 2);
279        canvas.draw_dark_pixel(0, 11);
280
281        assert!(canvas.into_image().ends_with("1 9 4 3 rectfill\n2 0 3 2 rectfill\n0 0 1 1 rectfill\n%%EOF"));
282    }
283
284    #[test]
285    fn eps_stream_preallocation_is_bounded() {
286        assert_eq!(stream_capacity(u32::MAX, u32::MAX), MAX_STREAM_PREALLOC);
287        assert_eq!(stream_capacity(10_000, 10_000), MAX_STREAM_PREALLOC);
288        assert_eq!(stream_capacity(2, 3), 120);
289        assert_eq!(stream_capacity(0, u32::MAX), 0);
290    }
291
292    #[test]
293    fn eps_normalization_keeps_valid_components_bit_for_bit() {
294        for value in [-0.0, 0.0, f64::from_bits(1), f64::MIN_POSITIVE, 0.2, 0.5, 1.0] {
295            assert_eq!(normalized_component(value).to_bits(), value.to_bits());
296        }
297    }
298
299    #[test]
300    fn eps_rgb_nonfinite_and_out_of_range_components_become_valid_operands() {
301        let mut canvas =
302            Canvas::new(8, 12, Color([f64::NAN, f64::NEG_INFINITY, f64::INFINITY]), Color([1.5, -0.5, 0.25]));
303        canvas.draw_dark_rect(2, 3, 4, 5);
304        let output = canvas.into_image();
305        assert!(output.contains("1 0 0.25 setrgbcolor\n0 0 8 12 rectfill"));
306        assert!(output.ends_with("0 0 1 setrgbcolor\n2 4 4 5 rectfill\n%%EOF"));
307        let canvas = Canvas::new(1, 1, Color([0.0; 3]), Color([f64::NAN, f64::NEG_INFINITY, f64::INFINITY]));
308        assert!(canvas.into_image().contains("0 0 1 setrgbcolor\n0 0 1 1 rectfill"));
309    }
310
311    #[test]
312    fn eps_cmyk_nonfinite_and_out_of_range_components_become_valid_operands() {
313        let mut canvas = CmykCanvas::new(
314            8,
315            12,
316            CmykColor([f64::NAN, f64::NEG_INFINITY, f64::INFINITY, 2.0]),
317            CmykColor([f64::NAN, 1.5, -0.5, 0.5]),
318        );
319        canvas.draw_dark_rect(2, 3, 4, 5);
320        let output = canvas.into_image();
321        assert!(output.contains("0 1 0 0.5 setcmykcolor\n0 0 8 12 rectfill"));
322        assert!(output.ends_with("0 0 1 1 setcmykcolor\n2 4 4 5 rectfill\n%%EOF"));
323    }
324
325    #[test]
326    fn eps_signed_zero_stays_in_background_and_foreground_operands() {
327        let canvas = Canvas::new(1, 1, Color([-0.0, 0.5, 1.0]), Color([1.0, -0.0, 0.5]));
328        let output = canvas.into_image();
329        assert!(output.contains("1 -0 0.5 setrgbcolor\n0 0 1 1 rectfill"));
330        assert!(output.ends_with("-0 0.5 1 setrgbcolor\n%%EOF"));
331    }
332}