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
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
use std::collections::HashMap;
use std::sync::Arc;
use ab_glyph::{Font, PxScale, ScaleFont};
use crate::{
FontManager, ZplError, ZplResult,
ast::parse_zpl,
engine::{backend, common, font, intr},
};
/// Measures the advance width of `text` in dots for the given ZPL font spec.
fn measure_text_dots(
fm: &font::FontManager,
font_char: char,
height: Option<u32>,
width: Option<u32>,
text: &str,
) -> u32 {
let mut buf = [0; 4];
let font_str = font_char.encode_utf8(&mut buf);
let font = match fm.get_font(font_str).or_else(|| fm.get_font("0")) {
Some(f) => f,
None => return 0,
};
let scale_y = height.unwrap_or(9) as f32;
let scale_x = width.unwrap_or(scale_y as u32) as f32;
let scaled = font.as_scaled(PxScale {
x: scale_x,
y: scale_y,
});
let mut w = 0.0_f32;
let mut last = None;
for c in text.chars() {
let gid = font.glyph_id(c);
if let Some(prev) = last {
w += scaled.kern(prev, gid);
}
w += scaled.h_advance(gid);
last = Some(gid);
}
w.ceil() as u32
}
/// Greedy word-wrap for `^FB`: fits words into `max_width` dots, hard-breaking
/// words that are longer than a full line. `\&` acts as an explicit line break.
fn wrap_text_block<F: Fn(&str) -> u32>(text: &str, max_width: u32, measure: F) -> Vec<String> {
let mut lines: Vec<String> = Vec::new();
for segment in text.split("\\&") {
if max_width == 0 {
lines.push(segment.trim().to_string());
continue;
}
let mut current = String::new();
for word in segment.split_whitespace() {
let candidate = if current.is_empty() {
word.to_string()
} else {
format!("{} {}", current, word)
};
if measure(&candidate) <= max_width {
current = candidate;
continue;
}
if !current.is_empty() {
lines.push(std::mem::take(&mut current));
}
// The word alone may still overflow: hard-break it by characters.
if measure(word) > max_width {
let mut piece = String::new();
for ch in word.chars() {
piece.push(ch);
if measure(&piece) > max_width && piece.chars().count() > 1 {
piece.pop();
lines.push(std::mem::take(&mut piece));
piece.push(ch);
}
}
current = piece;
} else {
current = word.to_string();
}
}
lines.push(current);
}
lines
}
/// 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 {
if let common::ZplInstruction::PageBreak = instruction {
backend.new_page()?;
continue;
}
let condition = match instruction {
common::ZplInstruction::PageBreak => continue,
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,
common::ZplInstruction::DataMatrix { condition, .. } => condition,
common::ZplInstruction::Pdf417 { condition, .. } => condition,
common::ZplInstruction::Barcode1D { condition, .. } => condition,
common::ZplInstruction::GraphicDiagonal { condition, .. } => condition,
};
if let Some((var, expected)) = condition
&& variables.get(var) != Some(expected)
{
continue;
}
match instruction {
common::ZplInstruction::PageBreak => {}
common::ZplInstruction::Text {
condition: _,
x,
y,
font,
height,
width,
orientation,
text,
reverse_print,
color,
block,
} => {
let resolved = replace_vars(text, variables);
let Some(b) = block else {
backend.draw_text(
*x,
*y,
*font,
*height,
*width,
*orientation,
&resolved,
*reverse_print,
color.clone(),
)?;
continue;
};
// ^FB: wrap into lines, justify, and place each line
// according to the field orientation.
let measure =
|s: &str| measure_text_dots(&font_manager, *font, *height, *width, s);
let lines = wrap_text_block(&resolved, b.width, measure);
let n_lines = lines.len().min(b.max_lines.max(1) as usize);
let font_h = height.unwrap_or(9) as i32;
let line_advance = (font_h + b.line_spacing).max(1);
let block_span = (n_lines as i32 - 1) * line_advance;
for (i, line) in lines.iter().take(n_lines).enumerate() {
if line.is_empty() {
continue;
}
let lw = measure(line) as i32;
let indent = if i > 0 { b.indent as i32 } else { 0 };
let avail = (b.width as i32 - indent).max(0);
let jx = indent
+ match b.justification {
'C' => (avail - lw).max(0) / 2,
'R' => (avail - lw).max(0),
_ => 0,
};
let ly = i as i32 * line_advance;
// Cell top-left offset, rotated with the field.
let (dx, dy) = match orientation {
'R' => (block_span - ly, jx),
'I' => (b.width as i32 - jx - lw, block_span - ly),
'B' => (ly, b.width as i32 - jx - lw),
_ => (jx, ly),
};
let fx = (*x as i32 + dx).max(0) as u32;
let fy = (*y as i32 + dy).max(0) as u32;
backend.draw_text(
fx,
fy,
*font,
*height,
*width,
*orientation,
line,
*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::Barcode1D {
condition: _,
kind,
x,
y,
orientation,
height,
module_width,
interpretation_line,
interpretation_line_above,
data,
reverse_print,
} => {
backend.draw_barcode_1d(
*kind,
*x,
*y,
*orientation,
*height,
*module_width,
*interpretation_line,
*interpretation_line_above,
&replace_vars(data, variables),
*reverse_print,
)?;
}
common::ZplInstruction::GraphicDiagonal {
condition: _,
x,
y,
width,
height,
thickness,
color,
custom_color,
diagonal_orientation,
reverse_print,
} => {
backend.draw_graphic_diagonal(
*x,
*y,
*width,
*height,
*thickness,
*color,
custom_color.clone(),
*diagonal_orientation,
*reverse_print,
)?;
}
common::ZplInstruction::DataMatrix {
condition: _,
x,
y,
orientation,
module_size,
data,
reverse_print,
} => {
backend.draw_datamatrix(
*x,
*y,
*orientation,
*module_size,
&replace_vars(data, variables),
*reverse_print,
)?;
}
common::ZplInstruction::Pdf417 {
condition: _,
x,
y,
orientation,
row_height,
module_width,
security_level,
data,
reverse_print,
} => {
backend.draw_pdf417(
*x,
*y,
*orientation,
*row_height,
*module_width,
*security_level,
&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)
}
}