Remember last successful printer for noconfirm auto-select.
Prefer that device when still connected; document browser protocol prompts as browser-owned. Co-authored-by: Cursor <cursoragent@cursor.com>
@@ -76,7 +76,7 @@ ESC/POS generation is **in-tree** (`escpos.rs`), not the `escpos` crates.io pack
76
76
| Toolbar | `app.rs` | New, Open, Save, Save As, Insert, Print |
77
77
| Document page width / zoom | `app.rs` | Per-document width (mm), preview zoom |
78
78
| Print dialog | `print_dialog.rs` | Parameters + multi-transport printer picker |
79
| App config | `config.rs` | `%APPDATA%/posprint/config.json` (Windows) / `~/.config/posprint/config.json` |
79
| App config | `config.rs` | `%APPDATA%/posprint/config.json` (Windows) / `~/.config/posprint/config.json` (trusted origins, default width, last printer) |
80
80
81
81
While the print dialog is open, the main UI is disabled and editor autocomplete does not steal focus.
82
82
@@ -155,8 +155,8 @@ Legacy JSON fields `preview_mode` and `cut_after_print` are ignored if present.
155
155
|------|---------|
156
156
| Template + metadata | `.pos` file |
157
157
| Last parameter values | In-memory (`print_dialog.last_params`) |
158
| Default page width / trusted origins | `config.rs` → platform config JSON |
159
| Recent files / selected printer | Not persisted |
158
| Default page width / trusted origins / last printer | `config.rs` → platform config JSON |
159
| Recent files | Not persisted |
160
160
161
161
---
162
162
@@ -76,7 +76,7 @@ ESC/POS generation is **in-tree** (`escpos.rs`), not the `escpos` crates.io pack76
| Toolbar | `app.rs` | New, Open, Save, Save As, Insert, Print |76
| Toolbar | `app.rs` | New, Open, Save, Save As, Insert, Print |77
| Document page width / zoom | `app.rs` | Per-document width (mm), preview zoom |77
| Document page width / zoom | `app.rs` | Per-document width (mm), preview zoom |78
| Print dialog | `print_dialog.rs` | Parameters + multi-transport printer picker |78
| Print dialog | `print_dialog.rs` | Parameters + multi-transport printer picker |79
| App config | `config.rs` | `%APPDATA%/posprint/config.json` (Windows) / `~/.config/posprint/config.json` |79
| App config | `config.rs` | `%APPDATA%/posprint/config.json` (Windows) / `~/.config/posprint/config.json` (trusted origins, default width, last printer) |80
80
81
While the print dialog is open, the main UI is disabled and editor autocomplete does not steal focus.81
While the print dialog is open, the main UI is disabled and editor autocomplete does not steal focus.82
82
@@ -155,8 +155,8 @@ Legacy JSON fields `preview_mode` and `cut_after_print` are ignored if present.155
|------|---------|155
|------|---------|156
| Template + metadata | `.pos` file |156
| Template + metadata | `.pos` file |157
| Last parameter values | In-memory (`print_dialog.last_params`) |157
| Last parameter values | In-memory (`print_dialog.last_params`) |158
| Default page width / trusted origins | `config.rs` → platform config JSON |158
| Default page width / trusted origins / last printer | `config.rs` → platform config JSON |159
| Recent files / selected printer | Not persisted |159
| Recent files | Not persisted |160
160
161
---161
---162
162
@@ -309,7 +309,7 @@ Websites can open the print dialog with an embedded template:
309
309
posprint://print?v=1&d=…
310
310
```
311
311
312
Add `&noconfirm=1&referrer=<percent-encoded verify URL>` to print after the site’s verify endpoint returns HTTP 200 and (on first use) the user trusts that domain (**Settings → Trusted sites**). Encoding helpers live in [`lib/`](../lib/). Full guide: [POSPRINT-URL.md](POSPRINT-URL.md).
312
Add `&noconfirm=1&referrer=<percent-encoded verify URL>` to print after the site’s verify endpoint returns HTTP 200 and (on first use) the user trusts that domain (**Settings → Trusted sites**). Auto-print uses the last printer that printed successfully when that device is still available. Encoding helpers live in [`lib/`](../lib/). Full guide: [POSPRINT-URL.md](POSPRINT-URL.md).
313
313
314
314
`@image` may use `https://…` or `http://…` (downloaded when preview/print needs the image).
315
315
@@ -309,7 +309,7 @@ Websites can open the print dialog with an embedded template:309
posprint://print?v=1&d=…309
posprint://print?v=1&d=…310
```310
```311
311
312
Add `&noconfirm=1&referrer=<percent-encoded verify URL>` to print after the site’s verify endpoint returns HTTP 200 and (on first use) the user trusts that domain (**Settings → Trusted sites**). Encoding helpers live in [`lib/`](../lib/). Full guide: [POSPRINT-URL.md](POSPRINT-URL.md).312
Add `&noconfirm=1&referrer=<percent-encoded verify URL>` to print after the site’s verify endpoint returns HTTP 200 and (on first use) the user trusts that domain (**Settings → Trusted sites**). Auto-print uses the last printer that printed successfully when that device is still available. Encoding helpers live in [`lib/`](../lib/). Full guide: [POSPRINT-URL.md](POSPRINT-URL.md).313
313
314
`@image` may use `https://…` or `http://…` (downloaded when preview/print needs the image).314
`@image` may use `https://…` or `http://…` (downloaded when preview/print needs the image).315
315
@@ -48,10 +48,22 @@ The OS protocol handler only receives the URL string — not the browser Referer
48
48
| posprint shows **Trust this site?** | If trusted, prints without asking |
49
49
| **Trust and print** stores the hostname | Revoke under **Settings → Trusted sites** |
50
50
51
After a successful print, posprint remembers that printer. On the next `noconfirm` (and in the interactive dialog), it selects that printer again **if it is still connected**; otherwise it keeps the usual first/default selection.
52
51
53
Without `referrer`, `noconfirm=1` is rejected. Without `noconfirm`, behaviour is unchanged (interactive print dialog).
52
54
53
55
Localhost / loopback verification URLs are allowed. Other private LAN addresses (e.g. `192.168.x.x`) are blocked.
54
56
57
### Browser “Open posprint?” prompt
58
59
Browsers (Chrome / Edge) always ask before launching a custom protocol. That dialog is **not** controlled by posprint.
60
61
- Typing or pasting `posprint://…` in the address bar usually offers **no** “always allow” option (no site origin).
62
- A real click from an **https://** page can show “Always allow this site to open…” once the browser remembers the choice for that origin.
63
- `http://127.0.0.1` / localhost test pages often never get a persistent allow checkbox.
64
65
No extra posprint registry or config is required for protocol registration beyond what install / first run already does.
66
55
67
---
56
68
57
69
## Size limits
@@ -48,10 +48,22 @@ The OS protocol handler only receives the URL string — not the browser Referer48
| posprint shows **Trust this site?** | If trusted, prints without asking |48
| posprint shows **Trust this site?** | If trusted, prints without asking |49
| **Trust and print** stores the hostname | Revoke under **Settings → Trusted sites** |49
| **Trust and print** stores the hostname | Revoke under **Settings → Trusted sites** |50
50
51
After a successful print, posprint remembers that printer. On the next `noconfirm` (and in the interactive dialog), it selects that printer again **if it is still connected**; otherwise it keeps the usual first/default selection.52
51
Without `referrer`, `noconfirm=1` is rejected. Without `noconfirm`, behaviour is unchanged (interactive print dialog).53
Without `referrer`, `noconfirm=1` is rejected. Without `noconfirm`, behaviour is unchanged (interactive print dialog).52
54
53
Localhost / loopback verification URLs are allowed. Other private LAN addresses (e.g. `192.168.x.x`) are blocked.55
Localhost / loopback verification URLs are allowed. Other private LAN addresses (e.g. `192.168.x.x`) are blocked.54
56
57
### Browser “Open posprint?” prompt58
59
Browsers (Chrome / Edge) always ask before launching a custom protocol. That dialog is **not** controlled by posprint.60
61
- Typing or pasting `posprint://…` in the address bar usually offers **no** “always allow” option (no site origin).62
- A real click from an **https://** page can show “Always allow this site to open…” once the browser remembers the choice for that origin.63
- `http://127.0.0.1` / localhost test pages often never get a persistent allow checkbox.64
65
No extra posprint registry or config is required for protocol registration beyond what install / first run already does.66
55
---67
---56
68
57
## Size limits69
## Size limits@@ -17,6 +17,9 @@ pub struct AppConfig {
17
17
/// Hostnames allowed to use `noconfirm=1` without asking again.
18
18
#[serde(default)]
19
19
pub trusted_origins: Vec<String>,
20
/// Last printer that printed successfully (`serial:…`, `winspool:…`, `usb:vid:pid`, or `manual:…`).
21
#[serde(default)]
22
pub last_printer_key: Option<String>,
20
23
}
21
24
22
25
fn default_config_version() -> u32 {
@@ -33,6 +36,7 @@ impl Default for AppConfig {
33
36
version: CONFIG_VERSION,
34
37
default_page_width_mm: default_page_width_mm(),
35
38
trusted_origins: Vec::new(),
39
last_printer_key: None,
36
40
}
37
41
}
38
42
}
@@ -94,6 +98,14 @@ impl AppConfig {
94
98
self.trusted_origins.retain(|o| o != &host);
95
99
}
96
100
101
pub fn remember_printer(&mut self, key: impl Into<String>) {
102
let key = key.into();
103
if key.is_empty() {
104
return;
105
}
106
self.last_printer_key = Some(key);
107
}
108
97
109
fn normalize(&mut self) {
98
110
self.version = CONFIG_VERSION;
99
111
if !self.default_page_width_mm.is_finite() || self.default_page_width_mm < 40.0 {
@@ -109,6 +121,14 @@ impl AppConfig {
109
121
hosts.sort();
110
122
hosts.dedup();
111
123
self.trusted_origins = hosts;
124
if let Some(key) = &self.last_printer_key {
125
let trimmed = key.trim();
126
if trimmed.is_empty() {
127
self.last_printer_key = None;
128
} else if trimmed != key.as_str() {
129
self.last_printer_key = Some(trimmed.to_string());
130
}
131
}
112
132
}
113
133
}
114
134
@@ -195,10 +215,12 @@ mod tests {
195
215
let mut cfg = AppConfig::default();
196
216
cfg.default_page_width_mm = 58.0;
197
217
cfg.trust_origin("pos.example");
218
cfg.remember_printer("winspool:POS-58");
198
219
cfg.save_to_path(&path).unwrap();
199
220
200
221
let loaded = AppConfig::load_from_path(&path);
201
222
assert_eq!(loaded.default_page_width_mm, 58.0);
202
223
assert!(loaded.is_trusted("pos.example"));
224
assert_eq!(loaded.last_printer_key.as_deref(), Some("winspool:POS-58"));
203
225
}
204
226
}
@@ -17,6 +17,9 @@ pub struct AppConfig {17
/// Hostnames allowed to use `noconfirm=1` without asking again.
17
/// Hostnames allowed to use `noconfirm=1` without asking again.
18
#[serde(default)]
18
#[serde(default)]
19
pub trusted_origins: Vec<String>,
19
pub trusted_origins: Vec<String>,
20
/// Last printer that printed successfully (`serial:…`, `winspool:…`, `usb:vid:pid`, or `manual:…`).
21
#[serde(default)]
22
pub last_printer_key: Option<String>,
20
}
23
}
21
24
22
fn default_config_version() -> u32 {
25
fn default_config_version() -> u32 {
@@ -33,6 +36,7 @@ impl Default for AppConfig {33
version: CONFIG_VERSION,
36
version: CONFIG_VERSION,
34
default_page_width_mm: default_page_width_mm(),
37
default_page_width_mm: default_page_width_mm(),
35
trusted_origins: Vec::new(),
38
trusted_origins: Vec::new(),
39
last_printer_key: None,
36
}
40
}
37
}
41
}
38
}
42
}
@@ -94,6 +98,14 @@ impl AppConfig {94
self.trusted_origins.retain(|o| o != &host);
98
self.trusted_origins.retain(|o| o != &host);
95
}
99
}
96
100
101
pub fn remember_printer(&mut self, key: impl Into<String>) {
102
let key = key.into();
103
if key.is_empty() {
104
return;
105
}
106
self.last_printer_key = Some(key);
107
}
108
97
fn normalize(&mut self) {
109
fn normalize(&mut self) {
98
self.version = CONFIG_VERSION;
110
self.version = CONFIG_VERSION;
99
if !self.default_page_width_mm.is_finite() || self.default_page_width_mm < 40.0 {
111
if !self.default_page_width_mm.is_finite() || self.default_page_width_mm < 40.0 {
@@ -109,6 +121,14 @@ impl AppConfig {109
hosts.sort();
121
hosts.sort();
110
hosts.dedup();
122
hosts.dedup();
111
self.trusted_origins = hosts;
123
self.trusted_origins = hosts;
124
if let Some(key) = &self.last_printer_key {
125
let trimmed = key.trim();
126
if trimmed.is_empty() {
127
self.last_printer_key = None;
128
} else if trimmed != key.as_str() {
129
self.last_printer_key = Some(trimmed.to_string());
130
}
131
}
112
}
132
}
113
}
133
}
114
134
@@ -195,10 +215,12 @@ mod tests {195
let mut cfg = AppConfig::default();
215
let mut cfg = AppConfig::default();
196
cfg.default_page_width_mm = 58.0;
216
cfg.default_page_width_mm = 58.0;
197
cfg.trust_origin("pos.example");
217
cfg.trust_origin("pos.example");
218
cfg.remember_printer("winspool:POS-58");
198
cfg.save_to_path(&path).unwrap();
219
cfg.save_to_path(&path).unwrap();
199
220
200
let loaded = AppConfig::load_from_path(&path);
221
let loaded = AppConfig::load_from_path(&path);
201
assert_eq!(loaded.default_page_width_mm, 58.0);
222
assert_eq!(loaded.default_page_width_mm, 58.0);
202
assert!(loaded.is_trusted("pos.example"));
223
assert!(loaded.is_trusted("pos.example"));
224
assert_eq!(loaded.last_printer_key.as_deref(), Some("winspool:POS-58"));
203
}
225
}
204
}
226
}
@@ -200,6 +200,33 @@ pub fn print_bytes<T: PrinterTransport + ?Sized>(transport: &mut T, data: &[u8])
200
200
Ok(())
201
201
}
202
202
203
/// Stable key for remembering the last successful printer across reconnects.
204
/// USB uses vid:pid only (bus/address change when replugged).
205
pub fn printer_preference_key(target: &PrinterTarget) -> String {
206
match target {
207
PrinterTarget::Serial(port) => format!("serial:{port}"),
208
PrinterTarget::WinSpooler(name) => format!("winspool:{name}"),
209
PrinterTarget::UsbDirect { vid, pid, .. } => {
210
format!("usb:{vid:04x}:{pid:04x}")
211
}
212
}
213
}
214
215
pub fn manual_printer_preference_key(name: &str) -> String {
216
format!("manual:{}", name.trim())
217
}
218
219
/// Index of a discovered printer matching a stored preference key, if still connected.
220
pub fn find_preferred_printer_index(printers: &[PrinterDevice], key: &str) -> Option<usize> {
221
let key = key.trim();
222
if key.is_empty() || key.starts_with("manual:") {
223
return None;
224
}
225
printers
226
.iter()
227
.position(|p| printer_preference_key(&p.target) == key)
228
}
229
203
230
pub struct MockTransport {
204
231
pub written: Vec<u8>,
205
232
}
@@ -263,4 +290,47 @@ mod tests {
263
290
});
264
291
assert!(is_usb_serial_candidate(&usb));
265
292
}
293
294
#[test]
295
fn preference_key_ignores_usb_bus_address() {
296
let a = PrinterTarget::UsbDirect {
297
vid: 0x0416,
298
pid: 0x5011,
299
bus: 1,
300
address: 2,
301
};
302
let b = PrinterTarget::UsbDirect {
303
vid: 0x0416,
304
pid: 0x5011,
305
bus: 3,
306
address: 9,
307
};
308
assert_eq!(printer_preference_key(&a), printer_preference_key(&b));
309
assert_eq!(printer_preference_key(&a), "usb:0416:5011");
310
}
311
312
#[test]
313
fn finds_preferred_printer_by_key() {
314
let printers = vec![
315
PrinterDevice {
316
id: "serial:COM1".into(),
317
display_name: "COM1".into(),
318
target: PrinterTarget::Serial("COM1".into()),
319
},
320
PrinterDevice {
321
id: "winspool:POS".into(),
322
display_name: "POS".into(),
323
target: PrinterTarget::WinSpooler("POS".into()),
324
},
325
];
326
assert_eq!(
327
find_preferred_printer_index(&printers, "winspool:POS"),
328
Some(1)
329
);
330
assert_eq!(find_preferred_printer_index(&printers, "serial:COM9"), None);
331
assert_eq!(
332
find_preferred_printer_index(&printers, "manual:COM3"),
333
None
334
);
335
}
266
336
}
@@ -200,6 +200,33 @@ pub fn print_bytes<T: PrinterTransport + ?Sized>(transport: &mut T, data: &[u8])200
Ok(())
200
Ok(())
201
}
201
}
202
202
203
/// Stable key for remembering the last successful printer across reconnects.
204
/// USB uses vid:pid only (bus/address change when replugged).
205
pub fn printer_preference_key(target: &PrinterTarget) -> String {
206
match target {
207
PrinterTarget::Serial(port) => format!("serial:{port}"),
208
PrinterTarget::WinSpooler(name) => format!("winspool:{name}"),
209
PrinterTarget::UsbDirect { vid, pid, .. } => {
210
format!("usb:{vid:04x}:{pid:04x}")
211
}
212
}
213
}
214
215
pub fn manual_printer_preference_key(name: &str) -> String {
216
format!("manual:{}", name.trim())
217
}
218
219
/// Index of a discovered printer matching a stored preference key, if still connected.
220
pub fn find_preferred_printer_index(printers: &[PrinterDevice], key: &str) -> Option<usize> {
221
let key = key.trim();
222
if key.is_empty() || key.starts_with("manual:") {
223
return None;
224
}
225
printers
226
.iter()
227
.position(|p| printer_preference_key(&p.target) == key)
228
}
229
203
pub struct MockTransport {
230
pub struct MockTransport {
204
pub written: Vec<u8>,
231
pub written: Vec<u8>,
205
}
232
}
@@ -263,4 +290,47 @@ mod tests {263
});
290
});
264
assert!(is_usb_serial_candidate(&usb));
291
assert!(is_usb_serial_candidate(&usb));
265
}
292
}
293
294
#[test]
295
fn preference_key_ignores_usb_bus_address() {
296
let a = PrinterTarget::UsbDirect {
297
vid: 0x0416,
298
pid: 0x5011,
299
bus: 1,
300
address: 2,
301
};
302
let b = PrinterTarget::UsbDirect {
303
vid: 0x0416,
304
pid: 0x5011,
305
bus: 3,
306
address: 9,
307
};
308
assert_eq!(printer_preference_key(&a), printer_preference_key(&b));
309
assert_eq!(printer_preference_key(&a), "usb:0416:5011");
310
}
311
312
#[test]
313
fn finds_preferred_printer_by_key() {
314
let printers = vec![
315
PrinterDevice {
316
id: "serial:COM1".into(),
317
display_name: "COM1".into(),
318
target: PrinterTarget::Serial("COM1".into()),
319
},
320
PrinterDevice {
321
id: "winspool:POS".into(),
322
display_name: "POS".into(),
323
target: PrinterTarget::WinSpooler("POS".into()),
324
},
325
];
326
assert_eq!(
327
find_preferred_printer_index(&printers, "winspool:POS"),
328
Some(1)
329
);
330
assert_eq!(find_preferred_printer_index(&printers, "serial:COM9"), None);
331
assert_eq!(
332
find_preferred_printer_index(&printers, "manual:COM3"),
333
None
334
);
335
}
266
}
336
}
@@ -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
list_printers, open_printer, open_printer_by_name, print_bytes, PrintError, PrinterDevice,
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,
15
16
};
17
use posprint::config::AppConfig;
16
18
17
19
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18
20
pub enum PrintExecuteResult {
@@ -98,9 +100,7 @@ impl PrintDialog {
98
100
match result {
99
101
Ok(list) => {
100
102
self.printers = list;
101
if self.selected_printer.is_none() && !self.printers.is_empty() {
102
self.selected_printer = Some(0);
103
}
103
self.apply_preferred_printer(AppConfig::load().last_printer_key.as_deref());
104
104
}
105
105
Err(e) => self.error = Some(format!("{e:?}")),
106
106
}
@@ -119,6 +119,51 @@ impl PrintDialog {
119
119
self.start_printer_discovery();
120
120
}
121
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
122
167
pub fn apply_inputs_to_last_params(&mut self) {
123
168
self.last_params = self.param_inputs.clone();
124
169
}
@@ -184,7 +229,10 @@ impl PrintDialog {
184
229
185
230
match transport_result {
186
231
Ok(mut transport) => match print_bytes(transport.as_mut(), &bytes) {
187
Ok(()) => PrintExecuteResult::Printed,
232
Ok(()) => {
233
self.remember_successful_printer();
234
PrintExecuteResult::Printed
235
}
188
236
Err(e) => {
189
237
self.error = Some(format!("{e:?}"));
190
238
PrintExecuteResult::StillOpen
@@ -312,3 +360,49 @@ pub enum PrintDialogAction {
312
360
None,
313
361
Print,
314
362
}
363
364
#[cfg(test)]
365
mod tests {
366
use super::*;
367
use posprint::print::PrinterTarget;
368
369
#[test]
370
fn prefers_last_connected_printer_over_first() {
371
let mut dialog = PrintDialog::default();
372
dialog.printers = vec![
373
PrinterDevice {
374
id: "a".into(),
375
display_name: "First".into(),
376
target: PrinterTarget::Serial("COM1".into()),
377
},
378
PrinterDevice {
379
id: "b".into(),
380
display_name: "Last".into(),
381
target: PrinterTarget::WinSpooler("POS".into()),
382
},
383
];
384
dialog.apply_preferred_printer(Some("winspool:POS"));
385
assert_eq!(dialog.selected_printer, Some(1));
386
assert!(!dialog.use_manual_port);
387
}
388
389
#[test]
390
fn falls_back_to_first_when_preferred_missing() {
391
let mut dialog = PrintDialog::default();
392
dialog.printers = vec![PrinterDevice {
393
id: "a".into(),
394
display_name: "Only".into(),
395
target: PrinterTarget::Serial("COM1".into()),
396
}];
397
dialog.apply_preferred_printer(Some("winspool:Gone"));
398
assert_eq!(dialog.selected_printer, Some(0));
399
}
400
401
#[test]
402
fn restores_manual_preference() {
403
let mut dialog = PrintDialog::default();
404
dialog.apply_preferred_printer(Some("manual:COM9"));
405
assert!(dialog.use_manual_port);
406
assert_eq!(dialog.manual_port, "COM9");
407
}
408
}
@@ -11,8 +11,10 @@ use posprint::io::{PosFile, PosMetadata};11
use posprint::params::{collect_parameters, parse_bool_value, ParamKind, ParamSpec};
11
use posprint::params::{collect_parameters, parse_bool_value, ParamKind, ParamSpec};
12
use posprint::pipeline;
12
use posprint::pipeline;
13
use posprint::print::{
13
use posprint::print::{
14
list_printers, open_printer, open_printer_by_name, print_bytes, PrintError, PrinterDevice,
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,
15
};
16
};
17
use posprint::config::AppConfig;
16
18
17
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18
pub enum PrintExecuteResult {
20
pub enum PrintExecuteResult {
@@ -98,9 +100,7 @@ impl PrintDialog {98
match result {
100
match result {
99
Ok(list) => {
101
Ok(list) => {
100
self.printers = list;
102
self.printers = list;
101
if self.selected_printer.is_none() && !self.printers.is_empty() {
103
self.apply_preferred_printer(AppConfig::load().last_printer_key.as_deref());
102
self.selected_printer = Some(0);
103
}
104
}
104
}
105
Err(e) => self.error = Some(format!("{e:?}")),
105
Err(e) => self.error = Some(format!("{e:?}")),
106
}
106
}
@@ -119,6 +119,51 @@ impl PrintDialog {119
self.start_printer_discovery();
119
self.start_printer_discovery();
120
}
120
}
121
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
122
pub fn apply_inputs_to_last_params(&mut self) {
167
pub fn apply_inputs_to_last_params(&mut self) {
123
self.last_params = self.param_inputs.clone();
168
self.last_params = self.param_inputs.clone();
124
}
169
}
@@ -184,7 +229,10 @@ impl PrintDialog {184
229
185
match transport_result {
230
match transport_result {
186
Ok(mut transport) => match print_bytes(transport.as_mut(), &bytes) {
231
Ok(mut transport) => match print_bytes(transport.as_mut(), &bytes) {
187
Ok(()) => PrintExecuteResult::Printed,
232
Ok(()) => {
233
self.remember_successful_printer();
234
PrintExecuteResult::Printed
235
}
188
Err(e) => {
236
Err(e) => {
189
self.error = Some(format!("{e:?}"));
237
self.error = Some(format!("{e:?}"));
190
PrintExecuteResult::StillOpen
238
PrintExecuteResult::StillOpen
@@ -312,3 +360,49 @@ pub enum PrintDialogAction {312
None,
360
None,
313
Print,
361
Print,
314
}
362
}
363
364
#[cfg(test)]
365
mod tests {
366
use super::*;
367
use posprint::print::PrinterTarget;
368
369
#[test]
370
fn prefers_last_connected_printer_over_first() {
371
let mut dialog = PrintDialog::default();
372
dialog.printers = vec![
373
PrinterDevice {
374
id: "a".into(),
375
display_name: "First".into(),
376
target: PrinterTarget::Serial("COM1".into()),
377
},
378
PrinterDevice {
379
id: "b".into(),
380
display_name: "Last".into(),
381
target: PrinterTarget::WinSpooler("POS".into()),
382
},
383
];
384
dialog.apply_preferred_printer(Some("winspool:POS"));
385
assert_eq!(dialog.selected_printer, Some(1));
386
assert!(!dialog.use_manual_port);
387
}
388
389
#[test]
390
fn falls_back_to_first_when_preferred_missing() {
391
let mut dialog = PrintDialog::default();
392
dialog.printers = vec![PrinterDevice {
393
id: "a".into(),
394
display_name: "Only".into(),
395
target: PrinterTarget::Serial("COM1".into()),
396
}];
397
dialog.apply_preferred_printer(Some("winspool:Gone"));
398
assert_eq!(dialog.selected_printer, Some(0));
399
}
400
401
#[test]
402
fn restores_manual_preference() {
403
let mut dialog = PrintDialog::default();
404
dialog.apply_preferred_printer(Some("manual:COM9"));
405
assert!(dialog.use_manual_port);
406
assert_eq!(dialog.manual_port, "COM9");
407
}
408
}