| 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_parameter_names;
|
| 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_names: Vec<String>,
|
| 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_names: 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_names = collect_parameter_names(&doc);
|
| 58 | self.param_inputs.clear();
|
| 59 | for name in &self.param_names {
|
| 60 | let value = self
|
| 61 | .last_params
|
| 62 | .get(name)
|
| 63 | .cloned()
|
| 64 | .unwrap_or_default();
|
| 65 | self.param_inputs.insert(name.clone(), value);
|
| 66 | }
|
| 67 | self.start_printer_discovery();
|
| 68 | Ok(())
|
| 69 | }
|
| 70 |
|
| 71 | pub fn start_printer_discovery(&mut self) {
|
| 72 | self.printers_loading = true;
|
| 73 | self.error = None;
|
| 74 | let (tx, rx) = mpsc::channel();
|
| 75 | self.printers_rx = Some(rx);
|
| 76 | std::thread::spawn(move || {
|
| 77 | let _ = tx.send(list_printers());
|
| 78 | });
|
| 79 | }
|
| 80 |
|
| 81 | pub fn poll_printer_discovery(&mut self, ctx: &egui::Context) {
|
| 82 | let Some(rx) = &self.printers_rx else {
|
| 83 | return;
|
| 84 | };
|
| 85 |
|
| 86 | match rx.try_recv() {
|
| 87 | Ok(result) => {
|
| 88 | self.printers_rx = None;
|
| 89 | self.printers_loading = false;
|
| 90 | match result {
|
| 91 | Ok(list) => {
|
| 92 | self.printers = list;
|
| 93 | if self.selected_printer.is_none() && !self.printers.is_empty() {
|
| 94 | self.selected_printer = Some(0);
|
| 95 | }
|
| 96 | }
|
| 97 | Err(e) => self.error = Some(format!("{e:?}")),
|
| 98 | }
|
| 99 | }
|
| 100 | Err(TryRecvError::Empty) => {
|
| 101 | ctx.request_repaint();
|
| 102 | }
|
| 103 | Err(TryRecvError::Disconnected) => {
|
| 104 | self.printers_rx = None;
|
| 105 | self.printers_loading = false;
|
| 106 | }
|
| 107 | }
|
| 108 | }
|
| 109 |
|
| 110 | pub fn refresh_printers(&mut self) {
|
| 111 | self.start_printer_discovery();
|
| 112 | }
|
| 113 |
|
| 114 | pub fn apply_inputs_to_last_params(&mut self) {
|
| 115 | self.last_params = self.param_inputs.clone();
|
| 116 | }
|
| 117 |
|
| 118 | pub fn execute_print(
|
| 119 | &mut self,
|
| 120 | body: &str,
|
| 121 | metadata: &PosMetadata,
|
| 122 | file_path: Option<&PathBuf>,
|
| 123 | ) -> PrintExecuteResult {
|
| 124 | self.error = None;
|
| 125 | if parse(body).is_err() {
|
| 126 | self.error = Some("Template has parse errors".into());
|
| 127 | return PrintExecuteResult::StillOpen;
|
| 128 | }
|
| 129 |
|
| 130 | for name in &self.param_names {
|
| 131 | if !self.param_inputs.contains_key(name) {
|
| 132 | self.error = Some(format!("Missing value for parameter {name}"));
|
| 133 | return PrintExecuteResult::StillOpen;
|
| 134 | }
|
| 135 | }
|
| 136 |
|
| 137 | self.last_params = self.param_inputs.clone();
|
| 138 |
|
| 139 | let base_dir = file_path.and_then(|p| p.parent());
|
| 140 | let file = PosFile {
|
| 141 | version: 1,
|
| 142 | metadata: metadata.clone(),
|
| 143 | body: body.to_string(),
|
| 144 | };
|
| 145 | let bytes = match pipeline::encode_pos_file(&file, base_dir, &self.last_params) {
|
| 146 | Ok(b) => b,
|
| 147 | Err(e) => {
|
| 148 | self.error = Some(e.to_string());
|
| 149 | return PrintExecuteResult::StillOpen;
|
| 150 | }
|
| 151 | };
|
| 152 |
|
| 153 | let transport_result = if self.use_manual_port {
|
| 154 | let name = self.manual_port.trim();
|
| 155 | if name.is_empty() {
|
| 156 | self.error = Some("Select a printer or enter a port/queue name".into());
|
| 157 | return PrintExecuteResult::StillOpen;
|
| 158 | }
|
| 159 | open_printer_by_name(name)
|
| 160 | } else if let Some(target) = self.selected_printer_target() {
|
| 161 | open_printer(target)
|
| 162 | } else {
|
| 163 | self.error = Some("Select a printer".into());
|
| 164 | return PrintExecuteResult::StillOpen;
|
| 165 | };
|
| 166 |
|
| 167 | match transport_result {
|
| 168 | Ok(mut transport) => match print_bytes(transport.as_mut(), &bytes) {
|
| 169 | Ok(()) => PrintExecuteResult::Printed,
|
| 170 | Err(e) => {
|
| 171 | self.error = Some(format!("{e:?}"));
|
| 172 | PrintExecuteResult::StillOpen
|
| 173 | }
|
| 174 | },
|
| 175 | Err(e) => {
|
| 176 | self.error = Some(format!("{e:?}"));
|
| 177 | PrintExecuteResult::StillOpen
|
| 178 | }
|
| 179 | }
|
| 180 | }
|
| 181 |
|
| 182 | fn selected_printer_target(&self) -> Option<&posprint::print::PrinterTarget> {
|
| 183 | if self.use_manual_port {
|
| 184 | return None;
|
| 185 | }
|
| 186 | self.selected_printer
|
| 187 | .and_then(|i| self.printers.get(i))
|
| 188 | .map(|p| &p.target)
|
| 189 | }
|
| 190 |
|
| 191 | pub fn show_ui(&mut self, ui: &mut egui::Ui, cancel_label: &str) -> PrintDialogAction {
|
| 192 | ui.heading("Parameters");
|
| 193 | if self.param_names.is_empty() {
|
| 194 | ui.label("No parameters in this template.");
|
| 195 | } else {
|
| 196 | for name in self.param_names.clone() {
|
| 197 | ui.horizontal(|ui| {
|
| 198 | ui.label(format!("{name}:"));
|
| 199 | let entry = self.param_inputs.entry(name).or_insert_with(String::new);
|
| 200 | ui.text_edit_singleline(entry);
|
| 201 | });
|
| 202 | }
|
| 203 | }
|
| 204 |
|
| 205 | ui.separator();
|
| 206 | ui.heading("Printer");
|
| 207 | ui.horizontal(|ui| {
|
| 208 | if ui
|
| 209 | .add_enabled(!self.printers_loading, egui::Button::new("Refresh"))
|
| 210 | .clicked()
|
| 211 | {
|
| 212 | self.refresh_printers();
|
| 213 | }
|
| 214 | if self.printers_loading {
|
| 215 | ui.spinner();
|
| 216 | ui.label("Discovering printers…");
|
| 217 | }
|
| 218 | });
|
| 219 |
|
| 220 | ui.checkbox(&mut self.use_manual_port, "Enter port or queue manually");
|
| 221 | if self.use_manual_port {
|
| 222 | ui.horizontal(|ui| {
|
| 223 | ui.label("Port / queue:");
|
| 224 | ui.text_edit_singleline(&mut self.manual_port);
|
| 225 | });
|
| 226 | ui.label("Examples: COM3, printer queue name (Windows), /dev/ttyUSB0 (Linux)");
|
| 227 | } else if self.printers_loading && self.printers.is_empty() {
|
| 228 | ui.label("Searching for USB, spooler, and serial printers…");
|
| 229 | } else if self.printers.is_empty() {
|
| 230 | ui.label(
|
| 231 | "No printers found. Connect a USB POS printer, refresh, or enter a port/queue manually.",
|
| 232 | );
|
| 233 | } else {
|
| 234 | for (i, printer) in self.printers.iter().enumerate() {
|
| 235 | ui.selectable_value(&mut self.selected_printer, Some(i), &printer.display_name);
|
| 236 | }
|
| 237 | }
|
| 238 |
|
| 239 | if let Some(err) = &self.error {
|
| 240 | ui.colored_label(egui::Color32::RED, err);
|
| 241 | }
|
| 242 |
|
| 243 | let mut action = PrintDialogAction::None;
|
| 244 | ui.horizontal(|ui| {
|
| 245 | if ui.button(cancel_label).clicked() {
|
| 246 | action = PrintDialogAction::Cancel;
|
| 247 | }
|
| 248 | if ui.button("Print").clicked() {
|
| 249 | action = PrintDialogAction::Print;
|
| 250 | }
|
| 251 | });
|
| 252 | action
|
| 253 | }
|
| 254 | }
|
| 255 |
|
| 256 | #[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
| 257 | pub enum PrintDialogAction {
|
| 258 | None,
|
| 259 | Cancel,
|
| 260 | Print,
|
| 261 | }
|