| 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 | list_printers, open_printer, open_printer_by_name, print_bytes, PrintError, PrinterDevice,
|
| 15 | };
|
| 16 |
|
| 17 | #[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
| 18 | pub enum PrintExecuteResult {
|
| 19 | StillOpen,
|
| 20 | Printed,
|
| 21 | }
|
| 22 |
|
| 23 | pub struct PrintDialog {
|
| 24 | pub param_inputs: HashMap<String, String>,
|
| 25 | pub param_specs: Vec<ParamSpec>,
|
| 26 | pub last_params: HashMap<String, String>,
|
| 27 | pub printers: Vec<PrinterDevice>,
|
| 28 | pub printers_loading: bool,
|
| 29 | printers_rx: Option<Receiver<Result<Vec<PrinterDevice>, PrintError>>>,
|
| 30 | pub selected_printer: Option<usize>,
|
| 31 | pub manual_port: String,
|
| 32 | pub use_manual_port: bool,
|
| 33 | pub error: Option<String>,
|
| 34 | }
|
| 35 |
|
| 36 | impl Default for PrintDialog {
|
| 37 | fn default() -> Self {
|
| 38 | Self {
|
| 39 | param_inputs: HashMap::new(),
|
| 40 | param_specs: Vec::new(),
|
| 41 | last_params: HashMap::new(),
|
| 42 | printers: Vec::new(),
|
| 43 | printers_loading: false,
|
| 44 | printers_rx: None,
|
| 45 | selected_printer: None,
|
| 46 | manual_port: String::new(),
|
| 47 | use_manual_port: false,
|
| 48 | error: None,
|
| 49 | }
|
| 50 | }
|
| 51 | }
|
| 52 |
|
| 53 | impl PrintDialog {
|
| 54 | pub fn prepare(&mut self, body: &str) -> Result<(), String> {
|
| 55 | self.error = None;
|
| 56 | let doc = parse(body).map_err(|e| e.to_string())?;
|
| 57 | self.param_specs = collect_parameters(&doc);
|
| 58 | self.param_inputs.clear();
|
| 59 | for spec in &self.param_specs {
|
| 60 | let value = match spec.kind {
|
| 61 | ParamKind::Bool => self
|
| 62 | .last_params
|
| 63 | .get(&spec.name)
|
| 64 | .cloned()
|
| 65 | .filter(|v| parse_bool_value(v).is_some())
|
| 66 | .unwrap_or_else(|| "false".into()),
|
| 67 | ParamKind::Text => self
|
| 68 | .last_params
|
| 69 | .get(&spec.name)
|
| 70 | .cloned()
|
| 71 | .unwrap_or_default(),
|
| 72 | };
|
| 73 | self.param_inputs.insert(spec.name.clone(), value);
|
| 74 | }
|
| 75 | self.start_printer_discovery();
|
| 76 | Ok(())
|
| 77 | }
|
| 78 |
|
| 79 | pub fn start_printer_discovery(&mut self) {
|
| 80 | self.printers_loading = true;
|
| 81 | self.error = None;
|
| 82 | let (tx, rx) = mpsc::channel();
|
| 83 | self.printers_rx = Some(rx);
|
| 84 | std::thread::spawn(move || {
|
| 85 | let _ = tx.send(list_printers());
|
| 86 | });
|
| 87 | }
|
| 88 |
|
| 89 | pub fn poll_printer_discovery(&mut self, ctx: &egui::Context) {
|
| 90 | let Some(rx) = &self.printers_rx else {
|
| 91 | return;
|
| 92 | };
|
| 93 |
|
| 94 | match rx.try_recv() {
|
| 95 | Ok(result) => {
|
| 96 | self.printers_rx = None;
|
| 97 | self.printers_loading = false;
|
| 98 | match result {
|
| 99 | Ok(list) => {
|
| 100 | self.printers = list;
|
| 101 | if self.selected_printer.is_none() && !self.printers.is_empty() {
|
| 102 | self.selected_printer = Some(0);
|
| 103 | }
|
| 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 | pub fn apply_inputs_to_last_params(&mut self) {
|
| 123 | self.last_params = self.param_inputs.clone();
|
| 124 | }
|
| 125 |
|
| 126 | pub fn execute_print(
|
| 127 | &mut self,
|
| 128 | body: &str,
|
| 129 | metadata: &PosMetadata,
|
| 130 | file_path: Option<&PathBuf>,
|
| 131 | ) -> PrintExecuteResult {
|
| 132 | self.error = None;
|
| 133 | if parse(body).is_err() {
|
| 134 | self.error = Some("Template has parse errors".into());
|
| 135 | return PrintExecuteResult::StillOpen;
|
| 136 | }
|
| 137 |
|
| 138 | for spec in &self.param_specs {
|
| 139 | if !self.param_inputs.contains_key(&spec.name) {
|
| 140 | self.error = Some(format!("Missing value for parameter {}", spec.name));
|
| 141 | return PrintExecuteResult::StillOpen;
|
| 142 | }
|
| 143 | if spec.kind == ParamKind::Bool {
|
| 144 | let raw = self.param_inputs.get(&spec.name).map(String::as_str).unwrap_or("");
|
| 145 | if parse_bool_value(raw).is_none() {
|
| 146 | self.error = Some(format!(
|
| 147 | "Invalid boolean for {}: use true/false",
|
| 148 | spec.name
|
| 149 | ));
|
| 150 | return PrintExecuteResult::StillOpen;
|
| 151 | }
|
| 152 | }
|
| 153 | }
|
| 154 |
|
| 155 | self.last_params = self.param_inputs.clone();
|
| 156 |
|
| 157 | let base_dir = file_path.and_then(|p| p.parent());
|
| 158 | let file = PosFile {
|
| 159 | version: 1,
|
| 160 | metadata: metadata.clone(),
|
| 161 | body: body.to_string(),
|
| 162 | };
|
| 163 | let bytes = match pipeline::encode_pos_file(&file, base_dir, &self.last_params) {
|
| 164 | Ok(b) => b,
|
| 165 | Err(e) => {
|
| 166 | self.error = Some(e.to_string());
|
| 167 | return PrintExecuteResult::StillOpen;
|
| 168 | }
|
| 169 | };
|
| 170 |
|
| 171 | let transport_result = if self.use_manual_port {
|
| 172 | let name = self.manual_port.trim();
|
| 173 | if name.is_empty() {
|
| 174 | self.error = Some("Select a printer or enter a port/queue name".into());
|
| 175 | return PrintExecuteResult::StillOpen;
|
| 176 | }
|
| 177 | open_printer_by_name(name)
|
| 178 | } else if let Some(target) = self.selected_printer_target() {
|
| 179 | open_printer(target)
|
| 180 | } else {
|
| 181 | self.error = Some("Select a printer".into());
|
| 182 | return PrintExecuteResult::StillOpen;
|
| 183 | };
|
| 184 |
|
| 185 | match transport_result {
|
| 186 | Ok(mut transport) => match print_bytes(transport.as_mut(), &bytes) {
|
| 187 | Ok(()) => PrintExecuteResult::Printed,
|
| 188 | Err(e) => {
|
| 189 | self.error = Some(format!("{e:?}"));
|
| 190 | PrintExecuteResult::StillOpen
|
| 191 | }
|
| 192 | },
|
| 193 | Err(e) => {
|
| 194 | self.error = Some(format!("{e:?}"));
|
| 195 | PrintExecuteResult::StillOpen
|
| 196 | }
|
| 197 | }
|
| 198 | }
|
| 199 |
|
| 200 | fn selected_printer_target(&self) -> Option<&posprint::print::PrinterTarget> {
|
| 201 | if self.use_manual_port {
|
| 202 | return None;
|
| 203 | }
|
| 204 | self.selected_printer
|
| 205 | .and_then(|i| self.printers.get(i))
|
| 206 | .map(|p| &p.target)
|
| 207 | }
|
| 208 |
|
| 209 | pub fn show_ui(&mut self, ui: &mut egui::Ui) -> PrintDialogAction {
|
| 210 | let mut action = PrintDialogAction::None;
|
| 211 |
|
| 212 | ui.heading("Parameters");
|
| 213 | if self.param_specs.is_empty() {
|
| 214 | ui.label("No parameters in this template.");
|
| 215 | } else {
|
| 216 | egui::ScrollArea::vertical()
|
| 217 | .id_salt("print_dialog_params")
|
| 218 | .max_height(140.0)
|
| 219 | .auto_shrink([false, true])
|
| 220 | .show(ui, |ui| {
|
| 221 | for spec in self.param_specs.clone() {
|
| 222 | ui.horizontal(|ui| {
|
| 223 | match spec.kind {
|
| 224 | ParamKind::Text => {
|
| 225 | ui.label(format!("{}:", spec.name));
|
| 226 | let entry = self
|
| 227 | .param_inputs
|
| 228 | .entry(spec.name.clone())
|
| 229 | .or_insert_with(String::new);
|
| 230 | ui.text_edit_singleline(entry);
|
| 231 | }
|
| 232 | ParamKind::Bool => {
|
| 233 | let mut checked = self
|
| 234 | .param_inputs
|
| 235 | .get(&spec.name)
|
| 236 | .and_then(|v| parse_bool_value(v))
|
| 237 | .unwrap_or(false);
|
| 238 | if ui.checkbox(&mut checked, &spec.name).changed() {
|
| 239 | self.param_inputs.insert(
|
| 240 | spec.name.clone(),
|
| 241 | if checked { "true" } else { "false" }.into(),
|
| 242 | );
|
| 243 | }
|
| 244 | }
|
| 245 | }
|
| 246 | });
|
| 247 | }
|
| 248 | });
|
| 249 | }
|
| 250 |
|
| 251 | ui.separator();
|
| 252 | ui.heading("Printer");
|
| 253 | ui.horizontal(|ui| {
|
| 254 | if ui
|
| 255 | .add_enabled(!self.printers_loading, egui::Button::new("Refresh"))
|
| 256 | .clicked()
|
| 257 | {
|
| 258 | self.refresh_printers();
|
| 259 | }
|
| 260 | if ui.button("Print").clicked() {
|
| 261 | action = PrintDialogAction::Print;
|
| 262 | }
|
| 263 | if self.printers_loading {
|
| 264 | ui.spinner();
|
| 265 | ui.label("Discovering printers…");
|
| 266 | }
|
| 267 | });
|
| 268 |
|
| 269 | ui.checkbox(&mut self.use_manual_port, "Enter port or queue manually");
|
| 270 | if self.use_manual_port {
|
| 271 | ui.horizontal(|ui| {
|
| 272 | ui.label("Port / queue:");
|
| 273 | ui.text_edit_singleline(&mut self.manual_port);
|
| 274 | });
|
| 275 | ui.label("Examples: COM3, printer queue name (Windows), /dev/ttyUSB0 (Linux)");
|
| 276 | } else if self.printers_loading && self.printers.is_empty() {
|
| 277 | ui.label("Searching for USB, spooler, and serial printers…");
|
| 278 | } else if self.printers.is_empty() {
|
| 279 | ui.label(
|
| 280 | "No printers found. Connect a USB POS printer, refresh, or enter a port/queue manually.",
|
| 281 | );
|
| 282 | } else {
|
| 283 | // Fixed height so wheel scrolling works; avoid nesting inside another ScrollArea.
|
| 284 | const PRINTER_LIST_HEIGHT: f32 = 220.0;
|
| 285 | egui::ScrollArea::vertical()
|
| 286 | .id_salt("print_dialog_printer_list")
|
| 287 | .max_height(PRINTER_LIST_HEIGHT)
|
| 288 | .min_scrolled_height(PRINTER_LIST_HEIGHT)
|
| 289 | .auto_shrink([false, false])
|
| 290 | .show(ui, |ui| {
|
| 291 | ui.set_min_width(ui.available_width());
|
| 292 | for (i, printer) in self.printers.iter().enumerate() {
|
| 293 | ui.selectable_value(
|
| 294 | &mut self.selected_printer,
|
| 295 | Some(i),
|
| 296 | &printer.display_name,
|
| 297 | );
|
| 298 | }
|
| 299 | });
|
| 300 | }
|
| 301 |
|
| 302 | if let Some(err) = &self.error {
|
| 303 | ui.colored_label(egui::Color32::RED, err);
|
| 304 | }
|
| 305 |
|
| 306 | action
|
| 307 | }
|
| 308 | }
|
| 309 |
|
| 310 | #[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
| 311 | pub enum PrintDialogAction {
|
| 312 | None,
|
| 313 | Print,
|
| 314 | }
|