| 1 | //! TSPL/TSPL2 output for label printers (first version: whole page as bitmap). |
| 2 | //! |
| 3 | //! The document is first encoded by the unchanged [`crate::escpos::EscPosEncoder`] |
| 4 | //! and that ESC/POS byte stream is rendered into a bitmap by a small emulator |
| 5 | //! (Font A 12×24 cells, ESC a alignment, GS ! size, ESC E bold, GS v 0 raster, |
| 6 | //! GS k barcodes, GS ( k QR codes, ESC d feeds, GS V cut = next label). This keeps |
| 7 | //! the label layout identical to the receipt layout, then |
| 8 | //! [`encode_labels`] wraps it in TSPL: |
| 9 | //! |
| 10 | //! ```text |
| 11 | //! SIZE w mm,h mm / GAP g mm,0 mm (BLINE for black marks, GAP 0,0 continuous) |
| 12 | //! DIRECTION d,0 / REFERENCE 0,0 / CLS / BITMAP x,y,wbytes,h,0,<data> / PRINT 1,1 |
| 13 | //! ``` |
| 14 | //! |
| 15 | //! References: Altec TSPL/TSPL2 programming manual (2023-1-9): SIZE p.1, GAP p.2, |
| 16 | //! GAPDETECT p.4, BLINEDETECT p.5, BLINE p.7, DIRECTION p.12, REFERENCE p.13, |
| 17 | //! CLS, BITMAP p.44 (bit 0 = black dot), PRINT; GETSETTING$ p.211; `<ESC>!?` p.82. |
| 18 | |
| 19 | use ab_glyph::{Font, FontRef, PxScale, ScaleFont}; |
| 20 | use image::{GrayImage, Luma}; |
| 21 | |
| 22 | use crate::dsl::{BarcodeSymbology, QrEcc}; |
| 23 | use crate::label_format::{LabelFormat, MediaKind}; |
| 24 | use crate::raster; |
| 25 | |
| 26 | /// ESC/POS source resolution assumed by Posprint's column model (8 dots/mm). |
| 27 | pub const SOURCE_DOTS_PER_MM: f32 = 8.0; |
| 28 | const CELL_W: f32 = 12.0; |
| 29 | const CELL_H: f32 = 24.0; |
| 30 | const LINE_ADVANCE: f32 = 30.0; |
| 31 | |
| 32 | /// Render an ESC/POS stream (as produced by `EscPosEncoder`) to bitmaps. |
| 33 | /// `source_width` is the printable width in source dots, `scale` the output |
| 34 | /// pixels per source dot. Each `GS V` cut starts a new page. |
| 35 | pub fn render_escpos(bytes: &[u8], source_width: u32, scale: f32) -> Vec<GrayImage> { |
| 36 | let mut r = Renderer::new(source_width, scale); |
| 37 | r.run(bytes); |
| 38 | r.finish() |
| 39 | } |
| 40 | |
| 41 | struct Renderer { |
| 42 | font: FontRef<'static>, |
| 43 | scale: f32, |
| 44 | width: u32, |
| 45 | rows: Vec<u8>, |
| 46 | y: u32, |
| 47 | pages: Vec<GrayImage>, |
| 48 | align: u8, |
| 49 | bold: bool, |
| 50 | size_w: u8, |
| 51 | size_h: u8, |
| 52 | line: Vec<u8>, |
| 53 | after_graphic: bool, |
| 54 | bc_height: u8, |
| 55 | bc_hri: bool, |
| 56 | bc_module: u8, |
| 57 | qr_size: u8, |
| 58 | qr_ecc: QrEcc, |
| 59 | qr_data: Vec<u8>, |
| 60 | } |
| 61 | |
| 62 | impl Renderer { |
| 63 | fn new(source_width: u32, scale: f32) -> Self { |
| 64 | let font = FontRef::try_from_slice(epaint_default_fonts::HACK_REGULAR).expect("bundled font"); |
| 65 | Self { |
| 66 | font, |
| 67 | scale, |
| 68 | width: ((source_width.max(1) as f32) * scale).round().max(1.0) as u32, |
| 69 | rows: Vec::new(), |
| 70 | y: 0, |
| 71 | pages: Vec::new(), |
| 72 | align: 0, |
| 73 | bold: false, |
| 74 | size_w: 1, |
| 75 | size_h: 1, |
| 76 | line: Vec::new(), |
| 77 | after_graphic: false, |
| 78 | bc_height: 162, |
| 79 | bc_hri: false, |
| 80 | bc_module: 3, |
| 81 | qr_size: 3, |
| 82 | qr_ecc: QrEcc::L, |
| 83 | qr_data: Vec::new(), |
| 84 | } |
| 85 | } |
| 86 | |
| 87 | fn px(&self, v: f32) -> u32 { |
| 88 | (v * self.scale).round().max(0.0) as u32 |
| 89 | } |
| 90 | |
| 91 | fn ensure_rows(&mut self, bottom: u32) { |
| 92 | let need = bottom as usize * self.width as usize; |
| 93 | if self.rows.len() < need { |
| 94 | self.rows.resize(need, 255); |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | fn set_dark(&mut self, x: u32, y: u32) { |
| 99 | if x < self.width { |
| 100 | self.ensure_rows(y + 1); |
| 101 | self.rows[y as usize * self.width as usize + x as usize] = 0; |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | fn align_x(&self, w: u32) -> u32 { |
| 106 | let free = self.width.saturating_sub(w); |
| 107 | match self.align { |
| 108 | 1 => free / 2, |
| 109 | 2 => free, |
| 110 | _ => 0, |
| 111 | } |
| 112 | } |
| 113 | |
| 114 | fn blit(&mut self, img: &GrayImage) { |
| 115 | let x0 = self.align_x(img.width()); |
| 116 | let y0 = self.y; |
| 117 | for (x, y, p) in img.enumerate_pixels() { |
| 118 | if p.0[0] < 128 { |
| 119 | self.set_dark(x0 + x, y0 + y); |
| 120 | } |
| 121 | } |
| 122 | self.y += img.height(); |
| 123 | self.ensure_rows(self.y); |
| 124 | self.after_graphic = true; |
| 125 | } |
| 126 | |
| 127 | fn flush_line(&mut self) { |
| 128 | let text = std::mem::take(&mut self.line); |
| 129 | if text.is_empty() { |
| 130 | if self.after_graphic { |
| 131 | // LF after a graphic flushes it; keep a small gap (1 mm at |
| 132 | // 8 dots/mm) instead of a full blank line to save label space. |
| 133 | self.after_graphic = false; |
| 134 | self.y += self.px(8.0); |
| 135 | self.ensure_rows(self.y); |
| 136 | return; |
| 137 | } |
| 138 | self.y += self.px(LINE_ADVANCE * self.size_h as f32); |
| 139 | self.ensure_rows(self.y); |
| 140 | return; |
| 141 | } |
| 142 | self.after_graphic = false; |
| 143 | let cw = CELL_W * self.scale * self.size_w as f32; |
| 144 | let ch = CELL_H * self.scale * self.size_h as f32; |
| 145 | let line_w = (cw * text.len() as f32).round() as u32; |
| 146 | let x0 = self.align_x(line_w) as f32; |
| 147 | let y0 = self.y as f32; |
| 148 | // Hack: advance ≈ 0.602 em; fit the advance to the cell width. |
| 149 | let gid = self.font.glyph_id('M'); |
| 150 | let unscaled_adv = self.font.h_advance_unscaled(gid); |
| 151 | let upem = self.font.units_per_em().unwrap_or(2048.0); |
| 152 | let sx = cw * upem / unscaled_adv; |
| 153 | let sy = ch * 0.85 / ((self.font.ascent_unscaled() - self.font.descent_unscaled()) / upem); |
| 154 | let pxs = PxScale { x: sx / upem * upem, y: sy }; |
| 155 | let scaled = self.font.as_scaled(pxs); |
| 156 | let baseline = y0 + (ch - (scaled.ascent() - scaled.descent())) / 2.0 + scaled.ascent(); |
| 157 | let mut dots: Vec<(u32, u32)> = Vec::new(); |
| 158 | for (i, b) in text.iter().enumerate() { |
| 159 | let c = *b as char; |
| 160 | if c == ' ' { |
| 161 | continue; |
| 162 | } |
| 163 | let glyph = scaled.scaled_glyph(c); |
| 164 | let mut glyph = glyph; |
| 165 | glyph.position = ab_glyph::point(x0 + cw * i as f32, baseline); |
| 166 | if let Some(outlined) = self.font.outline_glyph(glyph) { |
| 167 | let bounds = outlined.px_bounds(); |
| 168 | outlined.draw(|gx, gy, cov| { |
| 169 | if cov >= 0.5 { |
| 170 | let x = bounds.min.x + gx as f32; |
| 171 | let y = bounds.min.y + gy as f32; |
| 172 | if x >= 0.0 && y >= 0.0 { |
| 173 | dots.push((x as u32, y as u32)); |
| 174 | } |
| 175 | } |
| 176 | }); |
| 177 | } |
| 178 | } |
| 179 | let bold_px = if self.bold || self.size_w > 1 { (self.scale.round() as u32).max(1) } else { 0 }; |
| 180 | for (x, y) in dots { |
| 181 | self.set_dark(x, y); |
| 182 | for d in 1..=bold_px { |
| 183 | self.set_dark(x + d, y); |
| 184 | } |
| 185 | } |
| 186 | self.y += self.px(LINE_ADVANCE * self.size_h as f32).max(ch.ceil() as u32); |
| 187 | self.ensure_rows(self.y); |
| 188 | } |
| 189 | |
| 190 | fn cut(&mut self) { |
| 191 | if !self.line.is_empty() { |
| 192 | self.flush_line(); |
| 193 | } |
| 194 | let rows = std::mem::take(&mut self.rows); |
| 195 | let h = (rows.len() / self.width as usize) as u32; |
| 196 | if h > 0 { |
| 197 | if let Some(img) = GrayImage::from_raw(self.width, h, rows) { |
| 198 | self.pages.push(img); |
| 199 | } |
| 200 | } |
| 201 | self.y = 0; |
| 202 | self.after_graphic = false; |
| 203 | } |
| 204 | |
| 205 | fn finish(mut self) -> Vec<GrayImage> { |
| 206 | self.cut(); |
| 207 | self.pages |
| 208 | .into_iter() |
| 209 | .filter_map(trim_bottom) |
| 210 | .collect() |
| 211 | } |
| 212 | |
| 213 | fn barcode(&mut self, m: u8, data: &[u8]) { |
| 214 | let sym = match m { |
| 215 | 65 | 0 => Some(BarcodeSymbology::UpcA), |
| 216 | 66 | 1 => Some(BarcodeSymbology::UpcE), |
| 217 | 67 | 2 => Some(BarcodeSymbology::Ean13), |
| 218 | 68 | 3 => Some(BarcodeSymbology::Ean8), |
| 219 | 69 | 4 => Some(BarcodeSymbology::Code39), |
| 220 | 70 | 5 => Some(BarcodeSymbology::Itf), |
| 221 | 71 | 6 => Some(BarcodeSymbology::Codabar), |
| 222 | 73 => Some(BarcodeSymbology::Code128), |
| 223 | _ => None, |
| 224 | }; |
| 225 | let text = String::from_utf8_lossy(data).to_string(); |
| 226 | let Some(sym) = sym else { return }; |
| 227 | let height = self.px(self.bc_height as f32).max(1); |
| 228 | let Ok(img) = raster::render_barcode(sym, &text, height) else { |
| 229 | return; |
| 230 | }; |
| 231 | // Integer module width so bars stay scannable after scaling. |
| 232 | let mut k = ((self.bc_module as f32) * self.scale).round().max(1.0) as u32; |
| 233 | while k > 1 && img.width() * k > self.width { |
| 234 | k -= 1; |
| 235 | } |
| 236 | let scaled = image::imageops::resize(&img, img.width() * k, img.height(), image::imageops::FilterType::Nearest); |
| 237 | let scaled = if scaled.width() > self.width { |
| 238 | raster::scale_gray_to_print_width(scaled, self.width) |
| 239 | } else { |
| 240 | scaled |
| 241 | }; |
| 242 | self.blit(&scaled); |
| 243 | if self.bc_hri { |
| 244 | let saved = self.align; |
| 245 | self.line = text.into_bytes(); |
| 246 | self.after_graphic = false; |
| 247 | self.align = 1; |
| 248 | self.flush_line(); |
| 249 | self.align = saved; |
| 250 | self.after_graphic = true; |
| 251 | } |
| 252 | } |
| 253 | |
| 254 | fn qr(&mut self) { |
| 255 | let data = String::from_utf8_lossy(&self.qr_data).to_string(); |
| 256 | let module = ((self.qr_size.max(1) as f32) * self.scale).round().max(1.0) as u32; |
| 257 | if let Ok(img) = raster::render_qr(&data, None, self.qr_ecc, module) { |
| 258 | // Quiet zone of 2 modules so the code scans next to label edges/text. |
| 259 | let pad = module * 2; |
| 260 | let mut framed = GrayImage::from_pixel(img.width() + 2 * pad, img.height() + 2 * pad, Luma([255])); |
| 261 | image::imageops::overlay(&mut framed, &img, i64::from(pad), i64::from(pad)); |
| 262 | self.blit(&framed); |
| 263 | } |
| 264 | } |
| 265 | |
| 266 | fn raster(&mut self, wbytes: usize, h: usize, data: &[u8]) { |
| 267 | let w = (wbytes * 8) as u32; |
| 268 | let mut img = GrayImage::from_pixel(w.max(1), (h as u32).max(1), Luma([255])); |
| 269 | for y in 0..h { |
| 270 | for x in 0..w as usize { |
| 271 | let byte = data.get(y * wbytes + x / 8).copied().unwrap_or(0); |
| 272 | if byte & (0x80 >> (x % 8)) != 0 { |
| 273 | img.put_pixel(x as u32, y as u32, Luma([0])); |
| 274 | } |
| 275 | } |
| 276 | } |
| 277 | let nw = self.px(w as f32).max(1); |
| 278 | let nh = self.px(h as f32).max(1); |
| 279 | let img = if (self.scale - 1.0).abs() < f32::EPSILON { |
| 280 | img |
| 281 | } else { |
| 282 | image::imageops::resize(&img, nw, nh, image::imageops::FilterType::Triangle) |
| 283 | }; |
| 284 | let img = threshold(&img); |
| 285 | self.blit(&img); |
| 286 | } |
| 287 | |
| 288 | fn run(&mut self, b: &[u8]) { |
| 289 | let mut i = 0; |
| 290 | let get = |i: usize| b.get(i).copied().unwrap_or(0); |
| 291 | while i < b.len() { |
| 292 | let c = b[i]; |
| 293 | match c { |
| 294 | 0x1B => { |
| 295 | let cmd = get(i + 1); |
| 296 | match cmd { |
| 297 | b'@' => { |
| 298 | self.align = 0; |
| 299 | self.bold = false; |
| 300 | self.size_w = 1; |
| 301 | self.size_h = 1; |
| 302 | i += 2; |
| 303 | } |
| 304 | b'a' => { |
| 305 | self.align = get(i + 2) % 48 % 3; |
| 306 | i += 3; |
| 307 | } |
| 308 | b'E' => { |
| 309 | self.bold = get(i + 2) & 1 == 1; |
| 310 | i += 3; |
| 311 | } |
| 312 | b'd' => { |
| 313 | if !self.line.is_empty() { |
| 314 | self.flush_line(); |
| 315 | } |
| 316 | self.after_graphic = false; |
| 317 | self.y += self.px(LINE_ADVANCE) * get(i + 2) as u32; |
| 318 | self.ensure_rows(self.y); |
| 319 | i += 3; |
| 320 | } |
| 321 | b't' | b'M' | b'-' | b'!' | b'2' => { |
| 322 | i += if cmd == b'2' { 2 } else { 3 }; |
| 323 | } |
| 324 | _ => i += 2, |
| 325 | } |
| 326 | } |
| 327 | 0x1D => { |
| 328 | let cmd = get(i + 1); |
| 329 | match cmd { |
| 330 | b'!' => { |
| 331 | let n = get(i + 2); |
| 332 | self.size_w = ((n >> 4) & 7) + 1; |
| 333 | self.size_h = (n & 7) + 1; |
| 334 | i += 3; |
| 335 | } |
| 336 | b'V' => { |
| 337 | let m = get(i + 2); |
| 338 | i += if m == 65 || m == 66 { 4 } else { 3 }; |
| 339 | self.cut(); |
| 340 | } |
| 341 | b'h' => { |
| 342 | self.bc_height = get(i + 2).max(1); |
| 343 | i += 3; |
| 344 | } |
| 345 | b'H' => { |
| 346 | self.bc_hri = get(i + 2) % 48 != 0; |
| 347 | i += 3; |
| 348 | } |
| 349 | b'w' => { |
| 350 | self.bc_module = get(i + 2).clamp(1, 6); |
| 351 | i += 3; |
| 352 | } |
| 353 | b'k' => { |
| 354 | let m = get(i + 2); |
| 355 | if m >= 65 { |
| 356 | let n = get(i + 3) as usize; |
| 357 | let start = (i + 4).min(b.len()); |
| 358 | let end = (start + n).min(b.len()); |
| 359 | let data = b[start..end].to_vec(); |
| 360 | self.barcode(m, &data); |
| 361 | i = end; |
| 362 | } else { |
| 363 | let start = (i + 3).min(b.len()); |
| 364 | let end = b[start..].iter().position(|&x| x == 0).map(|p| start + p).unwrap_or(b.len()); |
| 365 | let data = b[start..end].to_vec(); |
| 366 | self.barcode(m, &data); |
| 367 | i = (end + 1).min(b.len()); |
| 368 | } |
| 369 | } |
| 370 | b'(' if get(i + 2) == b'k' => { |
| 371 | let len = get(i + 3) as usize | (get(i + 4) as usize) << 8; |
| 372 | let start = (i + 5).min(b.len()); |
| 373 | let end = (start + len).min(b.len()); |
| 374 | let p = &b[start..end]; |
| 375 | if p.len() >= 3 && p[0] == 49 { |
| 376 | match p[1] { |
| 377 | 67 => self.qr_size = p[2].clamp(1, 16), |
| 378 | 69 => { |
| 379 | self.qr_ecc = match p[2] { |
| 380 | 49 => QrEcc::M, |
| 381 | 50 => QrEcc::Q, |
| 382 | 51 => QrEcc::H, |
| 383 | _ => QrEcc::L, |
| 384 | } |
| 385 | } |
| 386 | 80 => self.qr_data = p[3..].to_vec(), |
| 387 | 81 => self.qr(), |
| 388 | _ => {} |
| 389 | } |
| 390 | } |
| 391 | i = end; |
| 392 | } |
| 393 | b'v' if get(i + 2) == 0x30 => { |
| 394 | let wb = get(i + 4) as usize | (get(i + 5) as usize) << 8; |
| 395 | let h = get(i + 6) as usize | (get(i + 7) as usize) << 8; |
| 396 | let start = (i + 8).min(b.len()); |
| 397 | let end = (start + wb * h).min(b.len()); |
| 398 | let data = b[start..end].to_vec(); |
| 399 | if !self.line.is_empty() { |
| 400 | self.flush_line(); |
| 401 | } |
| 402 | self.raster(wb, h, &data); |
| 403 | i = end; |
| 404 | } |
| 405 | _ => i += 2, |
| 406 | } |
| 407 | } |
| 408 | b'\n' => { |
| 409 | self.flush_line(); |
| 410 | i += 1; |
| 411 | } |
| 412 | b'\r' => i += 1, |
| 413 | 0x20..=0x7E => { |
| 414 | self.line.push(c); |
| 415 | i += 1; |
| 416 | } |
| 417 | _ => { |
| 418 | self.line.push(b'?'); |
| 419 | i += 1; |
| 420 | } |
| 421 | } |
| 422 | } |
| 423 | } |
| 424 | } |
| 425 | |
| 426 | fn threshold(img: &GrayImage) -> GrayImage { |
| 427 | let mut out = img.clone(); |
| 428 | for p in out.pixels_mut() { |
| 429 | p.0[0] = if p.0[0] < 128 { 0 } else { 255 }; |
| 430 | } |
| 431 | out |
| 432 | } |
| 433 | |
| 434 | /// Drop trailing white rows (receipt feeds before a cut); `None` if blank. |
| 435 | fn trim_bottom(img: GrayImage) -> Option<GrayImage> { |
| 436 | let (w, h) = img.dimensions(); |
| 437 | let mut last = None; |
| 438 | for y in (0..h).rev() { |
| 439 | if (0..w).any(|x| img.get_pixel(x, y).0[0] < 128) { |
| 440 | last = Some(y); |
| 441 | break; |
| 442 | } |
| 443 | } |
| 444 | let last = last?; |
| 445 | Some(image::imageops::crop_imm(&img, 0, 0, w, last + 1).to_image()) |
| 446 | } |
| 447 | |
| 448 | /// Scale (output dots per source dot) so the page fits the label width. |
| 449 | pub fn page_scale(source_width: u32, format: &LabelFormat) -> f32 { |
| 450 | let dpmm = format.dots_per_mm() as f32; |
| 451 | let natural = dpmm / SOURCE_DOTS_PER_MM; |
| 452 | let label_w = format.width_mm * dpmm; |
| 453 | let fit = label_w / source_width.max(1) as f32; |
| 454 | natural.min(fit) |
| 455 | } |
| 456 | |
| 457 | fn fmt_mm(v: f32) -> String { |
| 458 | let s = format!("{:.2}", v); |
| 459 | let s = s.trim_end_matches('0').trim_end_matches('.'); |
| 460 | s.to_string() |
| 461 | } |
| 462 | |
| 463 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
| 464 | pub struct TsplOptions { |
| 465 | /// Send GAPDETECT/BLINEDETECT with the label size first (sensor calibration; |
| 466 | /// the printer feeds a few labels). |
| 467 | pub calibrate: bool, |
| 468 | } |
| 469 | |
| 470 | /// TSPL header lines for a label format (CRLF terminated). |
| 471 | pub fn setup_commands(format: &LabelFormat, label_height_mm: f32, opts: TsplOptions) -> String { |
| 472 | let mut s = String::new(); |
| 473 | s.push_str(&format!("SIZE {} mm,{} mm\r\n", fmt_mm(format.width_mm), fmt_mm(label_height_mm))); |
| 474 | match format.media { |
| 475 | MediaKind::Gap => s.push_str(&format!("GAP {} mm,0 mm\r\n", fmt_mm(format.gap_mm))), |
| 476 | MediaKind::BlackMark => s.push_str(&format!("BLINE {} mm,0 mm\r\n", fmt_mm(format.gap_mm))), |
| 477 | MediaKind::Continuous => s.push_str("GAP 0,0\r\n"), |
| 478 | } |
| 479 | if opts.calibrate { |
| 480 | let dpmm = format.dots_per_mm() as f32; |
| 481 | let x = (label_height_mm * dpmm).round() as u32; |
| 482 | let y = (format.gap_mm * dpmm).round() as u32; |
| 483 | match format.media { |
| 484 | MediaKind::Gap => s.push_str(&format!("GAPDETECT {x},{y}\r\n")), |
| 485 | MediaKind::BlackMark => s.push_str(&format!("BLINEDETECT {x},{y}\r\n")), |
| 486 | MediaKind::Continuous => {} |
| 487 | } |
| 488 | } |
| 489 | s.push_str(&format!("DIRECTION {},0\r\n", if format.rotate_180 { 1 } else { 0 })); |
| 490 | s.push_str("REFERENCE 0,0\r\n"); |
| 491 | s |
| 492 | } |
| 493 | |
| 494 | /// TSPL `BITMAP` data: 1 bit per dot, MSB first, **0 = black** (manual p.44). |
| 495 | pub fn bitmap_bytes(img: &GrayImage) -> (usize, Vec<u8>) { |
| 496 | let (w, h) = img.dimensions(); |
| 497 | let wb = (w as usize).div_ceil(8); |
| 498 | let mut out = vec![0xFFu8; wb * h as usize]; |
| 499 | for (x, y, p) in img.enumerate_pixels() { |
| 500 | if p.0[0] < 128 { |
| 501 | out[y as usize * wb + x as usize / 8] &= !(0x80 >> (x % 8)); |
| 502 | } |
| 503 | } |
| 504 | (wb, out) |
| 505 | } |
| 506 | |
| 507 | /// Build a complete TSPL job for already-rendered pages. Pages taller than the |
| 508 | /// label are split over several labels; each page is centred horizontally. |
| 509 | pub fn encode_pages(pages: &[GrayImage], format: &LabelFormat, opts: TsplOptions) -> Vec<u8> { |
| 510 | let dpmm = format.dots_per_mm(); |
| 511 | let label_w = (format.width_mm * dpmm as f32).round() as u32; |
| 512 | let mut chunks: Vec<GrayImage> = Vec::new(); |
| 513 | let continuous = format.media == MediaKind::Continuous; |
| 514 | let label_h = (format.height_mm * dpmm as f32).round().max(1.0) as u32; |
| 515 | for page in pages { |
| 516 | if continuous { |
| 517 | chunks.push(page.clone()); |
| 518 | continue; |
| 519 | } |
| 520 | let mut y = 0; |
| 521 | while y < page.height() { |
| 522 | let h = label_h.min(page.height() - y); |
| 523 | chunks.push(image::imageops::crop_imm(page, 0, y, page.width(), h).to_image()); |
| 524 | y += h; |
| 525 | } |
| 526 | } |
| 527 | let mut out = Vec::new(); |
| 528 | let height_mm = |c: &GrayImage| { |
| 529 | if continuous { |
| 530 | (c.height() as f32 / dpmm as f32).max(5.0) |
| 531 | } else { |
| 532 | format.height_mm |
| 533 | } |
| 534 | }; |
| 535 | let first_h = chunks.first().map(height_mm).unwrap_or(format.height_mm); |
| 536 | out.extend_from_slice(setup_commands(format, first_h, opts).as_bytes()); |
| 537 | let mut current_h = first_h; |
| 538 | for c in &chunks { |
| 539 | let h_mm = height_mm(c); |
| 540 | if (h_mm - current_h).abs() > f32::EPSILON { |
| 541 | out.extend_from_slice(format!("SIZE {} mm,{} mm\r\n", fmt_mm(format.width_mm), fmt_mm(h_mm)).as_bytes()); |
| 542 | current_h = h_mm; |
| 543 | } |
| 544 | let (wb, data) = bitmap_bytes(c); |
| 545 | let x = label_w.saturating_sub(c.width()) / 2; |
| 546 | out.extend_from_slice(b"CLS\r\n"); |
| 547 | out.extend_from_slice(format!("BITMAP {x},0,{wb},{},0,", c.height()).as_bytes()); |
| 548 | out.extend_from_slice(&data); |
| 549 | out.extend_from_slice(b"\r\nPRINT 1,1\r\n"); |
| 550 | } |
| 551 | out |
| 552 | } |
| 553 | |
| 554 | /// ESC/POS bytes (from `EscPosEncoder`) → TSPL job for `format`. |
| 555 | pub fn escpos_to_tspl(escpos: &[u8], source_width: u32, format: &LabelFormat, opts: TsplOptions) -> Vec<u8> { |
| 556 | let scale = page_scale(source_width, format); |
| 557 | let pages = render_escpos(escpos, source_width, scale); |
| 558 | encode_pages(&pages, format, opts) |
| 559 | } |
| 560 | |
| 561 | /// TSPL status query `<ESC>!?` (manual p.82). |
| 562 | pub const STATUS_QUERY: &[u8] = &[0x1B, b'!', b'?']; |
| 563 | |
| 564 | /// Settings that can be read back over a bidirectional link (manual p.211). |
| 565 | pub const QUERY_PAPER_WIDTH: &str = "OUT GETSETTING$(\"CONFIG\",\"TSPL\",\"PAPER WIDTH\")\r\n"; |
| 566 | pub const QUERY_PAPER_SIZE: &str = "OUT GETSETTING$(\"CONFIG\",\"TSPL\",\"PAPER SIZE\")\r\n"; |
| 567 | pub const QUERY_GAP_SIZE: &str = "OUT GETSETTING$(\"CONFIG\",\"TSPL\",\"GAP SIZE\")\r\n"; |
| 568 | pub const QUERY_DPI: &str = "OUT GETSETTING$(\"SYSTEM\",\"INFORMATION\",\"DPI\")\r\n"; |
| 569 | |
| 570 | /// Status byte meaning (manual p.82), `None` = ready. |
| 571 | pub fn status_problem(byte: u8) -> Option<StatusProblem> { |
| 572 | if byte == 0 || byte == 0x20 { |
| 573 | return None; |
| 574 | } |
| 575 | Some(if byte & 0x01 != 0 { |
| 576 | StatusProblem::HeadOpen |
| 577 | } else if byte & 0x04 != 0 { |
| 578 | StatusProblem::OutOfPaper |
| 579 | } else if byte & 0x08 != 0 { |
| 580 | StatusProblem::OutOfRibbon |
| 581 | } else if byte & 0x02 != 0 { |
| 582 | StatusProblem::PaperJam |
| 583 | } else if byte & 0x10 != 0 { |
| 584 | StatusProblem::Paused |
| 585 | } else { |
| 586 | StatusProblem::Other |
| 587 | }) |
| 588 | } |
| 589 | |
| 590 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 591 | pub enum StatusProblem { |
| 592 | HeadOpen, |
| 593 | PaperJam, |
| 594 | OutOfPaper, |
| 595 | OutOfRibbon, |
| 596 | Paused, |
| 597 | Other, |
| 598 | } |
| 599 | |
| 600 | /// Parse a length reply from GETSETTING$ into mm. Units are only trusted when |
| 601 | /// explicit (`mm`, `inch`/`"`, `dot`); a bare number is assumed to be dots only |
| 602 | /// when `dpmm` is known and the value is clearly in dots range. Returns `None` |
| 603 | /// when unsure, so the dialog asks the user instead. |
| 604 | pub fn parse_length_mm(reply: &str, dpmm: Option<u32>) -> Option<f32> { |
| 605 | let r = reply.trim().trim_matches(char::from(0)).trim().to_ascii_lowercase(); |
| 606 | let num: String = r |
| 607 | .chars() |
| 608 | .skip_while(|c| !c.is_ascii_digit()) |
| 609 | .take_while(|c| c.is_ascii_digit() || *c == '.') |
| 610 | .collect(); |
| 611 | let v: f32 = num.parse().ok()?; |
| 612 | if !v.is_finite() || v <= 0.0 { |
| 613 | return None; |
| 614 | } |
| 615 | let mm = if r.contains("mm") { |
| 616 | v |
| 617 | } else if r.contains("inch") || r.contains('"') { |
| 618 | v * 25.4 |
| 619 | } else if r.contains("dot") { |
| 620 | v / dpmm? as f32 |
| 621 | } else { |
| 622 | return None; |
| 623 | }; |
| 624 | Some(mm) |
| 625 | } |
| 626 | |
| 627 | pub fn parse_dpi(reply: &str) -> Option<u16> { |
| 628 | let n: String = reply.chars().filter(|c| c.is_ascii_digit()).collect(); |
| 629 | match n.parse::<u16>().ok()? { |
| 630 | 200 | 203 => Some(203), |
| 631 | 300 => Some(300), |
| 632 | 600 => Some(600), |
| 633 | _ => None, |
| 634 | } |
| 635 | } |
| 636 | |
| 637 | #[cfg(test)] |
| 638 | mod tests { |
| 639 | use super::*; |
| 640 | use crate::escpos::EscPosEncoder; |
| 641 | use crate::io::PosMetadata; |
| 642 | |
| 643 | fn fmt(w: f32, h: f32) -> LabelFormat { |
| 644 | LabelFormat { width_mm: w, height_mm: h, gap_mm: 3.0, media: MediaKind::Gap, dpi: 300, rotate_180: false } |
| 645 | } |
| 646 | |
| 647 | fn split_cmds(job: &[u8]) -> Vec<String> { |
| 648 | // Text lines only (BITMAP data is binary): keep the line prefix up to data. |
| 649 | let mut out = Vec::new(); |
| 650 | let mut i = 0; |
| 651 | while i < job.len() { |
| 652 | let end = job[i..].windows(2).position(|w| w == b"\r\n").map(|p| i + p).unwrap_or(job.len()); |
| 653 | let line = &job[i..end]; |
| 654 | if line.starts_with(b"BITMAP ") { |
| 655 | let hdr: Vec<u8> = line.iter().take_while(|_| true).copied().collect(); |
| 656 | // header = first 5 commas |
| 657 | let mut commas = 0; |
| 658 | let mut k = 0; |
| 659 | while k < hdr.len() && commas < 5 { |
| 660 | if hdr[k] == b',' { |
| 661 | commas += 1; |
| 662 | } |
| 663 | k += 1; |
| 664 | } |
| 665 | let head = String::from_utf8_lossy(&hdr[..k]).to_string(); |
| 666 | let parts: Vec<usize> = head.trim_start_matches("BITMAP ").trim_end_matches(',').split(',').map(|s| s.parse().unwrap()).collect(); |
| 667 | let data_len = parts[2] * parts[3]; |
| 668 | out.push(head); |
| 669 | i = i + k + data_len; |
| 670 | assert_eq!(&job[i..i + 2], b"\r\n", "bitmap data length must match header"); |
| 671 | i += 2; |
| 672 | continue; |
| 673 | } |
| 674 | out.push(String::from_utf8_lossy(line).to_string()); |
| 675 | i = end + 2; |
| 676 | } |
| 677 | out |
| 678 | } |
| 679 | |
| 680 | #[test] |
| 681 | fn header_matches_spec_syntax() { |
| 682 | let s = setup_commands(&fmt(50.0, 30.0), 30.0, TsplOptions::default()); |
| 683 | assert_eq!(s, "SIZE 50 mm,30 mm\r\nGAP 3 mm,0 mm\r\nDIRECTION 0,0\r\nREFERENCE 0,0\r\n"); |
| 684 | let mut f = fmt(101.6, 25.4); |
| 685 | f.media = MediaKind::BlackMark; |
| 686 | f.gap_mm = 2.5; |
| 687 | f.rotate_180 = true; |
| 688 | let s = setup_commands(&f, 25.4, TsplOptions { calibrate: true }); |
| 689 | assert_eq!( |
| 690 | s, |
| 691 | "SIZE 101.6 mm,25.4 mm\r\nBLINE 2.5 mm,0 mm\r\nBLINEDETECT 305,30\r\nDIRECTION 1,0\r\nREFERENCE 0,0\r\n" |
| 692 | ); |
| 693 | f.media = MediaKind::Continuous; |
| 694 | let s = setup_commands(&f, 40.0, TsplOptions { calibrate: true }); |
| 695 | assert!(s.contains("GAP 0,0\r\n") && !s.contains("DETECT")); |
| 696 | let g = setup_commands(&fmt(50.0, 30.0), 30.0, TsplOptions { calibrate: true }); |
| 697 | assert!(g.contains("GAPDETECT 360,36\r\n")); |
| 698 | } |
| 699 | |
| 700 | #[test] |
| 701 | fn bitmap_zero_is_black() { |
| 702 | let mut img = GrayImage::from_pixel(10, 2, Luma([255])); |
| 703 | img.put_pixel(0, 0, Luma([0])); |
| 704 | img.put_pixel(9, 1, Luma([0])); |
| 705 | let (wb, data) = bitmap_bytes(&img); |
| 706 | assert_eq!(wb, 2); |
| 707 | assert_eq!(data, vec![0x7F, 0xFF, 0xFF, 0xBF]); |
| 708 | } |
| 709 | |
| 710 | #[test] |
| 711 | fn full_job_structure() { |
| 712 | let doc = crate::dsl::parse("# Hello\nWorld\n@barcode CODE128 ABC123\n@qr hi\n@cut\n").unwrap(); |
| 713 | let md = PosMetadata { page_width_mm: 58.0, ..Default::default() }; |
| 714 | let mut enc = EscPosEncoder::new(md.clone()); |
| 715 | let esc = enc.encode_document(&doc).unwrap().to_vec(); |
| 716 | let job = escpos_to_tspl(&esc, md.printable_dots() as u32, &fmt(100.0, 150.0), TsplOptions::default()); |
| 717 | let cmds = split_cmds(&job); |
| 718 | assert_eq!(cmds[0], "SIZE 100 mm,150 mm"); |
| 719 | assert_eq!(cmds[1], "GAP 3 mm,0 mm"); |
| 720 | assert_eq!(cmds[2], "DIRECTION 0,0"); |
| 721 | assert_eq!(cmds[3], "REFERENCE 0,0"); |
| 722 | assert_eq!(cmds[4], "CLS"); |
| 723 | assert!(cmds[5].starts_with("BITMAP ")); |
| 724 | assert_eq!(cmds[6], "PRINT 1,1"); |
| 725 | assert_eq!(cmds.len(), 7); |
| 726 | // 58 mm doc (384 source dots) at 300 dpi → 576 dots = 72 bytes, centred on 1200 dots. |
| 727 | let parts: Vec<u32> = cmds[5][7..].trim_end_matches(',').split(',').map(|s| s.parse().unwrap()).collect(); |
| 728 | assert_eq!(parts[2], 72); |
| 729 | assert_eq!(parts[0], (1200 - 576) / 2); |
| 730 | assert_eq!(parts[1], 0); |
| 731 | assert_eq!(parts[4], 0); |
| 732 | assert!(parts[3] > 100); |
| 733 | } |
| 734 | |
| 735 | #[test] |
| 736 | fn content_is_drawn() { |
| 737 | let doc = crate::dsl::parse("HELLO\n").unwrap(); |
| 738 | let md = PosMetadata { page_width_mm: 80.0, ..Default::default() }; |
| 739 | let esc = EscPosEncoder::new(md.clone()).encode_document(&doc).unwrap().to_vec(); |
| 740 | let pages = render_escpos(&esc, md.printable_dots() as u32, 1.0); |
| 741 | assert_eq!(pages.len(), 1); |
| 742 | let p = &pages[0]; |
| 743 | assert_eq!(p.width(), 576); |
| 744 | let dark = p.pixels().filter(|px| px.0[0] == 0).count(); |
| 745 | assert!(dark > 100, "text must produce dots, got {dark}"); |
| 746 | // Left aligned: nothing right of the 5 chars (60 dots). |
| 747 | assert!(p.enumerate_pixels().all(|(x, _, px)| x < 64 || px.0[0] == 255)); |
| 748 | } |
| 749 | |
| 750 | #[test] |
| 751 | fn center_and_right_alignment() { |
| 752 | for (dsl, check) in [(":center:\nX\n", 1u8), (":right:\nX\n", 2u8)] { |
| 753 | let doc = crate::dsl::parse(dsl).unwrap(); |
| 754 | let md = PosMetadata { page_width_mm: 80.0, ..Default::default() }; |
| 755 | let esc = EscPosEncoder::new(md.clone()).encode_document(&doc).unwrap().to_vec(); |
| 756 | let p = &render_escpos(&esc, 576, 1.0)[0]; |
| 757 | let xs: Vec<u32> = p.enumerate_pixels().filter(|(_, _, px)| px.0[0] == 0).map(|(x, _, _)| x).collect(); |
| 758 | let min = *xs.iter().min().unwrap(); |
| 759 | if check == 1 { |
| 760 | assert!((276..300).contains(&min), "center min {min}"); |
| 761 | } else { |
| 762 | assert!(min >= 560, "right min {min}"); |
| 763 | } |
| 764 | } |
| 765 | } |
| 766 | |
| 767 | #[test] |
| 768 | fn cut_starts_new_label_and_trailing_feed_is_trimmed() { |
| 769 | let doc = crate::dsl::parse("A\n@feed 5\n@cut\nB\n@cut\n@feed 3\n@cut\n").unwrap(); |
| 770 | let md = PosMetadata { page_width_mm: 58.0, ..Default::default() }; |
| 771 | let esc = EscPosEncoder::new(md.clone()).encode_document(&doc).unwrap().to_vec(); |
| 772 | let pages = render_escpos(&esc, 384, 1.5); |
| 773 | assert_eq!(pages.len(), 2, "blank page after last cut is skipped"); |
| 774 | assert!(pages[0].height() < 40, "feed before cut trimmed: {}", pages[0].height()); |
| 775 | let job = encode_pages(&pages, &fmt(60.0, 40.0), TsplOptions::default()); |
| 776 | assert_eq!(split_cmds(&job).iter().filter(|c| *c == "PRINT 1,1").count(), 2); |
| 777 | } |
| 778 | |
| 779 | #[test] |
| 780 | fn tall_page_splits_over_labels() { |
| 781 | let img = GrayImage::from_pixel(100, 250, Luma([0])); |
| 782 | let f = LabelFormat { width_mm: 20.0, height_mm: 10.0, gap_mm: 2.0, media: MediaKind::Gap, dpi: 203, rotate_180: false }; |
| 783 | // 10 mm @ 8 dots/mm = 80 dots → 4 labels (80+80+80+10). |
| 784 | let job = encode_pages(&[img], &f, TsplOptions::default()); |
| 785 | let cmds = split_cmds(&job); |
| 786 | let bitmaps: Vec<&String> = cmds.iter().filter(|c| c.starts_with("BITMAP")).collect(); |
| 787 | assert_eq!(bitmaps.len(), 4); |
| 788 | assert_eq!(bitmaps[0].as_str(), "BITMAP 30,0,13,80,0,"); |
| 789 | assert_eq!(bitmaps[3].as_str(), "BITMAP 30,0,13,10,0,"); |
| 790 | } |
| 791 | |
| 792 | #[test] |
| 793 | fn continuous_uses_content_height() { |
| 794 | let img = GrayImage::from_pixel(80, 400, Luma([0])); |
| 795 | let f = LabelFormat { width_mm: 10.0, height_mm: 10.0, gap_mm: 0.0, media: MediaKind::Continuous, dpi: 203, rotate_180: false }; |
| 796 | let cmds = split_cmds(&encode_pages(&[img], &f, TsplOptions::default())); |
| 797 | assert_eq!(cmds[0], "SIZE 10 mm,50 mm"); |
| 798 | assert_eq!(cmds[1], "GAP 0,0"); |
| 799 | } |
| 800 | |
| 801 | #[test] |
| 802 | fn wide_doc_shrinks_to_label() { |
| 803 | let f = fmt(40.0, 30.0); |
| 804 | let s = page_scale(576, &f); |
| 805 | assert!((576.0 * s - 480.0).abs() < 0.5); |
| 806 | assert!((page_scale(384, &fmt(100.0, 50.0)) - 1.5).abs() < 1e-6); |
| 807 | } |
| 808 | |
| 809 | #[test] |
| 810 | fn barcodes_and_raster_render() { |
| 811 | let doc = crate::dsl::parse("@barcode CODE128 ABC\n@barcode RASTER CODE128 ABC\n@qr RASTER hi scale=4\n").unwrap(); |
| 812 | let md = PosMetadata { page_width_mm: 58.0, ..Default::default() }; |
| 813 | let esc = EscPosEncoder::new(md.clone()).encode_document(&doc).unwrap().to_vec(); |
| 814 | let pages = render_escpos(&esc, 384, 1.5); |
| 815 | assert_eq!(pages.len(), 1); |
| 816 | assert!(pages[0].height() > 200); |
| 817 | assert_eq!(pages[0].width(), 576); |
| 818 | } |
| 819 | |
| 820 | #[test] |
| 821 | fn parses_replies_conservatively() { |
| 822 | assert_eq!(parse_length_mm("50.00 mm", None), Some(50.0)); |
| 823 | assert_eq!(parse_length_mm("2.00 inch", None), Some(50.8)); |
| 824 | assert_eq!(parse_length_mm("600 dot", Some(12)), Some(50.0)); |
| 825 | assert_eq!(parse_length_mm("600 dot", None), None); |
| 826 | assert_eq!(parse_length_mm("600", Some(12)), None); |
| 827 | assert_eq!(parse_length_mm("", None), None); |
| 828 | assert_eq!(parse_dpi("300\r\n"), Some(300)); |
| 829 | assert_eq!(parse_dpi("203"), Some(203)); |
| 830 | assert_eq!(parse_dpi("x"), None); |
| 831 | assert_eq!(status_problem(0), None); |
| 832 | assert_eq!(status_problem(0x04), Some(StatusProblem::OutOfPaper)); |
| 833 | assert_eq!(status_problem(0x05), Some(StatusProblem::HeadOpen)); |
| 834 | } |
| 835 | } |