BlueGit

timfa posprint

Files

posprint / src / print_dialog.rs

print_dialog.rs

print_dialog.rs 10.3 KiB Download Raw
1//! Shared print dialog state and UI (full app and print-only launcher).
2
3use std::collections::HashMap;
4use std::path::PathBuf;
5use std::sync::mpsc::{self, Receiver, TryRecvError};
6
7use eframe::egui;
8
9use posprint::dsl::parse;
10use posprint::io::{PosFile, PosMetadata};
11use posprint::params::{collect_parameters, parse_bool_value, ParamKind, ParamSpec};
12use posprint::pipeline;
13use posprint::print::{
14 list_printers, open_printer, open_printer_by_name, print_bytes, PrintError, PrinterDevice,
15};
16
17#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18pub enum PrintExecuteResult {
19 StillOpen,
20 Printed,
21}
22
23pub 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
36impl 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
53impl 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, cancel_label: &str) -> PrintDialogAction {
210 ui.heading("Parameters");
211 if self.param_specs.is_empty() {
212 ui.label("No parameters in this template.");
213 } else {
214 for spec in self.param_specs.clone() {
215 ui.horizontal(|ui| {
216 match spec.kind {
217 ParamKind::Text => {
218 ui.label(format!("{}:", spec.name));
219 let entry = self
220 .param_inputs
221 .entry(spec.name.clone())
222 .or_insert_with(String::new);
223 ui.text_edit_singleline(entry);
224 }
225 ParamKind::Bool => {
226 let mut checked = self
227 .param_inputs
228 .get(&spec.name)
229 .and_then(|v| parse_bool_value(v))
230 .unwrap_or(false);
231 if ui.checkbox(&mut checked, &spec.name).changed() {
232 self.param_inputs.insert(
233 spec.name.clone(),
234 if checked { "true" } else { "false" }.into(),
235 );
236 }
237 }
238 }
239 });
240 }
241 }
242
243 ui.separator();
244 ui.heading("Printer");
245 ui.horizontal(|ui| {
246 if ui
247 .add_enabled(!self.printers_loading, egui::Button::new("Refresh"))
248 .clicked()
249 {
250 self.refresh_printers();
251 }
252 if self.printers_loading {
253 ui.spinner();
254 ui.label("Discovering printers…");
255 }
256 });
257
258 ui.checkbox(&mut self.use_manual_port, "Enter port or queue manually");
259 if self.use_manual_port {
260 ui.horizontal(|ui| {
261 ui.label("Port / queue:");
262 ui.text_edit_singleline(&mut self.manual_port);
263 });
264 ui.label("Examples: COM3, printer queue name (Windows), /dev/ttyUSB0 (Linux)");
265 } else if self.printers_loading && self.printers.is_empty() {
266 ui.label("Searching for USB, spooler, and serial printers…");
267 } else if self.printers.is_empty() {
268 ui.label(
269 "No printers found. Connect a USB POS printer, refresh, or enter a port/queue manually.",
270 );
271 } else {
272 for (i, printer) in self.printers.iter().enumerate() {
273 ui.selectable_value(&mut self.selected_printer, Some(i), &printer.display_name);
274 }
275 }
276
277 if let Some(err) = &self.error {
278 ui.colored_label(egui::Color32::RED, err);
279 }
280
281 let mut action = PrintDialogAction::None;
282 ui.horizontal(|ui| {
283 if ui.button(cancel_label).clicked() {
284 action = PrintDialogAction::Cancel;
285 }
286 if ui.button("Print").clicked() {
287 action = PrintDialogAction::Print;
288 }
289 });
290 action
291 }
292}
293
294#[derive(Debug, Clone, Copy, PartialEq, Eq)]
295pub enum PrintDialogAction {
296 None,
297 Cancel,
298 Print,
299}