| 1 | use std::collections::HashMap;
|
| 2 | use std::path::Path;
|
| 3 |
|
| 4 | use crate::dsl::{parse, Document};
|
| 5 | use crate::escpos::{EscPosEncoder, EscPosError};
|
| 6 | use crate::io::{LoadError, PosFile};
|
| 7 | use crate::params::{
|
| 8 | collect_parameters, invalid_bool_parameters, substitute_document, ParamKind,
|
| 9 | };
|
| 10 | use crate::label_format::{LabelFormat, LabelFormatStore};
|
| 11 | use crate::print::{open_printer_by_name, print_bytes, PrintError, PrinterTarget};
|
| 12 | use crate::protocol::{Detection, PrinterProtocol};
|
| 13 | use crate::tspl::{self, TsplOptions};
|
| 14 |
|
| 15 | #[derive(Debug)]
|
| 16 | pub enum PipelineError {
|
| 17 | Load(LoadError),
|
| 18 | Parse(crate::dsl::ParseError),
|
| 19 | MissingParams(Vec<String>),
|
| 20 | InvalidBoolParams(Vec<String>),
|
| 21 | Encode(EscPosError),
|
| 22 | Print(PrintError),
|
| 23 | /// TSPL label printer without a saved label format (model key).
|
| 24 | LabelFormatMissing(String),
|
| 25 | }
|
| 26 |
|
| 27 | impl std::fmt::Display for PipelineError {
|
| 28 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
| 29 | match self {
|
| 30 | Self::Load(e) => write!(f, "{e:?}"),
|
| 31 | Self::Parse(e) => write!(f, "{e}"),
|
| 32 | Self::MissingParams(names) => {
|
| 33 | write!(f, "missing parameters: {}", names.join(", "))
|
| 34 | }
|
| 35 | Self::InvalidBoolParams(names) => write!(
|
| 36 | f,
|
| 37 | "invalid boolean for {}: use true/false (or 1/0, yes/no)",
|
| 38 | names.join(", ")
|
| 39 | ),
|
| 40 | Self::Encode(e) => write!(f, "{e:?}"),
|
| 41 | Self::Print(e) => write!(f, "{e:?}"),
|
| 42 | Self::LabelFormatMissing(model) => {
|
| 43 | write!(f, "{}", crate::i18n::trf("label.err.missing_cli", model))
|
| 44 | }
|
| 45 | }
|
| 46 | }
|
| 47 | }
|
| 48 |
|
| 49 | impl std::error::Error for PipelineError {}
|
| 50 |
|
| 51 | pub fn missing_parameters(document: &Document, params: &HashMap<String, String>) -> Vec<String> {
|
| 52 | collect_parameters(document)
|
| 53 | .into_iter()
|
| 54 | .filter(|p| match p.kind {
|
| 55 | ParamKind::Text => params
|
| 56 | .get(&p.name)
|
| 57 | .map(|v| v.is_empty())
|
| 58 | .unwrap_or(true),
|
| 59 | ParamKind::Bool => !params.contains_key(&p.name),
|
| 60 | })
|
| 61 | .map(|p| p.name)
|
| 62 | .collect()
|
| 63 | }
|
| 64 |
|
| 65 | pub fn encode_pos_file(
|
| 66 | file: &PosFile,
|
| 67 | base_dir: Option<&Path>,
|
| 68 | params: &HashMap<String, String>,
|
| 69 | ) -> Result<Vec<u8>, PipelineError> {
|
| 70 | let doc = parse(&file.body).map_err(PipelineError::Parse)?;
|
| 71 | let missing = missing_parameters(&doc, params);
|
| 72 | if !missing.is_empty() {
|
| 73 | return Err(PipelineError::MissingParams(missing));
|
| 74 | }
|
| 75 | let invalid_bool = invalid_bool_parameters(&doc, params);
|
| 76 | if !invalid_bool.is_empty() {
|
| 77 | return Err(PipelineError::InvalidBoolParams(invalid_bool));
|
| 78 | }
|
| 79 | let sub = substitute_document(&doc, params);
|
| 80 | let mut encoder = EscPosEncoder::new(file.metadata.clone());
|
| 81 | if let Some(dir) = base_dir {
|
| 82 | encoder = encoder.with_base_dir(dir);
|
| 83 | }
|
| 84 | let bytes = encoder
|
| 85 | .encode_document(&sub)
|
| 86 | .map_err(PipelineError::Encode)?;
|
| 87 | Ok(bytes.to_vec())
|
| 88 | }
|
| 89 |
|
| 90 | /// Encode for a TSPL label printer: the unchanged ESC/POS encoding is rendered
|
| 91 | /// to a bitmap and sent as TSPL `BITMAP` labels (see [`crate::tspl`]).
|
| 92 | pub fn encode_pos_file_tspl(
|
| 93 | file: &PosFile,
|
| 94 | base_dir: Option<&Path>,
|
| 95 | params: &HashMap<String, String>,
|
| 96 | format: &LabelFormat,
|
| 97 | opts: TsplOptions,
|
| 98 | ) -> Result<Vec<u8>, PipelineError> {
|
| 99 | let escpos = encode_pos_file(file, base_dir, params)?;
|
| 100 | Ok(tspl::escpos_to_tspl(
|
| 101 | &escpos,
|
| 102 | file.metadata.printable_dots() as u32,
|
| 103 | format,
|
| 104 | opts,
|
| 105 | ))
|
| 106 | }
|
| 107 |
|
| 108 | /// Resolve a printer name like `open_printer_by_name` does and detect its protocol.
|
| 109 | pub fn detect_by_name(name: &str) -> Option<(PrinterTarget, Detection)> {
|
| 110 | let name = name.trim();
|
| 111 | if name.is_empty() {
|
| 112 | return None;
|
| 113 | }
|
| 114 | let printers = crate::print::list_printers().ok()?;
|
| 115 | let matched = crate::print::find_matching_printer(&printers, name)?;
|
| 116 | let d = crate::print::detect_printer(&matched.target);
|
| 117 | Some((matched.target.clone(), d))
|
| 118 | }
|
| 119 |
|
| 120 | /// Suggested label format for a TSPL printer: model defaults, refined with
|
| 121 | /// values the printer reports itself (GETSETTING$, bidirectional USB only).
|
| 122 | /// Returns `(format, read_from_printer)`.
|
| 123 | pub fn suggest_label_format(target: &PrinterTarget, detection: &Detection) -> (LabelFormat, bool) {
|
| 124 | let mut f = LabelFormat::suggested_for_model(detection.model_name.as_deref());
|
| 125 | let ask = |q: &str| {
|
| 126 | crate::print::query_printer(target, q.as_bytes())
|
| 127 | .map(|r| String::from_utf8_lossy(&r).to_string())
|
| 128 | };
|
| 129 | let Some(dpi_reply) = ask(tspl::QUERY_DPI) else {
|
| 130 | return (f, false);
|
| 131 | };
|
| 132 | let mut from_printer = false;
|
| 133 | if let Some(dpi) = tspl::parse_dpi(&dpi_reply) {
|
| 134 | f.dpi = dpi;
|
| 135 | from_printer = true;
|
| 136 | }
|
| 137 | let dpmm = Some(f.dots_per_mm());
|
| 138 | if let Some(w) = ask(tspl::QUERY_PAPER_WIDTH).and_then(|r| tspl::parse_length_mm(&r, dpmm)) {
|
| 139 | f.width_mm = (w * 10.0).round() / 10.0;
|
| 140 | from_printer = true;
|
| 141 | }
|
| 142 | if let Some(h) = ask(tspl::QUERY_PAPER_SIZE).and_then(|r| tspl::parse_length_mm(&r, dpmm)) {
|
| 143 | f.height_mm = (h * 10.0).round() / 10.0;
|
| 144 | from_printer = true;
|
| 145 | }
|
| 146 | if let Some(g) = ask(tspl::QUERY_GAP_SIZE).and_then(|r| tspl::parse_length_mm(&r, dpmm)) {
|
| 147 | f.gap_mm = (g * 10.0).round() / 10.0;
|
| 148 | from_printer = true;
|
| 149 | }
|
| 150 | if f.validate().is_err() {
|
| 151 | return (LabelFormat::suggested_for_model(detection.model_name.as_deref()), false);
|
| 152 | }
|
| 153 | (f, from_printer)
|
| 154 | }
|
| 155 |
|
| 156 | /// TSPL `<ESC>!?` status (manual p.82); `None` when unknown or ready.
|
| 157 | pub fn tspl_status_problem(target: &PrinterTarget) -> Option<tspl::StatusProblem> {
|
| 158 | let reply = crate::print::query_printer(target, tspl::STATUS_QUERY)?;
|
| 159 | tspl::status_problem(*reply.first()?)
|
| 160 | }
|
| 161 |
|
| 162 | pub fn print_pos_file(
|
| 163 | path: &Path,
|
| 164 | printer_port: &str,
|
| 165 | params: &HashMap<String, String>,
|
| 166 | ) -> Result<(), PipelineError> {
|
| 167 | let file = PosFile::load_from_path(path).map_err(PipelineError::Load)?;
|
| 168 | let base_dir = path.parent();
|
| 169 | let bytes = match detect_by_name(printer_port) {
|
| 170 | Some((_, d)) if d.protocol == PrinterProtocol::Tspl => {
|
| 171 | let store = LabelFormatStore::load();
|
| 172 | let format = store
|
| 173 | .get(&d.model_key)
|
| 174 | .cloned()
|
| 175 | .ok_or_else(|| PipelineError::LabelFormatMissing(d.model_key.clone()))?;
|
| 176 | encode_pos_file_tspl(&file, base_dir, params, &format, TsplOptions::default())?
|
| 177 | }
|
| 178 | _ => encode_pos_file(&file, base_dir, params)?,
|
| 179 | };
|
| 180 | let mut transport = open_printer_by_name(printer_port).map_err(PipelineError::Print)?;
|
| 181 | print_bytes(&mut transport, &bytes).map_err(PipelineError::Print)
|
| 182 | }
|
| 183 |
|
| 184 | #[cfg(test)]
|
| 185 | mod tests {
|
| 186 | use super::*;
|
| 187 |
|
| 188 | #[test]
|
| 189 | fn detects_missing_parameters() {
|
| 190 | let file = PosFile::new("Hello ${A} ${B}");
|
| 191 | let doc = parse(&file.body).unwrap();
|
| 192 | let mut params = HashMap::new();
|
| 193 | params.insert("A".into(), "1".into());
|
| 194 | assert_eq!(missing_parameters(&doc, ¶ms), vec!["B".to_string()]);
|
| 195 | }
|
| 196 |
|
| 197 | #[test]
|
| 198 | fn encodes_raster_code128_with_substituted_data() {
|
| 199 | let file = PosFile::new("Testing\n@barcode RASTER CODE128 ${Data}\n\nLast line\n");
|
| 200 | let mut params = HashMap::new();
|
| 201 | params.insert("Data".into(), "Testcode".into());
|
| 202 | let bytes = encode_pos_file(&file, None, ¶ms).unwrap();
|
| 203 | assert!(bytes.windows(4).any(|w| w == [0x1D, b'v', 0x30, 0x00]));
|
| 204 | }
|
| 205 |
|
| 206 | #[test]
|
| 207 | fn tspl_encoding_reuses_escpos_layout() {
|
| 208 | let file = PosFile::new("Hi ${Name}\n@cut\n");
|
| 209 | let mut params = HashMap::new();
|
| 210 | params.insert("Name".into(), "Ada".into());
|
| 211 | let f = LabelFormat { dpi: 300, width_mm: 50.0, height_mm: 30.0, ..Default::default() };
|
| 212 | let job = encode_pos_file_tspl(&file, None, ¶ms, &f, TsplOptions::default()).unwrap();
|
| 213 | assert!(job.starts_with(b"SIZE 50 mm,30 mm\r\nGAP 3 mm,0 mm\r\n"));
|
| 214 | assert!(job.ends_with(b"\r\nPRINT 1,1\r\n"));
|
| 215 | // Missing params still fail like ESC/POS.
|
| 216 | let err = encode_pos_file_tspl(&file, None, &HashMap::new(), &f, TsplOptions::default());
|
| 217 | assert!(matches!(err, Err(PipelineError::MissingParams(_))));
|
| 218 | }
|
| 219 |
|
| 220 | #[test]
|
| 221 | fn encodes_when_all_params_present() {
|
| 222 | let file = PosFile::new("Hi ${Name}");
|
| 223 | let mut params = HashMap::new();
|
| 224 | params.insert("Name".into(), "Ada".into());
|
| 225 | let bytes = encode_pos_file(&file, None, ¶ms).unwrap();
|
| 226 | assert!(bytes.windows(2).any(|w| w == b"Hi"));
|
| 227 | }
|
| 228 | }
|