1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
use std::collections::HashMap;
use std::sync::Arc;
use crate::{
FontManager, ZplError, ZplResult,
ast::parse_zpl,
engine::{backend, common, font, intr},
};
/// The main entry point for processing and rendering ZPL labels.
///
/// `ZplEngine` holds the parsed instructions, label dimensions, and configuration
/// required to render a label using a specific backend.
#[derive(Debug)]
pub struct ZplEngine {
instructions: Vec<common::ZplInstruction>,
width: common::Unit,
height: common::Unit,
resolution: common::Resolution,
fonts: Option<Arc<font::FontManager>>,
}
impl ZplEngine {
/// Creates a new `ZplEngine` instance by parsing a ZPL string.
///
/// # Arguments
/// * `zpl` - The raw ZPL string to parse.
/// * `width` - The physical width of the label.
/// * `height` - The physical height of the label.
/// * `resolution` - The printing resolution (DPI).
///
/// # Errors
/// Returns an error if the ZPL is invalid or if the instruction building fails.
pub fn new(
zpl: &str,
width: common::Unit,
height: common::Unit,
resolution: common::Resolution,
) -> ZplResult<Self> {
let commands = parse_zpl(zpl)?;
if commands.is_empty() {
return Err(ZplError::EmptyInput);
}
let instructions = intr::ZplInstructionBuilder::new(commands);
let instructions = instructions.build()?;
Ok(Self {
instructions,
width,
height,
resolution,
fonts: None,
})
}
/// Sets the font manager to be used during rendering.
///
/// If no font manager is provided, a default one will be used.
pub fn set_fonts(&mut self, fonts: Arc<font::FontManager>) {
self.fonts = Some(fonts);
}
/// Renders the parsed instructions using the provided backend.
///
/// # Arguments
/// * `backend` - An implementation of `ZplForgeBackend` (e.g., PNG, PDF).
/// * `variables` - A map of template variables to replace in text fields (format: `{{key}}`).
///
/// # Errors
/// Returns an error if rendering fails at the backend level.
pub fn render<B: backend::ZplForgeBackend>(
&self,
mut backend: B,
variables: &HashMap<String, String>,
) -> ZplResult<Vec<u8>> {
fn replace_vars<'a>(
s: &'a str,
variables: &HashMap<String, String>,
) -> std::borrow::Cow<'a, str> {
if variables.is_empty() || !s.contains("{{") {
return std::borrow::Cow::Borrowed(s);
}
let mut result = String::new();
let mut last_pos = 0;
let mut found = false;
let mut cursor = 0;
while let Some(start_offset) = s[cursor..].find("{{") {
let start = cursor + start_offset;
if let Some(end_offset) = s[start + 2..].find("}}") {
let end = start + 2 + end_offset;
let key = &s[start + 2..end];
if let Some(value) = variables.get(key) {
if !found {
result.reserve(s.len());
found = true;
}
result.push_str(&s[last_pos..start]);
result.push_str(value);
last_pos = end + 2;
cursor = last_pos;
continue;
}
}
cursor = start + 2;
}
if found {
result.push_str(&s[last_pos..]);
std::borrow::Cow::Owned(result)
} else {
std::borrow::Cow::Borrowed(s)
}
}
let w_dots = self.width.clone().to_dots(self.resolution);
let h_dots = self.height.clone().to_dots(self.resolution);
let font_manager = if let Some(fonts) = &self.fonts {
fonts.clone()
} else {
Arc::new(FontManager::default())
};
backend.setup_page(w_dots as f64, h_dots as f64, self.resolution.dpi());
backend.setup_font_manager(&font_manager);
for instruction in &self.instructions {
let condition = match instruction {
common::ZplInstruction::Text { condition, .. } => condition,
common::ZplInstruction::GraphicBox { condition, .. } => condition,
common::ZplInstruction::GraphicCircle { condition, .. } => condition,
common::ZplInstruction::GraphicEllipse { condition, .. } => condition,
common::ZplInstruction::GraphicField { condition, .. } => condition,
common::ZplInstruction::CustomImage { condition, .. } => condition,
common::ZplInstruction::Code128 { condition, .. } => condition,
common::ZplInstruction::QRCode { condition, .. } => condition,
common::ZplInstruction::Code39 { condition, .. } => condition,
};
if let Some((var, expected)) = condition
&& variables.get(var) != Some(expected)
{
continue;
}
match instruction {
common::ZplInstruction::Text {
condition: _,
x,
y,
font,
height,
width,
text,
reverse_print,
color,
} => {
backend.draw_text(
*x,
*y,
*font,
*height,
*width,
&replace_vars(text, variables),
*reverse_print,
color.clone(),
)?;
}
common::ZplInstruction::GraphicBox {
condition: _,
x,
y,
width,
height,
thickness,
color,
custom_color,
rounding,
reverse_print,
} => {
backend.draw_graphic_box(
*x,
*y,
*width,
*height,
*thickness,
*color,
custom_color.clone(),
*rounding,
*reverse_print,
)?;
}
common::ZplInstruction::GraphicCircle {
condition: _,
x,
y,
radius,
thickness,
color,
custom_color,
reverse_print,
} => {
backend.draw_graphic_circle(
*x,
*y,
*radius,
*thickness,
*color,
custom_color.clone(),
*reverse_print,
)?;
}
common::ZplInstruction::GraphicEllipse {
condition: _,
x,
y,
width,
height,
thickness,
color,
custom_color,
reverse_print,
} => {
backend.draw_graphic_ellipse(
*x,
*y,
*width,
*height,
*thickness,
*color,
custom_color.clone(),
*reverse_print,
)?;
}
common::ZplInstruction::GraphicField {
condition: _,
x,
y,
width,
height,
data,
reverse_print,
} => {
backend.draw_graphic_field(*x, *y, *width, *height, data, *reverse_print)?;
}
common::ZplInstruction::Code128 {
condition: _,
x,
y,
orientation,
height,
module_width,
interpretation_line,
interpretation_line_above,
check_digit,
mode,
data,
reverse_print,
} => {
backend.draw_code128(
*x,
*y,
*orientation,
*height,
*module_width,
*interpretation_line,
*interpretation_line_above,
*check_digit,
*mode,
&replace_vars(data, variables),
*reverse_print,
)?;
}
common::ZplInstruction::QRCode {
condition: _,
x,
y,
orientation,
model,
magnification,
error_correction,
mask,
data,
reverse_print,
} => {
backend.draw_qr_code(
*x,
*y,
*orientation,
*model,
*magnification,
*error_correction,
*mask,
&replace_vars(data, variables),
*reverse_print,
)?;
}
common::ZplInstruction::Code39 {
condition: _,
x,
y,
orientation,
check_digit,
height,
module_width,
interpretation_line,
interpretation_line_above,
data,
reverse_print,
} => {
backend.draw_code39(
*x,
*y,
*orientation,
*check_digit,
*height,
*module_width,
*interpretation_line,
*interpretation_line_above,
&replace_vars(data, variables),
*reverse_print,
)?;
}
common::ZplInstruction::CustomImage {
condition: _,
x,
y,
width,
height,
data,
} => {
backend.draw_graphic_image_custom(*x, *y, *width, *height, data)?;
}
}
}
let result = backend.finalize()?;
Ok(result)
}
}