| 1 | //! Shared print dialog state and UI (full app and print-only launcher).
|
| 2 |
|
| 3 | use std::collections::HashMap;
|
| 4 | use std::path::PathBuf;
|
| 5 | use std::sync::mpsc::{self, Receiver, TryRecvError};
|
| 6 |
|
| 7 | use eframe::egui;
|
| 8 |
|
| 9 | use posprint::dsl::parse;
|
| 10 | use posprint::io::{PosFile, PosMetadata};
|
| 11 | use posprint::params::{collect_parameters, parse_bool_value, ParamKind, ParamSpec};
|
| 12 | use posprint::pipeline;
|
| 13 | use posprint::print::{
|
| 14 | find_preferred_printer_index, list_printers, manual_printer_preference_key, open_printer,
|
| 15 | open_printer_by_name, print_bytes, printer_preference_key, PrintError, PrinterDevice,
|
| 16 | };
|
| 17 | use posprint::config::AppConfig;
|
| 18 | use posprint::i18n::{tr, trf};
|
| 19 | use posprint::label_format::{FormatError, LabelFormat, LabelFormatStore, MediaKind};
|
| 20 | use posprint::print::{detect_printer, find_matching_printer, PrinterTarget};
|
| 21 | use posprint::protocol::{Detection, DetectionSource, PrinterProtocol};
|
| 22 | use posprint::tspl::TsplOptions;
|
| 23 |
|
| 24 | /// Label-format form for TSPL label printers (only shown for those).
|
| 25 | #[derive(Debug, Clone)]
|
| 26 | pub struct LabelForm {
|
| 27 | pub model_key: String,
|
| 28 | pub width: String,
|
| 29 | pub height: String,
|
| 30 | pub gap: String,
|
| 31 | pub media: MediaKind,
|
| 32 | pub dpi: u16,
|
| 33 | pub rotate_180: bool,
|
| 34 | pub calibrate: bool,
|
| 35 | pub from_printer: bool,
|
| 36 | pub error: Option<String>,
|
| 37 | }
|
| 38 |
|
| 39 | impl LabelForm {
|
| 40 | pub fn from_format(model_key: &str, f: &LabelFormat, calibrate: bool, from_printer: bool) -> Self {
|
| 41 | let n = |v: f32| {
|
| 42 | let s = format!("{v:.1}");
|
| 43 | s.trim_end_matches('0').trim_end_matches('.').to_string()
|
| 44 | };
|
| 45 | Self {
|
| 46 | model_key: model_key.to_string(),
|
| 47 | width: n(f.width_mm),
|
| 48 | height: n(f.height_mm),
|
| 49 | gap: n(f.gap_mm),
|
| 50 | media: f.media,
|
| 51 | dpi: f.dpi,
|
| 52 | rotate_180: f.rotate_180,
|
| 53 | calibrate,
|
| 54 | from_printer,
|
| 55 | error: None,
|
| 56 | }
|
| 57 | }
|
| 58 |
|
| 59 | /// Parse and validate; accepts `,` as decimal separator.
|
| 60 | pub fn to_format(&self) -> Result<LabelFormat, String> {
|
| 61 | let num = |s: &str, label: &str| -> Result<f32, String> {
|
| 62 | s.trim()
|
| 63 | .replace(',', ".")
|
| 64 | .parse::<f32>()
|
| 65 | .map_err(|_| trf("label.err.number", label))
|
| 66 | };
|
| 67 | let f = LabelFormat {
|
| 68 | width_mm: num(&self.width, tr("label.width"))?,
|
| 69 | height_mm: num(&self.height, tr("label.height"))?,
|
| 70 | gap_mm: if self.media == MediaKind::Continuous {
|
| 71 | num(&self.gap, tr("label.gap")).unwrap_or(0.0)
|
| 72 | } else {
|
| 73 | num(&self.gap, tr("label.gap"))?
|
| 74 | },
|
| 75 | media: self.media,
|
| 76 | dpi: self.dpi,
|
| 77 | rotate_180: self.rotate_180,
|
| 78 | };
|
| 79 | f.validate().map_err(|e| {
|
| 80 | tr(match e {
|
| 81 | FormatError::Width => "label.err.width",
|
| 82 | FormatError::Height => "label.err.height",
|
| 83 | FormatError::Gap => "label.err.gap",
|
| 84 | FormatError::Dpi => "label.err.dpi",
|
| 85 | })
|
| 86 | .to_string()
|
| 87 | })?;
|
| 88 | Ok(f)
|
| 89 | }
|
| 90 | }
|
| 91 |
|
| 92 | #[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
| 93 | pub enum PrintExecuteResult {
|
| 94 | StillOpen,
|
| 95 | Printed,
|
| 96 | }
|
| 97 |
|
| 98 | pub struct PrintDialog {
|
| 99 | pub param_inputs: HashMap<String, String>,
|
| 100 | pub param_specs: Vec<ParamSpec>,
|
| 101 | pub last_params: HashMap<String, String>,
|
| 102 | pub printers: Vec<PrinterDevice>,
|
| 103 | pub printers_loading: bool,
|
| 104 | printers_rx: Option<Receiver<Result<Vec<PrinterDevice>, PrintError>>>,
|
| 105 | pub selected_printer: Option<usize>,
|
| 106 | pub manual_port: String,
|
| 107 | pub use_manual_port: bool,
|
| 108 | pub error: Option<String>,
|
| 109 | /// Detected protocol per printer id (filled in the background).
|
| 110 | pub detections: HashMap<String, Detection>,
|
| 111 | detect_rx: Option<Receiver<HashMap<String, Detection>>>,
|
| 112 | /// Open label-format form (TSPL printers only).
|
| 113 | pub label_form: Option<LabelForm>,
|
| 114 | label_submit: bool,
|
| 115 | }
|
| 116 |
|
| 117 | impl Default for PrintDialog {
|
| 118 | fn default() -> Self {
|
| 119 | Self {
|
| 120 | param_inputs: HashMap::new(),
|
| 121 | param_specs: Vec::new(),
|
| 122 | last_params: HashMap::new(),
|
| 123 | printers: Vec::new(),
|
| 124 | printers_loading: false,
|
| 125 | printers_rx: None,
|
| 126 | selected_printer: None,
|
| 127 | manual_port: String::new(),
|
| 128 | use_manual_port: false,
|
| 129 | error: None,
|
| 130 | detections: HashMap::new(),
|
| 131 | detect_rx: None,
|
| 132 | label_form: None,
|
| 133 | label_submit: false,
|
| 134 | }
|
| 135 | }
|
| 136 | }
|
| 137 |
|
| 138 | impl PrintDialog {
|
| 139 | pub fn prepare(&mut self, body: &str) -> Result<(), String> {
|
| 140 | self.error = None;
|
| 141 | let doc = parse(body).map_err(|e| e.to_string())?;
|
| 142 | self.param_specs = collect_parameters(&doc);
|
| 143 | self.param_inputs.clear();
|
| 144 | for spec in &self.param_specs {
|
| 145 | let value = match spec.kind {
|
| 146 | ParamKind::Bool => self
|
| 147 | .last_params
|
| 148 | .get(&spec.name)
|
| 149 | .cloned()
|
| 150 | .filter(|v| parse_bool_value(v).is_some())
|
| 151 | .unwrap_or_else(|| "false".into()),
|
| 152 | ParamKind::Text => self
|
| 153 | .last_params
|
| 154 | .get(&spec.name)
|
| 155 | .cloned()
|
| 156 | .unwrap_or_default(),
|
| 157 | };
|
| 158 | self.param_inputs.insert(spec.name.clone(), value);
|
| 159 | }
|
| 160 | self.start_printer_discovery();
|
| 161 | Ok(())
|
| 162 | }
|
| 163 |
|
| 164 | pub fn start_printer_discovery(&mut self) {
|
| 165 | self.printers_loading = true;
|
| 166 | self.error = None;
|
| 167 | let (tx, rx) = mpsc::channel();
|
| 168 | self.printers_rx = Some(rx);
|
| 169 | std::thread::spawn(move || {
|
| 170 | let _ = tx.send(list_printers());
|
| 171 | });
|
| 172 | }
|
| 173 |
|
| 174 | pub fn poll_printer_discovery(&mut self, ctx: &egui::Context) {
|
| 175 | let Some(rx) = &self.printers_rx else {
|
| 176 | return;
|
| 177 | };
|
| 178 |
|
| 179 | match rx.try_recv() {
|
| 180 | Ok(result) => {
|
| 181 | self.printers_rx = None;
|
| 182 | self.printers_loading = false;
|
| 183 | match result {
|
| 184 | Ok(list) => {
|
| 185 | self.printers = list;
|
| 186 | self.start_protocol_detection();
|
| 187 | self.apply_preferred_printer(AppConfig::load().last_printer_key.as_deref());
|
| 188 | }
|
| 189 | Err(e) => self.error = Some(format!("{e:?}")),
|
| 190 | }
|
| 191 | }
|
| 192 | Err(TryRecvError::Empty) => {
|
| 193 | ctx.request_repaint();
|
| 194 | }
|
| 195 | Err(TryRecvError::Disconnected) => {
|
| 196 | self.printers_rx = None;
|
| 197 | self.printers_loading = false;
|
| 198 | }
|
| 199 | }
|
| 200 | }
|
| 201 |
|
| 202 | fn start_protocol_detection(&mut self) {
|
| 203 | let targets: Vec<(String, PrinterTarget)> = self
|
| 204 | .printers
|
| 205 | .iter()
|
| 206 | .map(|p| (p.id.clone(), p.target.clone()))
|
| 207 | .collect();
|
| 208 | let (tx, rx) = mpsc::channel();
|
| 209 | self.detect_rx = Some(rx);
|
| 210 | std::thread::spawn(move || {
|
| 211 | let map = targets
|
| 212 | .into_iter()
|
| 213 | .map(|(id, t)| (id, detect_printer(&t)))
|
| 214 | .collect();
|
| 215 | let _ = tx.send(map);
|
| 216 | });
|
| 217 | }
|
| 218 |
|
| 219 | fn poll_protocol_detection(&mut self) {
|
| 220 | if let Some(rx) = &self.detect_rx {
|
| 221 | if let Ok(map) = rx.try_recv() {
|
| 222 | self.detections = map;
|
| 223 | self.detect_rx = None;
|
| 224 | }
|
| 225 | }
|
| 226 | }
|
| 227 |
|
| 228 | /// The printer that would be used, as discovered device (manual names are
|
| 229 | /// matched against discovered printers like `open_printer_by_name`).
|
| 230 | fn effective_device(&self) -> Option<&PrinterDevice> {
|
| 231 | if self.use_manual_port {
|
| 232 | find_matching_printer(&self.printers, self.manual_port.trim())
|
| 233 | } else {
|
| 234 | self.selected_printer.and_then(|i| self.printers.get(i))
|
| 235 | }
|
| 236 | }
|
| 237 |
|
| 238 | /// Cached detection for the effective printer, if it is a TSPL printer.
|
| 239 | fn cached_tspl(&self) -> Option<&Detection> {
|
| 240 | let dev = self.effective_device()?;
|
| 241 | self.detections
|
| 242 | .get(&dev.id)
|
| 243 | .filter(|d| d.protocol == PrinterProtocol::Tspl)
|
| 244 | }
|
| 245 |
|
| 246 | /// Fresh detection at print time (does not rely on the background thread).
|
| 247 | fn tspl_for_print(&mut self) -> Option<(PrinterTarget, Detection)> {
|
| 248 | let dev = self.effective_device()?.clone();
|
| 249 | let d = match self.detections.get(&dev.id) {
|
| 250 | Some(d) => d.clone(),
|
| 251 | None => {
|
| 252 | let d = detect_printer(&dev.target);
|
| 253 | self.detections.insert(dev.id.clone(), d.clone());
|
| 254 | d
|
| 255 | }
|
| 256 | };
|
| 257 | (d.protocol == PrinterProtocol::Tspl).then_some((dev.target, d))
|
| 258 | }
|
| 259 |
|
| 260 | /// Label format to print with, or `None` when the form must be filled in first.
|
| 261 | fn resolve_label_format(
|
| 262 | &mut self,
|
| 263 | target: &PrinterTarget,
|
| 264 | d: &Detection,
|
| 265 | ) -> Option<(LabelFormat, TsplOptions)> {
|
| 266 | if let Some(form) = self.label_form.as_mut().filter(|f| f.model_key == d.model_key) {
|
| 267 | if !std::mem::take(&mut self.label_submit) {
|
| 268 | return None;
|
| 269 | }
|
| 270 | match form.to_format() {
|
| 271 | Ok(fmt) => {
|
| 272 | let mut store = LabelFormatStore::load();
|
| 273 | store.set(&d.model_key, fmt.clone());
|
| 274 | if let Err(e) = store.save() {
|
| 275 | form.error = Some(trf("label.err.save", &e));
|
| 276 | return None;
|
| 277 | }
|
| 278 | let opts = TsplOptions { calibrate: form.calibrate };
|
| 279 | self.label_form = None;
|
| 280 | return Some((fmt, opts));
|
| 281 | }
|
| 282 | Err(e) => {
|
| 283 | form.error = Some(e);
|
| 284 | return None;
|
| 285 | }
|
| 286 | }
|
| 287 | }
|
| 288 | self.label_submit = false;
|
| 289 | if let Some(fmt) = LabelFormatStore::load().get(&d.model_key) {
|
| 290 | return Some((fmt.clone(), TsplOptions::default()));
|
| 291 | }
|
| 292 | let (fmt, from_printer) = pipeline::suggest_label_format(target, d);
|
| 293 | self.label_form = Some(LabelForm::from_format(&d.model_key, &fmt, true, from_printer));
|
| 294 | None
|
| 295 | }
|
| 296 |
|
| 297 | pub fn refresh_printers(&mut self) {
|
| 298 | self.start_printer_discovery();
|
| 299 | }
|
| 300 |
|
| 301 | /// Prefer the last successful printer when still connected; otherwise keep/default selection.
|
| 302 | pub fn apply_preferred_printer(&mut self, preferred_key: Option<&str>) {
|
| 303 | if let Some(key) = preferred_key.map(str::trim).filter(|k| !k.is_empty()) {
|
| 304 | if let Some(name) = key.strip_prefix("manual:") {
|
| 305 | let name = name.trim();
|
| 306 | if !name.is_empty() {
|
| 307 | self.use_manual_port = true;
|
| 308 | self.manual_port = name.to_string();
|
| 309 | return;
|
| 310 | }
|
| 311 | } else if let Some(i) = find_preferred_printer_index(&self.printers, key) {
|
| 312 | self.use_manual_port = false;
|
| 313 | self.selected_printer = Some(i);
|
| 314 | return;
|
| 315 | }
|
| 316 | }
|
| 317 | if self.selected_printer.is_none() && !self.printers.is_empty() {
|
| 318 | self.selected_printer = Some(0);
|
| 319 | }
|
| 320 | }
|
| 321 |
|
| 322 | fn remember_successful_printer(&self) {
|
| 323 | let key = if self.use_manual_port {
|
| 324 | let name = self.manual_port.trim();
|
| 325 | if name.is_empty() {
|
| 326 | None
|
| 327 | } else {
|
| 328 | Some(manual_printer_preference_key(name))
|
| 329 | }
|
| 330 | } else {
|
| 331 | self.selected_printer
|
| 332 | .and_then(|i| self.printers.get(i))
|
| 333 | .map(|p| printer_preference_key(&p.target))
|
| 334 | };
|
| 335 | let Some(key) = key else {
|
| 336 | return;
|
| 337 | };
|
| 338 | let mut cfg = AppConfig::load();
|
| 339 | if cfg.last_printer_key.as_deref() == Some(key.as_str()) {
|
| 340 | return;
|
| 341 | }
|
| 342 | cfg.remember_printer(key);
|
| 343 | let _ = cfg.save();
|
| 344 | }
|
| 345 |
|
| 346 | pub fn apply_inputs_to_last_params(&mut self) {
|
| 347 | self.last_params = self.param_inputs.clone();
|
| 348 | }
|
| 349 |
|
| 350 | pub fn execute_print(
|
| 351 | &mut self,
|
| 352 | body: &str,
|
| 353 | metadata: &PosMetadata,
|
| 354 | file_path: Option<&PathBuf>,
|
| 355 | ) -> PrintExecuteResult {
|
| 356 | self.error = None;
|
| 357 | if parse(body).is_err() {
|
| 358 | self.error = Some("Template has parse errors".into());
|
| 359 | return PrintExecuteResult::StillOpen;
|
| 360 | }
|
| 361 |
|
| 362 | for spec in &self.param_specs {
|
| 363 | if !self.param_inputs.contains_key(&spec.name) {
|
| 364 | self.error = Some(format!("Missing value for parameter {}", spec.name));
|
| 365 | return PrintExecuteResult::StillOpen;
|
| 366 | }
|
| 367 | if spec.kind == ParamKind::Bool {
|
| 368 | let raw = self.param_inputs.get(&spec.name).map(String::as_str).unwrap_or("");
|
| 369 | if parse_bool_value(raw).is_none() {
|
| 370 | self.error = Some(format!(
|
| 371 | "Invalid boolean for {}: use true/false",
|
| 372 | spec.name
|
| 373 | ));
|
| 374 | return PrintExecuteResult::StillOpen;
|
| 375 | }
|
| 376 | }
|
| 377 | }
|
| 378 |
|
| 379 | self.last_params = self.param_inputs.clone();
|
| 380 |
|
| 381 | let base_dir = file_path.and_then(|p| p.parent());
|
| 382 | let file = PosFile {
|
| 383 | version: 1,
|
| 384 | metadata: metadata.clone(),
|
| 385 | body: body.to_string(),
|
| 386 | };
|
| 387 | let bytes = match pipeline::encode_pos_file(&file, base_dir, &self.last_params) {
|
| 388 | Ok(b) => b,
|
| 389 | Err(e) => {
|
| 390 | self.error = Some(e.to_string());
|
| 391 | return PrintExecuteResult::StillOpen;
|
| 392 | }
|
| 393 | };
|
| 394 |
|
| 395 | // Label printers (TSPL): same document, sent as TSPL bitmap labels.
|
| 396 | // ESC/POS printers keep the bytes above unchanged.
|
| 397 | let bytes = match self.tspl_for_print() {
|
| 398 | Some((target, d)) => match self.resolve_label_format(&target, &d) {
|
| 399 | Some((fmt, opts)) => {
|
| 400 | match pipeline::encode_pos_file_tspl(&file, base_dir, &self.last_params, &fmt, opts) {
|
| 401 | Ok(b) => b,
|
| 402 | Err(e) => {
|
| 403 | self.error = Some(e.to_string());
|
| 404 | return PrintExecuteResult::StillOpen;
|
| 405 | }
|
| 406 | }
|
| 407 | }
|
| 408 | None => return PrintExecuteResult::StillOpen,
|
| 409 | },
|
| 410 | None => bytes,
|
| 411 | };
|
| 412 |
|
| 413 | let transport_result = if self.use_manual_port {
|
| 414 | let name = self.manual_port.trim();
|
| 415 | if name.is_empty() {
|
| 416 | self.error = Some("Select a printer or enter a port/queue name".into());
|
| 417 | return PrintExecuteResult::StillOpen;
|
| 418 | }
|
| 419 | open_printer_by_name(name)
|
| 420 | } else if let Some(target) = self.selected_printer_target() {
|
| 421 | open_printer(target)
|
| 422 | } else {
|
| 423 | self.error = Some("Select a printer".into());
|
| 424 | return PrintExecuteResult::StillOpen;
|
| 425 | };
|
| 426 |
|
| 427 | match transport_result {
|
| 428 | Ok(mut transport) => match print_bytes(transport.as_mut(), &bytes) {
|
| 429 | Ok(()) => {
|
| 430 | self.remember_successful_printer();
|
| 431 | PrintExecuteResult::Printed
|
| 432 | }
|
| 433 | Err(e) => {
|
| 434 | self.error = Some(format!("{e:?}"));
|
| 435 | PrintExecuteResult::StillOpen
|
| 436 | }
|
| 437 | },
|
| 438 | Err(e) => {
|
| 439 | self.error = Some(format!("{e:?}"));
|
| 440 | PrintExecuteResult::StillOpen
|
| 441 | }
|
| 442 | }
|
| 443 | }
|
| 444 |
|
| 445 | fn selected_printer_target(&self) -> Option<&posprint::print::PrinterTarget> {
|
| 446 | if self.use_manual_port {
|
| 447 | return None;
|
| 448 | }
|
| 449 | self.selected_printer
|
| 450 | .and_then(|i| self.printers.get(i))
|
| 451 | .map(|p| &p.target)
|
| 452 | }
|
| 453 |
|
| 454 | pub fn show_ui(&mut self, ui: &mut egui::Ui) -> PrintDialogAction {
|
| 455 | let mut action = PrintDialogAction::None;
|
| 456 |
|
| 457 | ui.heading("Parameters");
|
| 458 | if self.param_specs.is_empty() {
|
| 459 | ui.label("No parameters in this template.");
|
| 460 | } else {
|
| 461 | egui::ScrollArea::vertical()
|
| 462 | .id_salt("print_dialog_params")
|
| 463 | .max_height(140.0)
|
| 464 | .auto_shrink([false, true])
|
| 465 | .show(ui, |ui| {
|
| 466 | for spec in self.param_specs.clone() {
|
| 467 | ui.horizontal(|ui| {
|
| 468 | match spec.kind {
|
| 469 | ParamKind::Text => {
|
| 470 | ui.label(format!("{}:", spec.name));
|
| 471 | let entry = self
|
| 472 | .param_inputs
|
| 473 | .entry(spec.name.clone())
|
| 474 | .or_insert_with(String::new);
|
| 475 | ui.text_edit_singleline(entry);
|
| 476 | }
|
| 477 | ParamKind::Bool => {
|
| 478 | let mut checked = self
|
| 479 | .param_inputs
|
| 480 | .get(&spec.name)
|
| 481 | .and_then(|v| parse_bool_value(v))
|
| 482 | .unwrap_or(false);
|
| 483 | if ui.checkbox(&mut checked, &spec.name).changed() {
|
| 484 | self.param_inputs.insert(
|
| 485 | spec.name.clone(),
|
| 486 | if checked { "true" } else { "false" }.into(),
|
| 487 | );
|
| 488 | }
|
| 489 | }
|
| 490 | }
|
| 491 | });
|
| 492 | }
|
| 493 | });
|
| 494 | }
|
| 495 |
|
| 496 | ui.separator();
|
| 497 | ui.heading("Printer");
|
| 498 | ui.horizontal(|ui| {
|
| 499 | if ui
|
| 500 | .add_enabled(!self.printers_loading, egui::Button::new("Refresh"))
|
| 501 | .clicked()
|
| 502 | {
|
| 503 | self.refresh_printers();
|
| 504 | }
|
| 505 | if ui.button("Print").clicked() {
|
| 506 | action = PrintDialogAction::Print;
|
| 507 | }
|
| 508 | if self.printers_loading {
|
| 509 | ui.spinner();
|
| 510 | ui.label("Discovering printers…");
|
| 511 | }
|
| 512 | });
|
| 513 |
|
| 514 | ui.checkbox(&mut self.use_manual_port, "Enter port or queue manually");
|
| 515 | if self.use_manual_port {
|
| 516 | ui.horizontal(|ui| {
|
| 517 | ui.label("Port / queue:");
|
| 518 | ui.text_edit_singleline(&mut self.manual_port);
|
| 519 | });
|
| 520 | ui.label(
|
| 521 | "Examples: COM3, Bluetooth COM after pairing, printer queue (Windows), /dev/ttyUSB0 or /dev/rfcomm0 (Linux)",
|
| 522 | );
|
| 523 | } else if self.printers_loading && self.printers.is_empty() {
|
| 524 | ui.label("Searching for USB, spooler, serial, and paired Bluetooth printers…");
|
| 525 | } else if self.printers.is_empty() {
|
| 526 | ui.label(
|
| 527 | "No printers found. Connect a USB POS printer, pair a Classic Bluetooth SPP printer in the OS, refresh, or enter a port/queue manually.",
|
| 528 | );
|
| 529 | } else {
|
| 530 | // Fixed height so wheel scrolling works; avoid nesting inside another ScrollArea.
|
| 531 | const PRINTER_LIST_HEIGHT: f32 = 220.0;
|
| 532 | egui::ScrollArea::vertical()
|
| 533 | .id_salt("print_dialog_printer_list")
|
| 534 | .max_height(PRINTER_LIST_HEIGHT)
|
| 535 | .min_scrolled_height(PRINTER_LIST_HEIGHT)
|
| 536 | .auto_shrink([false, false])
|
| 537 | .show(ui, |ui| {
|
| 538 | ui.set_min_width(ui.available_width());
|
| 539 | for (i, printer) in self.printers.iter().enumerate() {
|
| 540 | ui.selectable_value(
|
| 541 | &mut self.selected_printer,
|
| 542 | Some(i),
|
| 543 | &printer.display_name,
|
| 544 | );
|
| 545 | }
|
| 546 | });
|
| 547 | }
|
| 548 |
|
| 549 | self.poll_protocol_detection();
|
| 550 | if self.show_label_ui(ui) {
|
| 551 | action = PrintDialogAction::Print;
|
| 552 | }
|
| 553 |
|
| 554 | if let Some(err) = &self.error {
|
| 555 | ui.colored_label(egui::Color32::RED, err);
|
| 556 | }
|
| 557 |
|
| 558 | action
|
| 559 | }
|
| 560 | }
|
| 561 |
|
| 562 | impl PrintDialog {
|
| 563 | /// Label-printer section; only drawn for TSPL printers. Returns true when
|
| 564 | /// "Save and print" was clicked.
|
| 565 | fn show_label_ui(&mut self, ui: &mut egui::Ui) -> bool {
|
| 566 | let Some(d) = self.cached_tspl().cloned().or_else(|| {
|
| 567 | self.label_form.as_ref()?;
|
| 568 | let dev = self.effective_device()?;
|
| 569 | self.detections.get(&dev.id).cloned()
|
| 570 | }) else {
|
| 571 | return false;
|
| 572 | };
|
| 573 | if d.protocol != PrinterProtocol::Tspl {
|
| 574 | return false;
|
| 575 | }
|
| 576 | let mut submit = false;
|
| 577 | ui.separator();
|
| 578 | ui.heading(tr("label.title"));
|
| 579 | let source_tip = match d.source {
|
| 580 | DetectionSource::DeviceId => tr("label.source.device_id"),
|
| 581 | DetectionSource::UsbVendor => tr("label.source.usb_vendor"),
|
| 582 | DetectionSource::QueueName => tr("label.source.queue_name"),
|
| 583 | DetectionSource::Default => "",
|
| 584 | };
|
| 585 | let detected = trf("label.detected", d.protocol.label());
|
| 586 | let text = match &d.model_name {
|
| 587 | Some(m) => format!("{detected} — {m}"),
|
| 588 | None => detected,
|
| 589 | };
|
| 590 | ui.label(text).on_hover_text(source_tip);
|
| 591 |
|
| 592 | let stored = LabelFormatStore::load().get(&d.model_key).cloned();
|
| 593 | let mut close_form = false;
|
| 594 | if let Some(form) = self.label_form.as_mut().filter(|f| f.model_key == d.model_key) {
|
| 595 | ui.label(tr("label.format_missing"));
|
| 596 | if form.from_printer {
|
| 597 | ui.label(tr("label.from_printer"));
|
| 598 | }
|
| 599 | egui::Grid::new("label_format_grid").num_columns(2).show(ui, |ui| {
|
| 600 | ui.label(tr("label.width")).on_hover_text(tr("label.width.tip"));
|
| 601 | ui.text_edit_singleline(&mut form.width).on_hover_text(tr("label.width.tip"));
|
| 602 | ui.end_row();
|
| 603 | ui.label(tr("label.height")).on_hover_text(tr("label.height.tip"));
|
| 604 | ui.text_edit_singleline(&mut form.height).on_hover_text(tr("label.height.tip"));
|
| 605 | ui.end_row();
|
| 606 | ui.label(tr("label.media")).on_hover_text(tr("label.media.tip"));
|
| 607 | ui.horizontal(|ui| {
|
| 608 | ui.radio_value(&mut form.media, MediaKind::Gap, tr("label.media.gap"))
|
| 609 | .on_hover_text(tr("label.media.tip"));
|
| 610 | ui.radio_value(&mut form.media, MediaKind::BlackMark, tr("label.media.black_mark"))
|
| 611 | .on_hover_text(tr("label.media.tip"));
|
| 612 | ui.radio_value(&mut form.media, MediaKind::Continuous, tr("label.media.continuous"))
|
| 613 | .on_hover_text(tr("label.media.tip"));
|
| 614 | });
|
| 615 | ui.end_row();
|
| 616 | if form.media != MediaKind::Continuous {
|
| 617 | ui.label(tr("label.gap")).on_hover_text(tr("label.gap.tip"));
|
| 618 | ui.text_edit_singleline(&mut form.gap).on_hover_text(tr("label.gap.tip"));
|
| 619 | ui.end_row();
|
| 620 | }
|
| 621 | ui.label(tr("label.dpi")).on_hover_text(tr("label.dpi.tip"));
|
| 622 | ui.horizontal(|ui| {
|
| 623 | for dpi in [203u16, 300, 600] {
|
| 624 | ui.radio_value(&mut form.dpi, dpi, dpi.to_string())
|
| 625 | .on_hover_text(tr("label.dpi.tip"));
|
| 626 | }
|
| 627 | });
|
| 628 | ui.end_row();
|
| 629 | });
|
| 630 | ui.checkbox(&mut form.rotate_180, tr("label.rotate"))
|
| 631 | .on_hover_text(tr("label.rotate.tip"));
|
| 632 | if form.media != MediaKind::Continuous {
|
| 633 | ui.checkbox(&mut form.calibrate, tr("label.calibrate"))
|
| 634 | .on_hover_text(tr("label.calibrate.tip"));
|
| 635 | }
|
| 636 | ui.horizontal(|ui| {
|
| 637 | if ui
|
| 638 | .button(tr("label.save_print"))
|
| 639 | .on_hover_text(tr("label.save_print.tip"))
|
| 640 | .clicked()
|
| 641 | {
|
| 642 | submit = true;
|
| 643 | }
|
| 644 | if ui
|
| 645 | .button(tr("label.cancel"))
|
| 646 | .on_hover_text(tr("label.cancel.tip"))
|
| 647 | .clicked()
|
| 648 | {
|
| 649 | close_form = true;
|
| 650 | }
|
| 651 | });
|
| 652 | if let Some(err) = &form.error {
|
| 653 | ui.colored_label(egui::Color32::RED, err);
|
| 654 | }
|
| 655 | } else if let Some(f) = stored {
|
| 656 | ui.horizontal(|ui| {
|
| 657 | ui.label(format!(
|
| 658 | "{}: {} × {} mm, {} dpi",
|
| 659 | tr("label.format"),
|
| 660 | f.width_mm,
|
| 661 | f.height_mm,
|
| 662 | f.dpi
|
| 663 | ));
|
| 664 | if ui
|
| 665 | .button(tr("label.change"))
|
| 666 | .on_hover_text(tr("label.change.tip"))
|
| 667 | .clicked()
|
| 668 | {
|
| 669 | self.label_form = Some(LabelForm::from_format(&d.model_key, &f, false, false));
|
| 670 | }
|
| 671 | });
|
| 672 | } else {
|
| 673 | ui.label(tr("label.format_missing"));
|
| 674 | }
|
| 675 | if close_form {
|
| 676 | self.label_form = None;
|
| 677 | }
|
| 678 | if submit {
|
| 679 | self.label_submit = true;
|
| 680 | }
|
| 681 | submit
|
| 682 | }
|
| 683 | }
|
| 684 |
|
| 685 | #[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
| 686 | pub enum PrintDialogAction {
|
| 687 | None,
|
| 688 | Print,
|
| 689 | }
|
| 690 |
|
| 691 | #[cfg(test)]
|
| 692 | mod tests {
|
| 693 | use super::*;
|
| 694 | use posprint::print::PrinterTarget;
|
| 695 |
|
| 696 | #[test]
|
| 697 | fn prefers_last_connected_printer_over_first() {
|
| 698 | let mut dialog = PrintDialog::default();
|
| 699 | dialog.printers = vec![
|
| 700 | PrinterDevice {
|
| 701 | id: "a".into(),
|
| 702 | display_name: "First".into(),
|
| 703 | target: PrinterTarget::Serial("COM1".into()),
|
| 704 | },
|
| 705 | PrinterDevice {
|
| 706 | id: "b".into(),
|
| 707 | display_name: "Last".into(),
|
| 708 | target: PrinterTarget::WinSpooler("POS".into()),
|
| 709 | },
|
| 710 | ];
|
| 711 | dialog.apply_preferred_printer(Some("winspool:POS"));
|
| 712 | assert_eq!(dialog.selected_printer, Some(1));
|
| 713 | assert!(!dialog.use_manual_port);
|
| 714 | }
|
| 715 |
|
| 716 | #[test]
|
| 717 | fn falls_back_to_first_when_preferred_missing() {
|
| 718 | let mut dialog = PrintDialog::default();
|
| 719 | dialog.printers = vec![PrinterDevice {
|
| 720 | id: "a".into(),
|
| 721 | display_name: "Only".into(),
|
| 722 | target: PrinterTarget::Serial("COM1".into()),
|
| 723 | }];
|
| 724 | dialog.apply_preferred_printer(Some("winspool:Gone"));
|
| 725 | assert_eq!(dialog.selected_printer, Some(0));
|
| 726 | }
|
| 727 |
|
| 728 | #[test]
|
| 729 | fn label_form_parses_and_validates() {
|
| 730 | let f = LabelFormat { width_mm: 50.0, height_mm: 30.0, dpi: 300, ..Default::default() };
|
| 731 | let mut form = LabelForm::from_format("Altec ATP-300 Pro", &f, true, false);
|
| 732 | assert_eq!(form.width, "50");
|
| 733 | assert_eq!(form.to_format().unwrap(), f);
|
| 734 | form.width = "50,5".into();
|
| 735 | assert_eq!(form.to_format().unwrap().width_mm, 50.5);
|
| 736 | form.width = "abc".into();
|
| 737 | assert!(form.to_format().is_err());
|
| 738 | form.width = "500".into();
|
| 739 | assert!(form.to_format().is_err());
|
| 740 | form.width = "50".into();
|
| 741 | form.media = MediaKind::Continuous;
|
| 742 | form.gap = String::new();
|
| 743 | assert_eq!(form.to_format().unwrap().gap_mm, 0.0);
|
| 744 | }
|
| 745 |
|
| 746 | #[test]
|
| 747 | fn escpos_printers_show_no_label_section() {
|
| 748 | let mut dialog = PrintDialog::default();
|
| 749 | dialog.printers = vec![PrinterDevice {
|
| 750 | id: "a".into(),
|
| 751 | display_name: "POS".into(),
|
| 752 | target: PrinterTarget::Serial("COM1".into()),
|
| 753 | }];
|
| 754 | dialog.selected_printer = Some(0);
|
| 755 | assert!(dialog.cached_tspl().is_none());
|
| 756 | assert!(dialog.tspl_for_print().is_none(), "serial printers stay ESC/POS");
|
| 757 | let tspl_target = PrinterTarget::UsbDirect { vid: 0x1203, pid: 0x0231, bus: 250, address: 250 };
|
| 758 | dialog.printers.push(PrinterDevice {
|
| 759 | id: "usb:250:250:1203:0231".into(),
|
| 760 | display_name: "ATP".into(),
|
| 761 | target: tspl_target.clone(),
|
| 762 | });
|
| 763 | dialog.detections.insert(
|
| 764 | "usb:250:250:1203:0231".into(),
|
| 765 | posprint::protocol::detect(&tspl_target, Some("MFG:Altec;CMD:TSPL2;MDL:ATP-300 Pro;")),
|
| 766 | );
|
| 767 | dialog.selected_printer = Some(1);
|
| 768 | assert_eq!(dialog.cached_tspl().unwrap().model_key, "Altec ATP-300 Pro");
|
| 769 | }
|
| 770 |
|
| 771 | #[test]
|
| 772 | fn restores_manual_preference() {
|
| 773 | let mut dialog = PrintDialog::default();
|
| 774 | dialog.apply_preferred_printer(Some("manual:COM9"));
|
| 775 | assert!(dialog.use_manual_port);
|
| 776 | assert_eq!(dialog.manual_port, "COM9");
|
| 777 | }
|
| 778 | }
|