BlueGit

timfa posprint

Wire LAN discovery with cache-first scan and a settings toggle.

Enable optional TCP 9100 discovery (off by default): validate the cached LAN list first, show it, then scan local subnets and persist survivors.

Co-authored-by: Cursor <cursoragent@cursor.com>

timfa Tim Falken · pushed by timfa

Authored 2026-07-28 · 3 months ago

Hash
664b56f20d19d6920faf889dcc2bfaeee17dae08
Parent
32c21ccb
3 files changed +170 −27
src/app.rs +32 −0
@@ -132,6 +132,38 @@ impl PosPrintApp {
132 132 });
133 133 ui.label("Applies when you choose New. The current document width is unchanged.");
134 134
135 ui.add_space(16.0);
136 ui.heading("LAN network printers");
137 ui.label(
138 "Discover POS printers on the local network via raw ESC/POS TCP port 9100 (not CUPS).",
139 );
140 let mut lan = self.config.lan_printers_enabled;
141 if ui
142 .checkbox(&mut lan, "Enable LAN printer discovery (default: off)")
143 .changed()
144 {
145 self.config.lan_printers_enabled = lan;
146 self.settings_status = None;
147 }
148 ui.label(format!(
149 "Cached LAN printers: {}",
150 self.config.lan_printer_cache.len()
151 ));
152 if !self.config.lan_printer_cache.is_empty() {
153 egui::ScrollArea::vertical()
154 .id_salt("settings_lan_cache")
155 .max_height(100.0)
156 .show(ui, |ui| {
157 for entry in &self.config.lan_printer_cache {
158 ui.label(format!("{}:{}", entry.host, entry.port));
159 }
160 });
161 if ui.button("Clear LAN cache").clicked() {
162 self.config.clear_lan_printer_cache();
163 self.settings_status = Some("LAN printer cache cleared (save to persist).".into());
164 }
165 }
166
135 167 ui.add_space(16.0);
136 168 ui.heading("Trusted sites (noconfirm)");
137 169 ui.label(
@@ -132,6 +132,38 @@ impl PosPrintApp {
132 });
132 });
133 ui.label("Applies when you choose New. The current document width is unchanged.");
133 ui.label("Applies when you choose New. The current document width is unchanged.");
134
134
135 ui.add_space(16.0);
136 ui.heading("LAN network printers");
137 ui.label(
138 "Discover POS printers on the local network via raw ESC/POS TCP port 9100 (not CUPS).",
139 );
140 let mut lan = self.config.lan_printers_enabled;
141 if ui
142 .checkbox(&mut lan, "Enable LAN printer discovery (default: off)")
143 .changed()
144 {
145 self.config.lan_printers_enabled = lan;
146 self.settings_status = None;
147 }
148 ui.label(format!(
149 "Cached LAN printers: {}",
150 self.config.lan_printer_cache.len()
151 ));
152 if !self.config.lan_printer_cache.is_empty() {
153 egui::ScrollArea::vertical()
154 .id_salt("settings_lan_cache")
155 .max_height(100.0)
156 .show(ui, |ui| {
157 for entry in &self.config.lan_printer_cache {
158 ui.label(format!("{}:{}", entry.host, entry.port));
159 }
160 });
161 if ui.button("Clear LAN cache").clicked() {
162 self.config.clear_lan_printer_cache();
163 self.settings_status = Some("LAN printer cache cleared (save to persist).".into());
164 }
165 }
166
135 ui.add_space(16.0);
167 ui.add_space(16.0);
136 ui.heading("Trusted sites (noconfirm)");
168 ui.heading("Trusted sites (noconfirm)");
137 ui.label(
169 ui.label(
src/config.rs +38 −2
@@ -1,10 +1,12 @@
1 //! Persisted app preferences (trusted URL origins, default page width).
1 //! Persisted app preferences (trusted URL origins, default page width, LAN printers).
2 2
3 3 use std::fs;
4 4 use std::path::PathBuf;
5 5
6 6 use serde::{Deserialize, Serialize};
7 7
8 use crate::print::LanPrinterCacheEntry;
9
8 10 const CONFIG_VERSION: u32 = 1;
9 11
10 12 #[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
@@ -17,9 +19,15 @@ pub struct AppConfig {
17 19 /// Hostnames allowed to use `noconfirm=1` without asking again.
18 20 #[serde(default)]
19 21 pub trusted_origins: Vec<String>,
20 /// Last printer that printed successfully (`serial:…`, `winspool:…`, `usb:vid:pid`, or `manual:…`).
22 /// Last printer that printed successfully (`serial:…`, `winspool:…`, `usb:vid:pid`, `net:…`, or `manual:…`).
21 23 #[serde(default)]
22 24 pub last_printer_key: Option<String>,
25 /// When true, the print dialog discovers LAN printers via TCP 9100.
26 #[serde(default)]
27 pub lan_printers_enabled: bool,
28 /// Last known LAN printers (validated first on the next discovery).
29 #[serde(default)]
30 pub lan_printer_cache: Vec<LanPrinterCacheEntry>,
23 31 }
24 32
25 33 fn default_config_version() -> u32 {
@@ -37,6 +45,8 @@ impl Default for AppConfig {
37 45 default_page_width_mm: default_page_width_mm(),
38 46 trusted_origins: Vec::new(),
39 47 last_printer_key: None,
48 lan_printers_enabled: false,
49 lan_printer_cache: Vec::new(),
40 50 }
41 51 }
42 52 }
@@ -106,6 +116,10 @@ impl AppConfig {
106 116 self.last_printer_key = Some(key);
107 117 }
108 118
119 pub fn clear_lan_printer_cache(&mut self) {
120 self.lan_printer_cache.clear();
121 }
122
109 123 fn normalize(&mut self) {
110 124 self.version = CONFIG_VERSION;
111 125 if !self.default_page_width_mm.is_finite() || self.default_page_width_mm < 40.0 {
@@ -129,6 +143,17 @@ impl AppConfig {
129 143 self.last_printer_key = Some(trimmed.to_string());
130 144 }
131 145 }
146 self.lan_printer_cache.retain(|e| !e.host.trim().is_empty() && e.port != 0);
147 for entry in &mut self.lan_printer_cache {
148 entry.host = entry.host.trim().to_string();
149 if entry.port == 0 {
150 entry.port = crate::print::DEFAULT_PORT;
151 }
152 }
153 self.lan_printer_cache
154 .sort_by(|a, b| (&a.host, a.port).cmp(&(&b.host, b.port)));
155 self.lan_printer_cache
156 .dedup_by(|a, b| a.host == b.host && a.port == b.port);
132 157 }
133 158 }
134 159
@@ -216,11 +241,22 @@ mod tests {
216 241 cfg.default_page_width_mm = 58.0;
217 242 cfg.trust_origin("pos.example");
218 243 cfg.remember_printer("winspool:POS-58");
244 cfg.lan_printers_enabled = true;
245 cfg.lan_printer_cache.push(LanPrinterCacheEntry::new("192.168.1.50", 9100));
219 246 cfg.save_to_path(&path).unwrap();
220 247
221 248 let loaded = AppConfig::load_from_path(&path);
222 249 assert_eq!(loaded.default_page_width_mm, 58.0);
223 250 assert!(loaded.is_trusted("pos.example"));
224 251 assert_eq!(loaded.last_printer_key.as_deref(), Some("winspool:POS-58"));
252 assert!(loaded.lan_printers_enabled);
253 assert_eq!(loaded.lan_printer_cache.len(), 1);
254 assert_eq!(loaded.lan_printer_cache[0].host, "192.168.1.50");
255 }
256
257 #[test]
258 fn lan_disabled_by_default() {
259 assert!(!AppConfig::default().lan_printers_enabled);
260 assert!(AppConfig::default().lan_printer_cache.is_empty());
225 261 }
226 262 }
@@ -1,10 +1,12 @@
1//! Persisted app preferences (trusted URL origins, default page width).
1//! Persisted app preferences (trusted URL origins, default page width, LAN printers).
2
2
3use std::fs;
3use std::fs;
4use std::path::PathBuf;
4use std::path::PathBuf;
5
5
6use serde::{Deserialize, Serialize};
6use serde::{Deserialize, Serialize};
7
7
8use crate::print::LanPrinterCacheEntry;
9
8const CONFIG_VERSION: u32 = 1;
10const CONFIG_VERSION: u32 = 1;
9
11
10#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
12#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
@@ -17,9 +19,15 @@ pub struct AppConfig {
17 /// Hostnames allowed to use `noconfirm=1` without asking again.
19 /// Hostnames allowed to use `noconfirm=1` without asking again.
18 #[serde(default)]
20 #[serde(default)]
19 pub trusted_origins: Vec<String>,
21 pub trusted_origins: Vec<String>,
20 /// Last printer that printed successfully (`serial:…`, `winspool:…`, `usb:vid:pid`, or `manual:…`).
22 /// Last printer that printed successfully (`serial:…`, `winspool:…`, `usb:vid:pid`, `net:…`, or `manual:…`).
21 #[serde(default)]
23 #[serde(default)]
22 pub last_printer_key: Option<String>,
24 pub last_printer_key: Option<String>,
25 /// When true, the print dialog discovers LAN printers via TCP 9100.
26 #[serde(default)]
27 pub lan_printers_enabled: bool,
28 /// Last known LAN printers (validated first on the next discovery).
29 #[serde(default)]
30 pub lan_printer_cache: Vec<LanPrinterCacheEntry>,
23}
31}
24
32
25fn default_config_version() -> u32 {
33fn default_config_version() -> u32 {
@@ -37,6 +45,8 @@ impl Default for AppConfig {
37 default_page_width_mm: default_page_width_mm(),
45 default_page_width_mm: default_page_width_mm(),
38 trusted_origins: Vec::new(),
46 trusted_origins: Vec::new(),
39 last_printer_key: None,
47 last_printer_key: None,
48 lan_printers_enabled: false,
49 lan_printer_cache: Vec::new(),
40 }
50 }
41 }
51 }
42}
52}
@@ -106,6 +116,10 @@ impl AppConfig {
106 self.last_printer_key = Some(key);
116 self.last_printer_key = Some(key);
107 }
117 }
108
118
119 pub fn clear_lan_printer_cache(&mut self) {
120 self.lan_printer_cache.clear();
121 }
122
109 fn normalize(&mut self) {
123 fn normalize(&mut self) {
110 self.version = CONFIG_VERSION;
124 self.version = CONFIG_VERSION;
111 if !self.default_page_width_mm.is_finite() || self.default_page_width_mm < 40.0 {
125 if !self.default_page_width_mm.is_finite() || self.default_page_width_mm < 40.0 {
@@ -129,6 +143,17 @@ impl AppConfig {
129 self.last_printer_key = Some(trimmed.to_string());
143 self.last_printer_key = Some(trimmed.to_string());
130 }
144 }
131 }
145 }
146 self.lan_printer_cache.retain(|e| !e.host.trim().is_empty() && e.port != 0);
147 for entry in &mut self.lan_printer_cache {
148 entry.host = entry.host.trim().to_string();
149 if entry.port == 0 {
150 entry.port = crate::print::DEFAULT_PORT;
151 }
152 }
153 self.lan_printer_cache
154 .sort_by(|a, b| (&a.host, a.port).cmp(&(&b.host, b.port)));
155 self.lan_printer_cache
156 .dedup_by(|a, b| a.host == b.host && a.port == b.port);
132 }
157 }
133}
158}
134
159
@@ -216,11 +241,22 @@ mod tests {
216 cfg.default_page_width_mm = 58.0;
241 cfg.default_page_width_mm = 58.0;
217 cfg.trust_origin("pos.example");
242 cfg.trust_origin("pos.example");
218 cfg.remember_printer("winspool:POS-58");
243 cfg.remember_printer("winspool:POS-58");
244 cfg.lan_printers_enabled = true;
245 cfg.lan_printer_cache.push(LanPrinterCacheEntry::new("192.168.1.50", 9100));
219 cfg.save_to_path(&path).unwrap();
246 cfg.save_to_path(&path).unwrap();
220
247
221 let loaded = AppConfig::load_from_path(&path);
248 let loaded = AppConfig::load_from_path(&path);
222 assert_eq!(loaded.default_page_width_mm, 58.0);
249 assert_eq!(loaded.default_page_width_mm, 58.0);
223 assert!(loaded.is_trusted("pos.example"));
250 assert!(loaded.is_trusted("pos.example"));
224 assert_eq!(loaded.last_printer_key.as_deref(), Some("winspool:POS-58"));
251 assert_eq!(loaded.last_printer_key.as_deref(), Some("winspool:POS-58"));
252 assert!(loaded.lan_printers_enabled);
253 assert_eq!(loaded.lan_printer_cache.len(), 1);
254 assert_eq!(loaded.lan_printer_cache[0].host, "192.168.1.50");
255 }
256
257 #[test]
258 fn lan_disabled_by_default() {
259 assert!(!AppConfig::default().lan_printers_enabled);
260 assert!(AppConfig::default().lan_printer_cache.is_empty());
225 }
261 }
226}
262}
src/print_dialog.rs +100 −25
@@ -11,8 +11,10 @@ use posprint::io::{PosFile, PosMetadata};
11 11 use posprint::params::{collect_parameters, parse_bool_value, ParamKind, ParamSpec};
12 12 use posprint::pipeline;
13 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,
14 cache_entries_from_devices, find_preferred_printer_index, list_local_printers,
15 manual_printer_preference_key, merge_lan_devices, open_printer, open_printer_by_name,
16 print_bytes, printer_preference_key, remember_in_cache, scan_local_subnets, validate_cache,
17 PrintError, PrinterDevice, PrinterTarget, DEFAULT_PORT,
16 18 };
17 19 use posprint::config::AppConfig;
18 20
@@ -22,13 +24,24 @@ pub enum PrintExecuteResult {
22 24 Printed,
23 25 }
24 26
27 /// Progressive printer discovery results from the background thread.
28 #[derive(Debug)]
29 enum DiscoveryMsg {
30 /// Local USB/serial/spooler plus validated LAN cache (shown immediately).
31 Partial(Vec<PrinterDevice>),
32 /// Final list after optional full LAN scan (and cache update).
33 Done(Result<Vec<PrinterDevice>, PrintError>),
34 }
35
25 36 pub struct PrintDialog {
26 37 pub param_inputs: HashMap<String, String>,
27 38 pub param_specs: Vec<ParamSpec>,
28 39 pub last_params: HashMap<String, String>,
29 40 pub printers: Vec<PrinterDevice>,
30 41 pub printers_loading: bool,
31 printers_rx: Option<Receiver<Result<Vec<PrinterDevice>, PrintError>>>,
42 /// True while a LAN subnet scan may still be running after the cache partial.
43 pub lan_scanning: bool,
44 printers_rx: Option<Receiver<DiscoveryMsg>>,
32 45 pub selected_printer: Option<usize>,
33 46 pub manual_port: String,
34 47 pub use_manual_port: bool,
@@ -43,6 +56,7 @@ impl Default for PrintDialog {
43 56 last_params: HashMap::new(),
44 57 printers: Vec::new(),
45 58 printers_loading: false,
59 lan_scanning: false,
46 60 printers_rx: None,
47 61 selected_printer: None,
48 62 manual_port: String::new(),
@@ -80,11 +94,46 @@ impl PrintDialog {
80 94
81 95 pub fn start_printer_discovery(&mut self) {
82 96 self.printers_loading = true;
97 self.lan_scanning = false;
83 98 self.error = None;
84 99 let (tx, rx) = mpsc::channel();
85 100 self.printers_rx = Some(rx);
101
102 let cfg = AppConfig::load();
103 let lan_enabled = cfg.lan_printers_enabled;
104 let lan_cache = cfg.lan_printer_cache.clone();
105
86 106 std::thread::spawn(move || {
87 let _ = tx.send(list_printers());
107 let local = match list_local_printers() {
108 Ok(list) => list,
109 Err(e) => {
110 let _ = tx.send(DiscoveryMsg::Done(Err(e)));
111 return;
112 }
113 };
114
115 if !lan_enabled {
116 let _ = tx.send(DiscoveryMsg::Done(Ok(local)));
117 return;
118 }
119
120 // Phase 1: validate cached LAN hosts (fast) and show them with local devices.
121 let validated = validate_cache(&lan_cache);
122 let mut partial = local.clone();
123 partial.extend(validated.iter().cloned());
124 let _ = tx.send(DiscoveryMsg::Partial(partial));
125
126 // Phase 2: full subnet scan, merge, persist cache.
127 let scanned = scan_local_subnets(DEFAULT_PORT);
128 let lan = merge_lan_devices(&validated, &scanned);
129 let new_cache = cache_entries_from_devices(&lan);
130 let mut cfg = AppConfig::load();
131 cfg.lan_printer_cache = new_cache;
132 let _ = cfg.save();
133
134 let mut final_list = local;
135 final_list.extend(lan);
136 let _ = tx.send(DiscoveryMsg::Done(Ok(final_list)));
88 137 });
89 138 }
90 139
@@ -94,9 +143,16 @@ impl PrintDialog {
94 143 };
95 144
96 145 match rx.try_recv() {
97 Ok(result) => {
146 Ok(DiscoveryMsg::Partial(list)) => {
147 self.printers = list;
148 self.lan_scanning = true;
149 self.apply_preferred_printer(AppConfig::load().last_printer_key.as_deref());
150 ctx.request_repaint();
151 }
152 Ok(DiscoveryMsg::Done(result)) => {
98 153 self.printers_rx = None;
99 154 self.printers_loading = false;
155 self.lan_scanning = false;
100 156 match result {
101 157 Ok(list) => {
102 158 self.printers = list;
@@ -111,6 +167,7 @@ impl PrintDialog {
111 167 Err(TryRecvError::Disconnected) => {
112 168 self.printers_rx = None;
113 169 self.printers_loading = false;
170 self.lan_scanning = false;
114 171 }
115 172 }
116 173 }
@@ -141,26 +198,32 @@ impl PrintDialog {
141 198 }
142 199
143 200 fn remember_successful_printer(&self) {
144 let key = if self.use_manual_port {
201 let mut cfg = AppConfig::load();
202
203 if self.use_manual_port {
145 204 let name = self.manual_port.trim();
146 205 if name.is_empty() {
147 None
148 } else {
149 Some(manual_printer_preference_key(name))
206 return;
207 }
208 if let Some((host, port)) = posprint::print::parse_network_target(name) {
209 remember_in_cache(&mut cfg.lan_printer_cache, &host, port);
210 }
211 let key = manual_printer_preference_key(name);
212 if cfg.last_printer_key.as_deref() != Some(key.as_str()) {
213 cfg.remember_printer(key);
214 }
215 } else if let Some(printer) = self.selected_printer.and_then(|i| self.printers.get(i)) {
216 if let PrinterTarget::Network { host, port } = &printer.target {
217 remember_in_cache(&mut cfg.lan_printer_cache, host, *port);
218 }
219 let key = printer_preference_key(&printer.target);
220 if cfg.last_printer_key.as_deref() != Some(key.as_str()) {
221 cfg.remember_printer(key);
150 222 }
151 223 } 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 224 return;
162 225 }
163 cfg.remember_printer(key);
226
164 227 let _ = cfg.save();
165 228 }
166 229
@@ -310,22 +373,31 @@ impl PrintDialog {
310 373 }
311 374 if self.printers_loading {
312 375 ui.spinner();
313 ui.label("Discovering printers…");
376 if self.lan_scanning {
377 ui.label("Scanning LAN for TCP 9100 printers…");
378 } else {
379 ui.label("Discovering printers…");
380 }
314 381 }
315 382 });
316 383
317 ui.checkbox(&mut self.use_manual_port, "Enter port or queue manually");
384 ui.checkbox(
385 &mut self.use_manual_port,
386 "Enter port, queue, or LAN address manually",
387 );
318 388 if self.use_manual_port {
319 389 ui.horizontal(|ui| {
320 ui.label("Port / queue:");
390 ui.label("Port / queue / host:");
321 391 ui.text_edit_singleline(&mut self.manual_port);
322 392 });
323 ui.label("Examples: COM3, printer queue name (Windows), /dev/ttyUSB0 (Linux)");
393 ui.label(
394 "Examples: COM3, /dev/ttyUSB0, Windows queue name, 192.168.1.50, 192.168.1.50:9100",
395 );
324 396 } else if self.printers_loading && self.printers.is_empty() {
325 ui.label("Searching for USB, spooler, and serial printers…");
397 ui.label("Searching for USB, spooler, serial, and (if enabled) LAN printers…");
326 398 } else if self.printers.is_empty() {
327 399 ui.label(
328 "No printers found. Connect a USB POS printer, refresh, or enter a port/queue manually.",
400 "No printers found. Connect a USB POS printer, enable LAN printers in Settings, refresh, or enter an address manually.",
329 401 );
330 402 } else {
331 403 // Fixed height so wheel scrolling works; avoid nesting inside another ScrollArea.
@@ -345,6 +417,9 @@ impl PrintDialog {
345 417 );
346 418 }
347 419 });
420 if self.lan_scanning {
421 ui.label("LAN scan still running — list will update when finished.");
422 }
348 423 }
349 424
350 425 if let Some(err) = &self.error {
@@ -11,8 +11,10 @@ use posprint::io::{PosFile, PosMetadata};
11use posprint::params::{collect_parameters, parse_bool_value, ParamKind, ParamSpec};
11use posprint::params::{collect_parameters, parse_bool_value, ParamKind, ParamSpec};
12use posprint::pipeline;
12use posprint::pipeline;
13use posprint::print::{
13use posprint::print::{
14 find_preferred_printer_index, list_printers, manual_printer_preference_key, open_printer,
14 cache_entries_from_devices, find_preferred_printer_index, list_local_printers,
15 open_printer_by_name, print_bytes, printer_preference_key, PrintError, PrinterDevice,
15 manual_printer_preference_key, merge_lan_devices, open_printer, open_printer_by_name,
16 print_bytes, printer_preference_key, remember_in_cache, scan_local_subnets, validate_cache,
17 PrintError, PrinterDevice, PrinterTarget, DEFAULT_PORT,
16};
18};
17use posprint::config::AppConfig;
19use posprint::config::AppConfig;
18
20
@@ -22,13 +24,24 @@ pub enum PrintExecuteResult {
22 Printed,
24 Printed,
23}
25}
24
26
27/// Progressive printer discovery results from the background thread.
28#[derive(Debug)]
29enum DiscoveryMsg {
30 /// Local USB/serial/spooler plus validated LAN cache (shown immediately).
31 Partial(Vec<PrinterDevice>),
32 /// Final list after optional full LAN scan (and cache update).
33 Done(Result<Vec<PrinterDevice>, PrintError>),
34}
35
25pub struct PrintDialog {
36pub struct PrintDialog {
26 pub param_inputs: HashMap<String, String>,
37 pub param_inputs: HashMap<String, String>,
27 pub param_specs: Vec<ParamSpec>,
38 pub param_specs: Vec<ParamSpec>,
28 pub last_params: HashMap<String, String>,
39 pub last_params: HashMap<String, String>,
29 pub printers: Vec<PrinterDevice>,
40 pub printers: Vec<PrinterDevice>,
30 pub printers_loading: bool,
41 pub printers_loading: bool,
31 printers_rx: Option<Receiver<Result<Vec<PrinterDevice>, PrintError>>>,
42 /// True while a LAN subnet scan may still be running after the cache partial.
43 pub lan_scanning: bool,
44 printers_rx: Option<Receiver<DiscoveryMsg>>,
32 pub selected_printer: Option<usize>,
45 pub selected_printer: Option<usize>,
33 pub manual_port: String,
46 pub manual_port: String,
34 pub use_manual_port: bool,
47 pub use_manual_port: bool,
@@ -43,6 +56,7 @@ impl Default for PrintDialog {
43 last_params: HashMap::new(),
56 last_params: HashMap::new(),
44 printers: Vec::new(),
57 printers: Vec::new(),
45 printers_loading: false,
58 printers_loading: false,
59 lan_scanning: false,
46 printers_rx: None,
60 printers_rx: None,
47 selected_printer: None,
61 selected_printer: None,
48 manual_port: String::new(),
62 manual_port: String::new(),
@@ -80,11 +94,46 @@ impl PrintDialog {
80
94
81 pub fn start_printer_discovery(&mut self) {
95 pub fn start_printer_discovery(&mut self) {
82 self.printers_loading = true;
96 self.printers_loading = true;
97 self.lan_scanning = false;
83 self.error = None;
98 self.error = None;
84 let (tx, rx) = mpsc::channel();
99 let (tx, rx) = mpsc::channel();
85 self.printers_rx = Some(rx);
100 self.printers_rx = Some(rx);
101
102 let cfg = AppConfig::load();
103 let lan_enabled = cfg.lan_printers_enabled;
104 let lan_cache = cfg.lan_printer_cache.clone();
105
86 std::thread::spawn(move || {
106 std::thread::spawn(move || {
87 let _ = tx.send(list_printers());
107 let local = match list_local_printers() {
108 Ok(list) => list,
109 Err(e) => {
110 let _ = tx.send(DiscoveryMsg::Done(Err(e)));
111 return;
112 }
113 };
114
115 if !lan_enabled {
116 let _ = tx.send(DiscoveryMsg::Done(Ok(local)));
117 return;
118 }
119
120 // Phase 1: validate cached LAN hosts (fast) and show them with local devices.
121 let validated = validate_cache(&lan_cache);
122 let mut partial = local.clone();
123 partial.extend(validated.iter().cloned());
124 let _ = tx.send(DiscoveryMsg::Partial(partial));
125
126 // Phase 2: full subnet scan, merge, persist cache.
127 let scanned = scan_local_subnets(DEFAULT_PORT);
128 let lan = merge_lan_devices(&validated, &scanned);
129 let new_cache = cache_entries_from_devices(&lan);
130 let mut cfg = AppConfig::load();
131 cfg.lan_printer_cache = new_cache;
132 let _ = cfg.save();
133
134 let mut final_list = local;
135 final_list.extend(lan);
136 let _ = tx.send(DiscoveryMsg::Done(Ok(final_list)));
88 });
137 });
89 }
138 }
90
139
@@ -94,9 +143,16 @@ impl PrintDialog {
94 };
143 };
95
144
96 match rx.try_recv() {
145 match rx.try_recv() {
97 Ok(result) => {
146 Ok(DiscoveryMsg::Partial(list)) => {
147 self.printers = list;
148 self.lan_scanning = true;
149 self.apply_preferred_printer(AppConfig::load().last_printer_key.as_deref());
150 ctx.request_repaint();
151 }
152 Ok(DiscoveryMsg::Done(result)) => {
98 self.printers_rx = None;
153 self.printers_rx = None;
99 self.printers_loading = false;
154 self.printers_loading = false;
155 self.lan_scanning = false;
100 match result {
156 match result {
101 Ok(list) => {
157 Ok(list) => {
102 self.printers = list;
158 self.printers = list;
@@ -111,6 +167,7 @@ impl PrintDialog {
111 Err(TryRecvError::Disconnected) => {
167 Err(TryRecvError::Disconnected) => {
112 self.printers_rx = None;
168 self.printers_rx = None;
113 self.printers_loading = false;
169 self.printers_loading = false;
170 self.lan_scanning = false;
114 }
171 }
115 }
172 }
116 }
173 }
@@ -141,26 +198,32 @@ impl PrintDialog {
141 }
198 }
142
199
143 fn remember_successful_printer(&self) {
200 fn remember_successful_printer(&self) {
144 let key = if self.use_manual_port {
201 let mut cfg = AppConfig::load();
202
203 if self.use_manual_port {
145 let name = self.manual_port.trim();
204 let name = self.manual_port.trim();
146 if name.is_empty() {
205 if name.is_empty() {
147 None
206 return;
148 } else {
207 }
149 Some(manual_printer_preference_key(name))
208 if let Some((host, port)) = posprint::print::parse_network_target(name) {
209 remember_in_cache(&mut cfg.lan_printer_cache, &host, port);
210 }
211 let key = manual_printer_preference_key(name);
212 if cfg.last_printer_key.as_deref() != Some(key.as_str()) {
213 cfg.remember_printer(key);
214 }
215 } else if let Some(printer) = self.selected_printer.and_then(|i| self.printers.get(i)) {
216 if let PrinterTarget::Network { host, port } = &printer.target {
217 remember_in_cache(&mut cfg.lan_printer_cache, host, *port);
218 }
219 let key = printer_preference_key(&printer.target);
220 if cfg.last_printer_key.as_deref() != Some(key.as_str()) {
221 cfg.remember_printer(key);
150 }
222 }
151 } else {
223 } 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;
224 return;
162 }
225 }
163 cfg.remember_printer(key);
226
164 let _ = cfg.save();
227 let _ = cfg.save();
165 }
228 }
166
229
@@ -310,22 +373,31 @@ impl PrintDialog {
310 }
373 }
311 if self.printers_loading {
374 if self.printers_loading {
312 ui.spinner();
375 ui.spinner();
313 ui.label("Discovering printers…");
376 if self.lan_scanning {
377 ui.label("Scanning LAN for TCP 9100 printers…");
378 } else {
379 ui.label("Discovering printers…");
380 }
314 }
381 }
315 });
382 });
316
383
317 ui.checkbox(&mut self.use_manual_port, "Enter port or queue manually");
384 ui.checkbox(
385 &mut self.use_manual_port,
386 "Enter port, queue, or LAN address manually",
387 );
318 if self.use_manual_port {
388 if self.use_manual_port {
319 ui.horizontal(|ui| {
389 ui.horizontal(|ui| {
320 ui.label("Port / queue:");
390 ui.label("Port / queue / host:");
321 ui.text_edit_singleline(&mut self.manual_port);
391 ui.text_edit_singleline(&mut self.manual_port);
322 });
392 });
323 ui.label("Examples: COM3, printer queue name (Windows), /dev/ttyUSB0 (Linux)");
393 ui.label(
394 "Examples: COM3, /dev/ttyUSB0, Windows queue name, 192.168.1.50, 192.168.1.50:9100",
395 );
324 } else if self.printers_loading && self.printers.is_empty() {
396 } else if self.printers_loading && self.printers.is_empty() {
325 ui.label("Searching for USB, spooler, and serial printers…");
397 ui.label("Searching for USB, spooler, serial, and (if enabled) LAN printers…");
326 } else if self.printers.is_empty() {
398 } else if self.printers.is_empty() {
327 ui.label(
399 ui.label(
328 "No printers found. Connect a USB POS printer, refresh, or enter a port/queue manually.",
400 "No printers found. Connect a USB POS printer, enable LAN printers in Settings, refresh, or enter an address manually.",
329 );
401 );
330 } else {
402 } else {
331 // Fixed height so wheel scrolling works; avoid nesting inside another ScrollArea.
403 // Fixed height so wheel scrolling works; avoid nesting inside another ScrollArea.
@@ -345,6 +417,9 @@ impl PrintDialog {
345 );
417 );
346 }
418 }
347 });
419 });
420 if self.lan_scanning {
421 ui.label("LAN scan still running — list will update when finished.");
422 }
348 }
423 }
349
424
350 if let Some(err) = &self.error {
425 if let Some(err) = &self.error {