| 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 |
|
| 19 | #[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
| 20 | pub enum PrintExecuteResult {
|
| 21 | StillOpen,
|
| 22 | Printed,
|
| 23 | }
|
| 24 |
|
| 25 | pub struct PrintDialog {
|
| 26 | pub param_inputs: HashMap<String, String>,
|
| 27 | pub param_specs: Vec<ParamSpec>,
|
| 28 | pub last_params: HashMap<String, String>,
|
| 29 | pub printers: Vec<PrinterDevice>,
|
| 30 | pub printers_loading: bool,
|
| 31 | printers_rx: Option<Receiver<Result<Vec<PrinterDevice>, PrintError>>>,
|
| 32 | pub selected_printer: Option<usize>,
|
| 33 | pub manual_port: String,
|
| 34 | pub use_manual_port: bool,
|
| 35 | pub error: Option<String>,
|
| 36 | }
|
| 37 |
|
| 38 | impl Default for PrintDialog {
|
| 39 | fn default() -> Self {
|
| 40 | Self {
|
| 41 | param_inputs: HashMap::new(),
|
| 42 | param_specs: Vec::new(),
|
| 43 | last_params: HashMap::new(),
|
| 44 | printers: Vec::new(),
|
| 45 | printers_loading: false,
|
| 46 | printers_rx: None,
|
| 47 | selected_printer: None,
|
| 48 | manual_port: String::new(),
|
| 49 | use_manual_port: false,
|
| 50 | error: None,
|
| 51 | }
|
| 52 | }
|
| 53 | }
|
| 54 |
|
| 55 | impl PrintDialog {
|
| 56 | pub fn prepare(&mut self, body: &str) -> Result<(), String> {
|
| 57 | self.error = None;
|
| 58 | let doc = parse(body).map_err(|e| e.to_string())?;
|
| 59 | self.param_specs = collect_parameters(&doc);
|
| 60 | self.param_inputs.clear();
|
| 61 | for spec in &self.param_specs {
|
| 62 | let value = match spec.kind {
|
| 63 | ParamKind::Bool => self
|
| 64 | .last_params
|
| 65 | .get(&spec.name)
|
| 66 | .cloned()
|
| 67 | .filter(|v| parse_bool_value(v).is_some())
|
| 68 | .unwrap_or_else(|| "false".into()),
|
| 69 | ParamKind::Text => self
|
| 70 | .last_params
|
| 71 | .get(&spec.name)
|
| 72 | .cloned()
|
| 73 | .unwrap_or_default(),
|
| 74 | };
|
| 75 | self.param_inputs.insert(spec.name.clone(), value);
|
| 76 | }
|
| 77 | self.start_printer_discovery();
|
| 78 | Ok(())
|
| 79 | }
|
| 80 |
|
| 81 | pub fn start_printer_discovery(&mut self) {
|
| 82 | self.printers_loading = true;
|
| 83 | self.error = None;
|
| 84 | let (tx, rx) = mpsc::channel();
|
| 85 | self.printers_rx = Some(rx);
|
| 86 | std::thread::spawn(move || {
|
| 87 | let _ = tx.send(list_printers());
|
| 88 | });
|
| 89 | }
|
| 90 |
|
| 91 | pub fn poll_printer_discovery(&mut self, ctx: &egui::Context) {
|
| 92 | let Some(rx) = &self.printers_rx else {
|
| 93 | return;
|
| 94 | };
|
| 95 |
|
| 96 | match rx.try_recv() {
|
| 97 | Ok(result) => {
|
| 98 | self.printers_rx = None;
|
| 99 | self.printers_loading = false;
|
| 100 | match result {
|
| 101 | Ok(list) => {
|
| 102 | self.printers = list;
|
| 103 | self.apply_preferred_printer(AppConfig::load().last_printer_key.as_deref());
|
| 104 | }
|
| 105 | Err(e) => self.error = Some(format!("{e:?}")),
|
| 106 | }
|
| 107 | }
|
| 108 | Err(TryRecvError::Empty) => {
|
| 109 | ctx.request_repaint();
|
| 110 | }
|
| 111 | Err(TryRecvError::Disconnected) => {
|
| 112 | self.printers_rx = None;
|
| 113 | self.printers_loading = false;
|
| 114 | }
|
| 115 | }
|
| 116 | }
|
| 117 |
|
| 118 | pub fn refresh_printers(&mut self) {
|
| 119 | self.start_printer_discovery();
|
| 120 | }
|
| 121 |
|
| 122 | /// Prefer the last successful printer when still connected; otherwise keep/default selection.
|
| 123 | pub fn apply_preferred_printer(&mut self, preferred_key: Option<&str>) {
|
| 124 | if let Some(key) = preferred_key.map(str::trim).filter(|k| !k.is_empty()) {
|
| 125 | if let Some(name) = key.strip_prefix("manual:") {
|
| 126 | let name = name.trim();
|
| 127 | if !name.is_empty() {
|
| 128 | self.use_manual_port = true;
|
| 129 | self.manual_port = name.to_string();
|
| 130 | return;
|
| 131 | }
|
| 132 | } else if let Some(i) = find_preferred_printer_index(&self.printers, key) {
|
| 133 | self.use_manual_port = false;
|
| 134 | self.selected_printer = Some(i);
|
| 135 | return;
|
| 136 | }
|
| 137 | }
|
| 138 | if self.selected_printer.is_none() && !self.printers.is_empty() {
|
| 139 | self.selected_printer = Some(0);
|
| 140 | }
|
| 141 | }
|
| 142 |
|
| 143 | fn remember_successful_printer(&self) {
|
| 144 | let key = if self.use_manual_port {
|
| 145 | let name = self.manual_port.trim();
|
| 146 | if name.is_empty() {
|
| 147 | None
|
| 148 | } else {
|
| 149 | Some(manual_printer_preference_key(name))
|
| 150 | }
|
| 151 | } else {
|
| 152 | self.selected_printer
|
| 153 | .and_then(|i| self.printers.get(i))
|
| 154 | .map(|p| printer_preference_key(&p.target))
|
| 155 | };
|
| 156 | let Some(key) = key else {
|
| 157 | return;
|
| 158 | };
|
| 159 | let mut cfg = AppConfig::load();
|
| 160 | if cfg.last_printer_key.as_deref() == Some(key.as_str()) {
|
| 161 | return;
|
| 162 | }
|
| 163 | cfg.remember_printer(key);
|
| 164 | let _ = cfg.save();
|
| 165 | }
|
| 166 |
|
| 167 | pub fn apply_inputs_to_last_params(&mut self) {
|
| 168 | self.last_params = self.param_inputs.clone();
|
| 169 | }
|
| 170 |
|
| 171 | pub fn execute_print(
|
| 172 | &mut self,
|
| 173 | body: &str,
|
| 174 | metadata: &PosMetadata,
|
| 175 | file_path: Option<&PathBuf>,
|
| 176 | ) -> PrintExecuteResult {
|
| 177 | self.error = None;
|
| 178 | if parse(body).is_err() {
|
| 179 | self.error = Some("Template has parse errors".into());
|
| 180 | return PrintExecuteResult::StillOpen;
|
| 181 | }
|
| 182 |
|
| 183 | for spec in &self.param_specs {
|
| 184 | if !self.param_inputs.contains_key(&spec.name) {
|
| 185 | self.error = Some(format!("Missing value for parameter {}", spec.name));
|
| 186 | return PrintExecuteResult::StillOpen;
|
| 187 | }
|
| 188 | if spec.kind == ParamKind::Bool {
|
| 189 | let raw = self.param_inputs.get(&spec.name).map(String::as_str).unwrap_or("");
|
| 190 | if parse_bool_value(raw).is_none() {
|
| 191 | self.error = Some(format!(
|
| 192 | "Invalid boolean for {}: use true/false",
|
| 193 | spec.name
|
| 194 | ));
|
| 195 | return PrintExecuteResult::StillOpen;
|
| 196 | }
|
| 197 | }
|
| 198 | }
|
| 199 |
|
| 200 | self.last_params = self.param_inputs.clone();
|
| 201 |
|
| 202 | let base_dir = file_path.and_then(|p| p.parent());
|
| 203 | let file = PosFile {
|
| 204 | version: 1,
|
| 205 | metadata: metadata.clone(),
|
| 206 | body: body.to_string(),
|
| 207 | };
|
| 208 | let bytes = match pipeline::encode_pos_file(&file, base_dir, &self.last_params) {
|
| 209 | Ok(b) => b,
|
| 210 | Err(e) => {
|
| 211 | self.error = Some(e.to_string());
|
| 212 | return PrintExecuteResult::StillOpen;
|
| 213 | }
|
| 214 | };
|
| 215 |
|
| 216 | let transport_result = if self.use_manual_port {
|
| 217 | let name = self.manual_port.trim();
|
| 218 | if name.is_empty() {
|
| 219 | self.error = Some("Select a printer or enter a port/queue name".into());
|
| 220 | return PrintExecuteResult::StillOpen;
|
| 221 | }
|
| 222 | open_printer_by_name(name)
|
| 223 | } else if let Some(target) = self.selected_printer_target() {
|
| 224 | open_printer(target)
|
| 225 | } else {
|
| 226 | self.error = Some("Select a printer".into());
|
| 227 | return PrintExecuteResult::StillOpen;
|
| 228 | };
|
| 229 |
|
| 230 | match transport_result {
|
| 231 | Ok(mut transport) => match print_bytes(transport.as_mut(), &bytes) {
|
| 232 | Ok(()) => {
|
| 233 | self.remember_successful_printer();
|
| 234 | PrintExecuteResult::Printed
|
| 235 | }
|
| 236 | Err(e) => {
|
| 237 | self.error = Some(format!("{e:?}"));
|
| 238 | PrintExecuteResult::StillOpen
|
| 239 | }
|
| 240 | },
|
| 241 | Err(e) => {
|
| 242 | self.error = Some(format!("{e:?}"));
|
| 243 | PrintExecuteResult::StillOpen
|
| 244 | }
|
| 245 | }
|
| 246 | }
|
| 247 |
|
| 248 | fn selected_printer_target(&self) -> Option<&posprint::print::PrinterTarget> {
|
| 249 | if self.use_manual_port {
|
| 250 | return None;
|
| 251 | }
|
| 252 | self.selected_printer
|
| 253 | .and_then(|i| self.printers.get(i))
|
| 254 | .map(|p| &p.target)
|
| 255 | }
|
| 256 |
|
| 257 | pub fn show_ui(&mut self, ui: &mut egui::Ui) -> PrintDialogAction {
|
| 258 | let mut action = PrintDialogAction::None;
|
| 259 |
|
| 260 | ui.heading("Parameters");
|
| 261 | if self.param_specs.is_empty() {
|
| 262 | ui.label("No parameters in this template.");
|
| 263 | } else {
|
| 264 | egui::ScrollArea::vertical()
|
| 265 | .id_salt("print_dialog_params")
|
| 266 | .max_height(140.0)
|
| 267 | .auto_shrink([false, true])
|
| 268 | .show(ui, |ui| {
|
| 269 | for spec in self.param_specs.clone() {
|
| 270 | ui.horizontal(|ui| {
|
| 271 | match spec.kind {
|
| 272 | ParamKind::Text => {
|
| 273 | ui.label(format!("{}:", spec.name));
|
| 274 | let entry = self
|
| 275 | .param_inputs
|
| 276 | .entry(spec.name.clone())
|
| 277 | .or_insert_with(String::new);
|
| 278 | ui.text_edit_singleline(entry);
|
| 279 | }
|
| 280 | ParamKind::Bool => {
|
| 281 | let mut checked = self
|
| 282 | .param_inputs
|
| 283 | .get(&spec.name)
|
| 284 | .and_then(|v| parse_bool_value(v))
|
| 285 | .unwrap_or(false);
|
| 286 | if ui.checkbox(&mut checked, &spec.name).changed() {
|
| 287 | self.param_inputs.insert(
|
| 288 | spec.name.clone(),
|
| 289 | if checked { "true" } else { "false" }.into(),
|
| 290 | );
|
| 291 | }
|
| 292 | }
|
| 293 | }
|
| 294 | });
|
| 295 | }
|
| 296 | });
|
| 297 | }
|
| 298 |
|
| 299 | ui.separator();
|
| 300 | ui.heading("Printer");
|
| 301 | ui.horizontal(|ui| {
|
| 302 | if ui
|
| 303 | .add_enabled(!self.printers_loading, egui::Button::new("Refresh"))
|
| 304 | .clicked()
|
| 305 | {
|
| 306 | self.refresh_printers();
|
| 307 | }
|
| 308 | if ui.button("Print").clicked() {
|
| 309 | action = PrintDialogAction::Print;
|
| 310 | }
|
| 311 | if self.printers_loading {
|
| 312 | ui.spinner();
|
| 313 | ui.label("Discovering printers…");
|
| 314 | }
|
| 315 | });
|
| 316 |
|
| 317 | ui.checkbox(&mut self.use_manual_port, "Enter port or queue manually");
|
| 318 | if self.use_manual_port {
|
| 319 | ui.horizontal(|ui| {
|
| 320 | ui.label("Port / queue:");
|
| 321 | ui.text_edit_singleline(&mut self.manual_port);
|
| 322 | });
|
| 323 | ui.label(
|
| 324 | "Examples: COM3, Bluetooth COM after pairing, printer queue (Windows), /dev/ttyUSB0 or /dev/rfcomm0 (Linux)",
|
| 325 | );
|
| 326 | } else if self.printers_loading && self.printers.is_empty() {
|
| 327 | ui.label("Searching for USB, spooler, serial, and paired Bluetooth printers…");
|
| 328 | } else if self.printers.is_empty() {
|
| 329 | ui.label(
|
| 330 | "No printers found. Connect a USB POS printer, pair a Classic Bluetooth SPP printer in the OS, refresh, or enter a port/queue manually.",
|
| 331 | );
|
| 332 | } else {
|
| 333 | // Fixed height so wheel scrolling works; avoid nesting inside another ScrollArea.
|
| 334 | const PRINTER_LIST_HEIGHT: f32 = 220.0;
|
| 335 | egui::ScrollArea::vertical()
|
| 336 | .id_salt("print_dialog_printer_list")
|
| 337 | .max_height(PRINTER_LIST_HEIGHT)
|
| 338 | .min_scrolled_height(PRINTER_LIST_HEIGHT)
|
| 339 | .auto_shrink([false, false])
|
| 340 | .show(ui, |ui| {
|
| 341 | ui.set_min_width(ui.available_width());
|
| 342 | for (i, printer) in self.printers.iter().enumerate() {
|
| 343 | ui.selectable_value(
|
| 344 | &mut self.selected_printer,
|
| 345 | Some(i),
|
| 346 | &printer.display_name,
|
| 347 | );
|
| 348 | }
|
| 349 | });
|
| 350 | }
|
| 351 |
|
| 352 | if let Some(err) = &self.error {
|
| 353 | ui.colored_label(egui::Color32::RED, err);
|
| 354 | }
|
| 355 |
|
| 356 | action
|
| 357 | }
|
| 358 | }
|
| 359 |
|
| 360 | #[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
| 361 | pub enum PrintDialogAction {
|
| 362 | None,
|
| 363 | Print,
|
| 364 | }
|
| 365 |
|
| 366 | #[cfg(test)]
|
| 367 | mod tests {
|
| 368 | use super::*;
|
| 369 | use posprint::print::PrinterTarget;
|
| 370 |
|
| 371 | #[test]
|
| 372 | fn prefers_last_connected_printer_over_first() {
|
| 373 | let mut dialog = PrintDialog::default();
|
| 374 | dialog.printers = vec![
|
| 375 | PrinterDevice {
|
| 376 | id: "a".into(),
|
| 377 | display_name: "First".into(),
|
| 378 | target: PrinterTarget::Serial("COM1".into()),
|
| 379 | },
|
| 380 | PrinterDevice {
|
| 381 | id: "b".into(),
|
| 382 | display_name: "Last".into(),
|
| 383 | target: PrinterTarget::WinSpooler("POS".into()),
|
| 384 | },
|
| 385 | ];
|
| 386 | dialog.apply_preferred_printer(Some("winspool:POS"));
|
| 387 | assert_eq!(dialog.selected_printer, Some(1));
|
| 388 | assert!(!dialog.use_manual_port);
|
| 389 | }
|
| 390 |
|
| 391 | #[test]
|
| 392 | fn falls_back_to_first_when_preferred_missing() {
|
| 393 | let mut dialog = PrintDialog::default();
|
| 394 | dialog.printers = vec![PrinterDevice {
|
| 395 | id: "a".into(),
|
| 396 | display_name: "Only".into(),
|
| 397 | target: PrinterTarget::Serial("COM1".into()),
|
| 398 | }];
|
| 399 | dialog.apply_preferred_printer(Some("winspool:Gone"));
|
| 400 | assert_eq!(dialog.selected_printer, Some(0));
|
| 401 | }
|
| 402 |
|
| 403 | #[test]
|
| 404 | fn restores_manual_preference() {
|
| 405 | let mut dialog = PrintDialog::default();
|
| 406 | dialog.apply_preferred_printer(Some("manual:COM9"));
|
| 407 | assert!(dialog.use_manual_port);
|
| 408 | assert_eq!(dialog.manual_port, "COM9");
|
| 409 | }
|
| 410 | }
|