Add noconfirm URL option with trusted domains and Settings tab.
Co-authored-by: Cursor <cursoragent@cursor.com>
@@ -7,7 +7,7 @@ posprint is a **single Rust binary** using **egui** (eframe). No separate fronte
7
7
```
8
8
┌──────────────────────────────────────────────────┐
9
9
│ posprint (Rust + egui) │
10
│ - Design (editor + preview) / Help │
10
│ - Design / Help / Settings │
11
11
│ - DSL parse → AST → preview + ESC/POS │
12
12
│ - USB-direct / Win spooler / serial printing │
13
13
│ - `.pos` JSON load/save (serde) │
@@ -33,6 +33,7 @@ src/
33
33
├── raster.rs # Barcode / QR bitmaps
34
34
├── image_load.rs # Local + http(s) @image loading
35
35
├── protocol_url.rs # posprint:// encode/decode
36
├── config.rs # Trusted origins + default page width
36
37
├── editor_assist.rs # @ autocomplete, Insert snippets
37
38
├── help_view.rs # Markdown help renderer
38
39
├── io/mod.rs # PosFile, PosMetadata
@@ -71,9 +72,11 @@ ESC/POS generation is **in-tree** (`escpos.rs`), not the `escpos` crates.io pack
71
72
|------|--------|-------------|
72
73
| **Design** | `app.rs` | Editor + side preview |
73
74
| **Help** | `help_view.rs` | `docs/HELP.md` via `include_str!` |
75
| **Settings** | `app.rs` | Default page width; trusted `noconfirm` origins |
74
76
| Toolbar | `app.rs` | New, Open, Save, Save As, Insert, Print |
75
| Settings | `app.rs` | Page width (mm), preview zoom |
77
| Document page width / zoom | `app.rs` | Per-document width (mm), preview zoom |
76
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` |
77
80
78
81
While the print dialog is open, the main UI is disabled and editor autocomplete does not steal focus.
79
82
@@ -152,6 +155,7 @@ Legacy JSON fields `preview_mode` and `cut_after_print` are ignored if present.
152
155
|------|---------|
153
156
| Template + metadata | `.pos` file |
154
157
| Last parameter values | In-memory (`print_dialog.last_params`) |
158
| Default page width / trusted origins | `config.rs` → platform config JSON |
155
159
| Recent files / selected printer | Not persisted |
156
160
157
161
---
@@ -7,7 +7,7 @@ posprint is a **single Rust binary** using **egui** (eframe). No separate fronte7
```7
```8
┌──────────────────────────────────────────────────┐8
┌──────────────────────────────────────────────────┐9
│ posprint (Rust + egui) │9
│ posprint (Rust + egui) │10
│ - Design (editor + preview) / Help │10
│ - Design / Help / Settings │11
│ - DSL parse → AST → preview + ESC/POS │11
│ - DSL parse → AST → preview + ESC/POS │12
│ - USB-direct / Win spooler / serial printing │12
│ - USB-direct / Win spooler / serial printing │13
│ - `.pos` JSON load/save (serde) │13
│ - `.pos` JSON load/save (serde) │@@ -33,6 +33,7 @@ src/33
├── raster.rs # Barcode / QR bitmaps33
├── raster.rs # Barcode / QR bitmaps34
├── image_load.rs # Local + http(s) @image loading34
├── image_load.rs # Local + http(s) @image loading35
├── protocol_url.rs # posprint:// encode/decode35
├── protocol_url.rs # posprint:// encode/decode36
├── config.rs # Trusted origins + default page width36
├── editor_assist.rs # @ autocomplete, Insert snippets37
├── editor_assist.rs # @ autocomplete, Insert snippets37
├── help_view.rs # Markdown help renderer38
├── help_view.rs # Markdown help renderer38
├── io/mod.rs # PosFile, PosMetadata39
├── io/mod.rs # PosFile, PosMetadata@@ -71,9 +72,11 @@ ESC/POS generation is **in-tree** (`escpos.rs`), not the `escpos` crates.io pack71
|------|--------|-------------|72
|------|--------|-------------|72
| **Design** | `app.rs` | Editor + side preview |73
| **Design** | `app.rs` | Editor + side preview |73
| **Help** | `help_view.rs` | `docs/HELP.md` via `include_str!` |74
| **Help** | `help_view.rs` | `docs/HELP.md` via `include_str!` |75
| **Settings** | `app.rs` | Default page width; trusted `noconfirm` origins |74
| Toolbar | `app.rs` | New, Open, Save, Save As, Insert, Print |76
| Toolbar | `app.rs` | New, Open, Save, Save As, Insert, Print |75
| Settings | `app.rs` | Page width (mm), preview zoom |77
| Document page width / zoom | `app.rs` | Per-document width (mm), preview zoom |76
| 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` |77
80
78
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.79
82
@@ -152,6 +155,7 @@ Legacy JSON fields `preview_mode` and `cut_after_print` are ignored if present.152
|------|---------|155
|------|---------|153
| Template + metadata | `.pos` file |156
| Template + metadata | `.pos` file |154
| 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 |155
| Recent files / selected printer | Not persisted |159
| Recent files / selected printer | Not persisted |156
160
157
---161
---@@ -10,6 +10,7 @@ Built-in reference for the template editor and POS markup language.
10
10
|-----|---------|
11
11
| **Design** | Side-by-side template editor and live preview |
12
12
| **Help** | This documentation |
13
| **Settings** | Default page width for new documents; trusted sites for `noconfirm` |
13
14
14
15
## Toolbar actions
15
16
@@ -308,7 +309,7 @@ Websites can open the print dialog with an embedded template:
308
309
posprint://print?v=1&d=…
309
310
```
310
311
311
Encoding helpers live in [`lib/`](../lib/). Full guide: [POSPRINT-URL.md](POSPRINT-URL.md).
312
Add `&noconfirm=1&origin=shop.example.com` to print immediately after the user trusts that domain once (see **Settings → Trusted sites**). Encoding helpers live in [`lib/`](../lib/). Full guide: [POSPRINT-URL.md](POSPRINT-URL.md).
312
313
313
314
`@image` may use `https://…` or `http://…` (downloaded when preview/print needs the image).
314
315
@@ -10,6 +10,7 @@ Built-in reference for the template editor and POS markup language.10
|-----|---------|10
|-----|---------|11
| **Design** | Side-by-side template editor and live preview |11
| **Design** | Side-by-side template editor and live preview |12
| **Help** | This documentation |12
| **Help** | This documentation |13
| **Settings** | Default page width for new documents; trusted sites for `noconfirm` |13
14
14
## Toolbar actions15
## Toolbar actions15
16
@@ -308,7 +309,7 @@ Websites can open the print dialog with an embedded template:308
posprint://print?v=1&d=…309
posprint://print?v=1&d=…309
```310
```310
311
311
Encoding helpers live in [`lib/`](../lib/). Full guide: [POSPRINT-URL.md](POSPRINT-URL.md).312
Add `&noconfirm=1&origin=shop.example.com` to print immediately after the user trusts that domain once (see **Settings → Trusted sites**). Encoding helpers live in [`lib/`](../lib/). Full guide: [POSPRINT-URL.md](POSPRINT-URL.md).312
313
313
`@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).314
315
@@ -12,17 +12,36 @@ Full reference: create URLs from PHP, Node.js, or browser JavaScript using the h
12
12
posprint://print?v=1&d=<BASE64URL(raw_deflate(utf8(.pos JSON)))>
13
13
```
14
14
15
Optional auto-print:
16
17
```
18
posprint://print?v=1&d=…&noconfirm=1&origin=shop.example.com
19
```
20
15
21
| Part | Meaning |
16
22
|------|---------|
17
23
| `posprint://` | Custom protocol (registered on install / first run) |
18
24
| `print` | Open the print-only dialog (same UX as `posprint --print`) |
19
25
| `v=1` | URL payload version |
20
26
| `d=` | Compressed `.pos` file (JSON with `version`, `metadata`, `body`) |
27
| `noconfirm=1` | Start printing immediately (after domain trust; see below) |
28
| `origin=` | Hostname of the calling site (required with `noconfirm`) |
21
29
22
**Parameters are not in the URL.** The user fills `${Name}` / `$[Name]` in the dialog.
30
**Template parameters are not in the URL.** With a normal link the user fills `${Name}` / `$[Name]` in the dialog. Prefer templates without unresolved parameters when using `noconfirm`.
23
31
24
32
**Images:** keep logos out of the URL. Use `@image https://…` (or `http://…`) in the template body; posprint downloads them when needed.
25
33
34
### Auto-print (`noconfirm`) and trusted domains
35
36
The OS protocol handler only receives the URL string — not the browser Referer. Callers that want silent print must pass **`origin=<hostname>`** (e.g. `shop.example.com` or `https://shop.example.com/checkout`).
37
38
| First visit from that origin | Later visits |
39
|------------------------------|--------------|
40
| posprint shows **Trust this site?** | If trusted, prints without asking |
41
| **Trust and print** stores the hostname and continues | Revoke under **Settings → Trusted sites** |
42
43
Without `origin`, `noconfirm=1` is rejected with an error. Without `noconfirm`, behaviour is unchanged (interactive print dialog).
44
26
45
---
27
46
28
47
## Size limits
@@ -68,6 +87,11 @@ $url = posprint_url([
68
87
'metadata' => ['page_width_mm' => 53, 'chars_per_line' => 32],
69
88
'body' => "@barcode RASTER CODE128 \${data}\nHello\n@cut\n",
70
89
]);
90
// Auto-print (after the user trusts this site once):
91
$auto = posprint_url($pos, [
92
'noconfirm' => true,
93
'origin' => 'https://shop.example.com',
94
]);
71
95
// <a href="<?= htmlspecialchars($url) ?>">Print</a>
72
96
```
73
97
@@ -81,6 +105,11 @@ const url = posprintUrl({
81
105
metadata: { page_width_mm: 53, chars_per_line: 32 },
82
106
body: '@barcode RASTER CODE128 ${data}\nHello\n@cut\n',
83
107
});
108
109
const auto = posprintUrl(pos, {
110
noconfirm: true,
111
origin: location.hostname, // or 'shop.example.com'
112
});
84
113
```
85
114
86
115
#### Browser
@@ -93,7 +122,11 @@ const url = posprintUrl({
93
122
metadata: { page_width_mm: 53 },
94
123
body: '@barcode RASTER CODE128 ${data}\nHello\n@cut\n',
95
124
});
96
location.href = url;
125
const auto = await posprintUrl(pos, {
126
noconfirm: true,
127
origin: location.origin,
128
});
129
location.href = auto;
97
130
</script>
98
131
```
99
132
@@ -12,17 +12,36 @@ Full reference: create URLs from PHP, Node.js, or browser JavaScript using the h12
posprint://print?v=1&d=<BASE64URL(raw_deflate(utf8(.pos JSON)))>12
posprint://print?v=1&d=<BASE64URL(raw_deflate(utf8(.pos JSON)))>13
```13
```14
14
15
Optional auto-print:16
17
```18
posprint://print?v=1&d=…&noconfirm=1&origin=shop.example.com19
```20
15
| Part | Meaning |21
| Part | Meaning |16
|------|---------|22
|------|---------|17
| `posprint://` | Custom protocol (registered on install / first run) |23
| `posprint://` | Custom protocol (registered on install / first run) |18
| `print` | Open the print-only dialog (same UX as `posprint --print`) |24
| `print` | Open the print-only dialog (same UX as `posprint --print`) |19
| `v=1` | URL payload version |25
| `v=1` | URL payload version |20
| `d=` | Compressed `.pos` file (JSON with `version`, `metadata`, `body`) |26
| `d=` | Compressed `.pos` file (JSON with `version`, `metadata`, `body`) |27
| `noconfirm=1` | Start printing immediately (after domain trust; see below) |28
| `origin=` | Hostname of the calling site (required with `noconfirm`) |21
29
22
**Parameters are not in the URL.** The user fills `${Name}` / `$[Name]` in the dialog.30
**Template parameters are not in the URL.** With a normal link the user fills `${Name}` / `$[Name]` in the dialog. Prefer templates without unresolved parameters when using `noconfirm`.23
31
24
**Images:** keep logos out of the URL. Use `@image https://…` (or `http://…`) in the template body; posprint downloads them when needed.32
**Images:** keep logos out of the URL. Use `@image https://…` (or `http://…`) in the template body; posprint downloads them when needed.25
33
34
### Auto-print (`noconfirm`) and trusted domains35
36
The OS protocol handler only receives the URL string — not the browser Referer. Callers that want silent print must pass **`origin=<hostname>`** (e.g. `shop.example.com` or `https://shop.example.com/checkout`).37
38
| First visit from that origin | Later visits |39
|------------------------------|--------------|40
| posprint shows **Trust this site?** | If trusted, prints without asking |41
| **Trust and print** stores the hostname and continues | Revoke under **Settings → Trusted sites** |42
43
Without `origin`, `noconfirm=1` is rejected with an error. Without `noconfirm`, behaviour is unchanged (interactive print dialog).44
26
---45
---27
46
28
## Size limits47
## Size limits@@ -68,6 +87,11 @@ $url = posprint_url([68
'metadata' => ['page_width_mm' => 53, 'chars_per_line' => 32],87
'metadata' => ['page_width_mm' => 53, 'chars_per_line' => 32],69
'body' => "@barcode RASTER CODE128 \${data}\nHello\n@cut\n",88
'body' => "@barcode RASTER CODE128 \${data}\nHello\n@cut\n",70
]);89
]);90
// Auto-print (after the user trusts this site once):91
$auto = posprint_url($pos, [92
'noconfirm' => true,93
'origin' => 'https://shop.example.com',94
]);71
// <a href="<?= htmlspecialchars($url) ?>">Print</a>95
// <a href="<?= htmlspecialchars($url) ?>">Print</a>72
```96
```73
97
@@ -81,6 +105,11 @@ const url = posprintUrl({81
metadata: { page_width_mm: 53, chars_per_line: 32 },105
metadata: { page_width_mm: 53, chars_per_line: 32 },82
body: '@barcode RASTER CODE128 ${data}\nHello\n@cut\n',106
body: '@barcode RASTER CODE128 ${data}\nHello\n@cut\n',83
});107
});108
109
const auto = posprintUrl(pos, {110
noconfirm: true,111
origin: location.hostname, // or 'shop.example.com'112
});84
```113
```85
114
86
#### Browser115
#### Browser@@ -93,7 +122,11 @@ const url = posprintUrl({93
metadata: { page_width_mm: 53 },122
metadata: { page_width_mm: 53 },94
body: '@barcode RASTER CODE128 ${data}\nHello\n@cut\n',123
body: '@barcode RASTER CODE128 ${data}\nHello\n@cut\n',95
});124
});96
location.href = url;125
const auto = await posprintUrl(pos, {126
noconfirm: true,127
origin: location.origin,128
});129
location.href = auto;97
</script>130
</script>98
```131
```99
132
@@ -31,6 +31,8 @@ Build the document in JavaScript and open the link:
31
31
},
32
32
body: '@barcode RASTER CODE128 ${data}\nHello\n@cut\n',
33
33
});
34
// Silent print after the user trusts this origin once:
35
// const url = await posprintUrl(pos, { noconfirm: true, origin: location.hostname });
34
36
window.location.href = url;
35
37
});
36
38
</script>
@@ -31,6 +31,8 @@ Build the document in JavaScript and open the link:31
},31
},32
body: '@barcode RASTER CODE128 ${data}\nHello\n@cut\n',32
body: '@barcode RASTER CODE128 ${data}\nHello\n@cut\n',33
});33
});34
// Silent print after the user trusts this origin once:35
// const url = await posprintUrl(pos, { noconfirm: true, origin: location.hostname });34
window.location.href = url;36
window.location.href = url;35
});37
});36
</script>38
</script>@@ -5,9 +5,10 @@
5
5
* Requires CompressionStream('deflate-raw') (modern browsers).
6
6
*
7
7
* @param {object|string} pos
8
* @param {{ noconfirm?: boolean, origin?: string }} [options]
8
9
* @returns {Promise<string>}
9
10
*/
10
export async function posprintUrl(pos) {
11
export async function posprintUrl(pos, options = {}) {
11
12
const json = typeof pos === 'string' ? pos : JSON.stringify(pos);
12
13
if (typeof CompressionStream === 'undefined') {
13
14
throw new Error("CompressionStream('deflate-raw') is not available in this browser");
@@ -16,7 +17,30 @@ export async function posprintUrl(pos) {
16
17
const stream = new Blob([json]).stream().pipeThrough(new CompressionStream('deflate-raw'));
17
18
const buffer = await new Response(stream).arrayBuffer();
18
19
const b64 = bytesToBase64Url(new Uint8Array(buffer));
19
return `posprint://print?v=1&d=${b64}`;
20
let url = `posprint://print?v=1&d=${b64}`;
21
if (options.noconfirm) {
22
url += '&noconfirm=1';
23
}
24
if (options.origin) {
25
const host = normalizeOrigin(options.origin);
26
if (host) {
27
url += `&origin=${encodeURIComponent(host)}`;
28
}
29
}
30
return url;
31
}
32
33
function normalizeOrigin(raw) {
34
const s = String(raw).trim();
35
if (!s) return null;
36
try {
37
if (/^https?:\/\//i.test(s)) {
38
return new URL(s).hostname.toLowerCase();
39
}
40
} catch (_) {
41
/* fall through */
42
}
43
return s.split('/')[0].split(':')[0].toLowerCase() || null;
20
44
}
21
45
22
46
function bytesToBase64Url(bytes) {
@@ -5,9 +5,10 @@5
* Requires CompressionStream('deflate-raw') (modern browsers).
5
* Requires CompressionStream('deflate-raw') (modern browsers).
6
*
6
*
7
* @param {object|string} pos
7
* @param {object|string} pos
8
* @param {{ noconfirm?: boolean, origin?: string }} [options]
8
* @returns {Promise<string>}
9
* @returns {Promise<string>}
9
*/
10
*/
10
export async function posprintUrl(pos) {
11
export async function posprintUrl(pos, options = {}) {
11
const json = typeof pos === 'string' ? pos : JSON.stringify(pos);
12
const json = typeof pos === 'string' ? pos : JSON.stringify(pos);
12
if (typeof CompressionStream === 'undefined') {
13
if (typeof CompressionStream === 'undefined') {
13
throw new Error("CompressionStream('deflate-raw') is not available in this browser");
14
throw new Error("CompressionStream('deflate-raw') is not available in this browser");
@@ -16,7 +17,30 @@ export async function posprintUrl(pos) {16
const stream = new Blob([json]).stream().pipeThrough(new CompressionStream('deflate-raw'));
17
const stream = new Blob([json]).stream().pipeThrough(new CompressionStream('deflate-raw'));
17
const buffer = await new Response(stream).arrayBuffer();
18
const buffer = await new Response(stream).arrayBuffer();
18
const b64 = bytesToBase64Url(new Uint8Array(buffer));
19
const b64 = bytesToBase64Url(new Uint8Array(buffer));
19
return `posprint://print?v=1&d=${b64}`;
20
let url = `posprint://print?v=1&d=${b64}`;
21
if (options.noconfirm) {
22
url += '&noconfirm=1';
23
}
24
if (options.origin) {
25
const host = normalizeOrigin(options.origin);
26
if (host) {
27
url += `&origin=${encodeURIComponent(host)}`;
28
}
29
}
30
return url;
31
}
32
33
function normalizeOrigin(raw) {
34
const s = String(raw).trim();
35
if (!s) return null;
36
try {
37
if (/^https?:\/\//i.test(s)) {
38
return new URL(s).hostname.toLowerCase();
39
}
40
} catch (_) {
41
/* fall through */
42
}
43
return s.split('/')[0].split(':')[0].toLowerCase() || null;
20
}
44
}
21
45
22
function bytesToBase64Url(bytes) {
46
function bytesToBase64Url(bytes) {
@@ -8,13 +8,37 @@ const zlib = require('zlib');
8
8
* Encoding: UTF-8 JSON → raw deflate → base64url (no padding).
9
9
*
10
10
* @param {object|string} pos
11
* @param {{ noconfirm?: boolean, origin?: string }} [options]
11
12
* @returns {string}
12
13
*/
13
function posprintUrl(pos) {
14
function posprintUrl(pos, options = {}) {
14
15
const json = typeof pos === 'string' ? pos : JSON.stringify(pos);
15
16
const compressed = zlib.deflateRawSync(Buffer.from(json, 'utf8'), { level: 9 });
16
17
const b64 = compressed.toString('base64url');
17
return `posprint://print?v=1&d=${b64}`;
18
let url = `posprint://print?v=1&d=${b64}`;
19
if (options.noconfirm) {
20
url += '&noconfirm=1';
21
}
22
if (options.origin) {
23
const host = normalizeOrigin(options.origin);
24
if (host) {
25
url += `&origin=${encodeURIComponent(host)}`;
26
}
27
}
28
return url;
29
}
30
31
function normalizeOrigin(raw) {
32
const s = String(raw).trim();
33
if (!s) return null;
34
try {
35
if (/^https?:\/\//i.test(s)) {
36
return new URL(s).hostname.toLowerCase();
37
}
38
} catch (_) {
39
/* fall through */
40
}
41
return s.split('/')[0].split(':')[0].toLowerCase() || null;
18
42
}
19
43
20
44
module.exports = { posprintUrl };
@@ -8,13 +8,37 @@ const zlib = require('zlib');8
* Encoding: UTF-8 JSON → raw deflate → base64url (no padding).
8
* Encoding: UTF-8 JSON → raw deflate → base64url (no padding).
9
*
9
*
10
* @param {object|string} pos
10
* @param {object|string} pos
11
* @param {{ noconfirm?: boolean, origin?: string }} [options]
11
* @returns {string}
12
* @returns {string}
12
*/
13
*/
13
function posprintUrl(pos) {
14
function posprintUrl(pos, options = {}) {
14
const json = typeof pos === 'string' ? pos : JSON.stringify(pos);
15
const json = typeof pos === 'string' ? pos : JSON.stringify(pos);
15
const compressed = zlib.deflateRawSync(Buffer.from(json, 'utf8'), { level: 9 });
16
const compressed = zlib.deflateRawSync(Buffer.from(json, 'utf8'), { level: 9 });
16
const b64 = compressed.toString('base64url');
17
const b64 = compressed.toString('base64url');
17
return `posprint://print?v=1&d=${b64}`;
18
let url = `posprint://print?v=1&d=${b64}`;
19
if (options.noconfirm) {
20
url += '&noconfirm=1';
21
}
22
if (options.origin) {
23
const host = normalizeOrigin(options.origin);
24
if (host) {
25
url += `&origin=${encodeURIComponent(host)}`;
26
}
27
}
28
return url;
29
}
30
31
function normalizeOrigin(raw) {
32
const s = String(raw).trim();
33
if (!s) return null;
34
try {
35
if (/^https?:\/\//i.test(s)) {
36
return new URL(s).hostname.toLowerCase();
37
}
38
} catch (_) {
39
/* fall through */
40
}
41
return s.split('/')[0].split(':')[0].toLowerCase() || null;
18
}
42
}
19
43
20
module.exports = { posprintUrl };
44
module.exports = { posprintUrl };
@@ -5,10 +5,11 @@
5
5
* Encoding: UTF-8 JSON → raw deflate (gzdeflate) → base64url (no padding).
6
6
*
7
7
* @param array|string $pos PosFile as associative array or JSON string
8
* @param array{noconfirm?: bool, origin?: string} $options Optional URL flags
8
9
* @return string posprint://print?v=1&d=…
9
10
* @throws InvalidArgumentException
10
11
*/
11
function posprint_url($pos): string
12
function posprint_url($pos, array $options = []): string
12
13
{
13
14
if (is_array($pos)) {
14
15
$json = json_encode($pos, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
@@ -27,5 +28,36 @@ function posprint_url($pos): string
27
28
}
28
29
29
30
$b64 = rtrim(strtr(base64_encode($compressed), '+/', '-_'), '=');
30
return 'posprint://print?v=1&d=' . $b64;
31
$url = 'posprint://print?v=1&d=' . $b64;
32
33
if (!empty($options['noconfirm'])) {
34
$url .= '&noconfirm=1';
35
}
36
if (!empty($options['origin'])) {
37
$host = posprint_normalize_origin((string) $options['origin']);
38
if ($host !== null) {
39
$url .= '&origin=' . rawurlencode($host);
40
}
41
}
42
43
return $url;
44
}
45
46
/**
47
* @return string|null lowercase hostname
48
*/
49
function posprint_normalize_origin(string $raw): ?string
50
{
51
$s = trim($raw);
52
if ($s === '') {
53
return null;
54
}
55
if (preg_match('#^https?://#i', $s) === 1) {
56
$host = parse_url($s, PHP_URL_HOST);
57
return is_string($host) && $host !== '' ? strtolower($host) : null;
58
}
59
$host = explode('/', $s, 2)[0];
60
$host = explode(':', $host, 2)[0];
61
$host = trim($host);
62
return $host !== '' ? strtolower($host) : null;
31
63
}
@@ -5,10 +5,11 @@5
* Encoding: UTF-8 JSON → raw deflate (gzdeflate) → base64url (no padding).
5
* Encoding: UTF-8 JSON → raw deflate (gzdeflate) → base64url (no padding).
6
*
6
*
7
* @param array|string $pos PosFile as associative array or JSON string
7
* @param array|string $pos PosFile as associative array or JSON string
8
* @param array{noconfirm?: bool, origin?: string} $options Optional URL flags
8
* @return string posprint://print?v=1&d=…
9
* @return string posprint://print?v=1&d=…
9
* @throws InvalidArgumentException
10
* @throws InvalidArgumentException
10
*/
11
*/
11
function posprint_url($pos): string
12
function posprint_url($pos, array $options = []): string
12
{
13
{
13
if (is_array($pos)) {
14
if (is_array($pos)) {
14
$json = json_encode($pos, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
15
$json = json_encode($pos, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
@@ -27,5 +28,36 @@ function posprint_url($pos): string27
}
28
}
28
29
29
$b64 = rtrim(strtr(base64_encode($compressed), '+/', '-_'), '=');
30
$b64 = rtrim(strtr(base64_encode($compressed), '+/', '-_'), '=');
30
return 'posprint://print?v=1&d=' . $b64;
31
$url = 'posprint://print?v=1&d=' . $b64;
32
33
if (!empty($options['noconfirm'])) {
34
$url .= '&noconfirm=1';
35
}
36
if (!empty($options['origin'])) {
37
$host = posprint_normalize_origin((string) $options['origin']);
38
if ($host !== null) {
39
$url .= '&origin=' . rawurlencode($host);
40
}
41
}
42
43
return $url;
44
}
45
46
/**
47
* @return string|null lowercase hostname
48
*/
49
function posprint_normalize_origin(string $raw): ?string
50
{
51
$s = trim($raw);
52
if ($s === '') {
53
return null;
54
}
55
if (preg_match('#^https?://#i', $s) === 1) {
56
$host = parse_url($s, PHP_URL_HOST);
57
return is_string($host) && $host !== '' ? strtolower($host) : null;
58
}
59
$host = explode('/', $s, 2)[0];
60
$host = explode(':', $host, 2)[0];
61
$host = trim($host);
62
return $host !== '' ? strtolower($host) : null;
31
}
63
}
@@ -2,6 +2,7 @@ use std::path::PathBuf;
2
2
3
3
use eframe::egui;
4
4
5
use posprint::config::AppConfig;
5
6
use posprint::dsl::{self, parse};
6
7
use posprint::editor_assist::{
7
8
apply_directive_completion, at_directive_prefix, barcode_insert_options, char_index_to_byte,
@@ -20,6 +21,7 @@ use crate::print_dialog::{PrintDialog, PrintDialogAction, PrintExecuteResult};
20
21
enum ViewMode {
21
22
Design,
22
23
Help,
24
Settings,
23
25
}
24
26
25
27
pub struct PosPrintApp {
@@ -35,14 +37,19 @@ pub struct PosPrintApp {
35
37
editor_cursor: usize,
36
38
undo: TextUndo,
37
39
preview_zoom: f32,
40
config: AppConfig,
41
settings_status: Option<String>,
38
42
}
39
43
40
44
impl Default for PosPrintApp {
41
45
fn default() -> Self {
46
let config = AppConfig::load();
47
let mut metadata = PosMetadata::default();
48
metadata.page_width_mm = config.default_page_width_mm;
42
49
Self {
43
50
view_mode: ViewMode::Design,
44
51
body: default_template(),
45
metadata: PosMetadata::default(),
52
metadata,
46
53
file_path: None,
47
54
dirty: false,
48
55
parse_error: None,
@@ -52,6 +59,8 @@ impl Default for PosPrintApp {
52
59
editor_cursor: 0,
53
60
undo: TextUndo::default(),
54
61
preview_zoom: 1.0,
62
config,
63
settings_status: None,
55
64
}
56
65
}
57
66
}
@@ -105,6 +114,74 @@ impl PosPrintApp {
105
114
*self = Self::default();
106
115
}
107
116
117
fn show_settings(&mut self, ui: &mut egui::Ui) {
118
ui.heading("Settings");
119
ui.separator();
120
121
ui.heading("New documents");
122
ui.horizontal(|ui| {
123
ui.label("Default page width (mm):");
124
let mut width = self.config.default_page_width_mm;
125
if ui
126
.add(egui::DragValue::new(&mut width).range(40.0..=120.0).speed(1.0))
127
.changed()
128
{
129
self.config.default_page_width_mm = width;
130
self.settings_status = None;
131
}
132
});
133
ui.label("Applies when you choose New. The current document width is unchanged.");
134
135
ui.add_space(16.0);
136
ui.heading("Trusted sites (noconfirm)");
137
ui.label(
138
"Sites listed here may use posprint://…&noconfirm=1&origin=… without asking again.",
139
);
140
141
if self.config.trusted_origins.is_empty() {
142
ui.label("No trusted sites yet.");
143
} else {
144
let origins = self.config.trusted_origins.clone();
145
for origin in origins {
146
ui.horizontal(|ui| {
147
ui.label(&origin);
148
if ui.button("Revoke").clicked() {
149
self.config.revoke_origin(&origin);
150
match self.config.save() {
151
Ok(()) => {
152
self.settings_status =
153
Some(format!("Revoked trust for {origin}"))
154
}
155
Err(e) => {
156
self.settings_status = Some(format!("Save failed: {e}"))
157
}
158
}
159
}
160
});
161
}
162
if ui.button("Revoke all").clicked() {
163
self.config.trusted_origins.clear();
164
match self.config.save() {
165
Ok(()) => {
166
self.settings_status = Some("Cleared all trusted sites.".into())
167
}
168
Err(e) => self.settings_status = Some(format!("Save failed: {e}")),
169
}
170
}
171
}
172
173
ui.add_space(16.0);
174
if ui.button("Save settings").clicked() {
175
match self.config.save() {
176
Ok(()) => self.settings_status = Some("Settings saved.".into()),
177
Err(e) => self.settings_status = Some(format!("Save failed: {e}")),
178
}
179
}
180
if let Some(status) = &self.settings_status {
181
ui.label(status);
182
}
183
}
184
108
185
fn open_file_dialog(&mut self) {
109
186
if let Some(path) = rfd::FileDialog::new()
110
187
.add_filter("POS template", &["pos"])
@@ -342,6 +419,7 @@ impl eframe::App for PosPrintApp {
342
419
ui.horizontal(|ui| {
343
420
ui.selectable_value(&mut self.view_mode, ViewMode::Design, "Design");
344
421
ui.selectable_value(&mut self.view_mode, ViewMode::Help, "Help");
422
ui.selectable_value(&mut self.view_mode, ViewMode::Settings, "Settings");
345
423
if let Ok(doc) = parse(&self.body) {
346
424
if !dsl::document_ends_with_cut(&doc) {
347
425
ui.colored_label(
@@ -398,6 +476,13 @@ impl eframe::App for PosPrintApp {
398
476
});
399
477
});
400
478
}
479
ViewMode::Settings => {
480
egui::CentralPanel::default().show(ctx, |ui| {
481
ui.add_enabled_ui(main_enabled, |ui| {
482
self.show_settings(ui);
483
});
484
});
485
}
401
486
}
402
487
403
488
if self.show_print_dialog {
@@ -2,6 +2,7 @@ use std::path::PathBuf;2
2
3
use eframe::egui;
3
use eframe::egui;
4
4
5
use posprint::config::AppConfig;
5
use posprint::dsl::{self, parse};
6
use posprint::dsl::{self, parse};
6
use posprint::editor_assist::{
7
use posprint::editor_assist::{
7
apply_directive_completion, at_directive_prefix, barcode_insert_options, char_index_to_byte,
8
apply_directive_completion, at_directive_prefix, barcode_insert_options, char_index_to_byte,
@@ -20,6 +21,7 @@ use crate::print_dialog::{PrintDialog, PrintDialogAction, PrintExecuteResult};20
enum ViewMode {
21
enum ViewMode {
21
Design,
22
Design,
22
Help,
23
Help,
24
Settings,
23
}
25
}
24
26
25
pub struct PosPrintApp {
27
pub struct PosPrintApp {
@@ -35,14 +37,19 @@ pub struct PosPrintApp {35
editor_cursor: usize,
37
editor_cursor: usize,
36
undo: TextUndo,
38
undo: TextUndo,
37
preview_zoom: f32,
39
preview_zoom: f32,
40
config: AppConfig,
41
settings_status: Option<String>,
38
}
42
}
39
43
40
impl Default for PosPrintApp {
44
impl Default for PosPrintApp {
41
fn default() -> Self {
45
fn default() -> Self {
46
let config = AppConfig::load();
47
let mut metadata = PosMetadata::default();
48
metadata.page_width_mm = config.default_page_width_mm;
42
Self {
49
Self {
43
view_mode: ViewMode::Design,
50
view_mode: ViewMode::Design,
44
body: default_template(),
51
body: default_template(),
45
metadata: PosMetadata::default(),
52
metadata,
46
file_path: None,
53
file_path: None,
47
dirty: false,
54
dirty: false,
48
parse_error: None,
55
parse_error: None,
@@ -52,6 +59,8 @@ impl Default for PosPrintApp {52
editor_cursor: 0,
59
editor_cursor: 0,
53
undo: TextUndo::default(),
60
undo: TextUndo::default(),
54
preview_zoom: 1.0,
61
preview_zoom: 1.0,
62
config,
63
settings_status: None,
55
}
64
}
56
}
65
}
57
}
66
}
@@ -105,6 +114,74 @@ impl PosPrintApp {105
*self = Self::default();
114
*self = Self::default();
106
}
115
}
107
116
117
fn show_settings(&mut self, ui: &mut egui::Ui) {
118
ui.heading("Settings");
119
ui.separator();
120
121
ui.heading("New documents");
122
ui.horizontal(|ui| {
123
ui.label("Default page width (mm):");
124
let mut width = self.config.default_page_width_mm;
125
if ui
126
.add(egui::DragValue::new(&mut width).range(40.0..=120.0).speed(1.0))
127
.changed()
128
{
129
self.config.default_page_width_mm = width;
130
self.settings_status = None;
131
}
132
});
133
ui.label("Applies when you choose New. The current document width is unchanged.");
134
135
ui.add_space(16.0);
136
ui.heading("Trusted sites (noconfirm)");
137
ui.label(
138
"Sites listed here may use posprint://…&noconfirm=1&origin=… without asking again.",
139
);
140
141
if self.config.trusted_origins.is_empty() {
142
ui.label("No trusted sites yet.");
143
} else {
144
let origins = self.config.trusted_origins.clone();
145
for origin in origins {
146
ui.horizontal(|ui| {
147
ui.label(&origin);
148
if ui.button("Revoke").clicked() {
149
self.config.revoke_origin(&origin);
150
match self.config.save() {
151
Ok(()) => {
152
self.settings_status =
153
Some(format!("Revoked trust for {origin}"))
154
}
155
Err(e) => {
156
self.settings_status = Some(format!("Save failed: {e}"))
157
}
158
}
159
}
160
});
161
}
162
if ui.button("Revoke all").clicked() {
163
self.config.trusted_origins.clear();
164
match self.config.save() {
165
Ok(()) => {
166
self.settings_status = Some("Cleared all trusted sites.".into())
167
}
168
Err(e) => self.settings_status = Some(format!("Save failed: {e}")),
169
}
170
}
171
}
172
173
ui.add_space(16.0);
174
if ui.button("Save settings").clicked() {
175
match self.config.save() {
176
Ok(()) => self.settings_status = Some("Settings saved.".into()),
177
Err(e) => self.settings_status = Some(format!("Save failed: {e}")),
178
}
179
}
180
if let Some(status) = &self.settings_status {
181
ui.label(status);
182
}
183
}
184
108
fn open_file_dialog(&mut self) {
185
fn open_file_dialog(&mut self) {
109
if let Some(path) = rfd::FileDialog::new()
186
if let Some(path) = rfd::FileDialog::new()
110
.add_filter("POS template", &["pos"])
187
.add_filter("POS template", &["pos"])
@@ -342,6 +419,7 @@ impl eframe::App for PosPrintApp {342
ui.horizontal(|ui| {
419
ui.horizontal(|ui| {
343
ui.selectable_value(&mut self.view_mode, ViewMode::Design, "Design");
420
ui.selectable_value(&mut self.view_mode, ViewMode::Design, "Design");
344
ui.selectable_value(&mut self.view_mode, ViewMode::Help, "Help");
421
ui.selectable_value(&mut self.view_mode, ViewMode::Help, "Help");
422
ui.selectable_value(&mut self.view_mode, ViewMode::Settings, "Settings");
345
if let Ok(doc) = parse(&self.body) {
423
if let Ok(doc) = parse(&self.body) {
346
if !dsl::document_ends_with_cut(&doc) {
424
if !dsl::document_ends_with_cut(&doc) {
347
ui.colored_label(
425
ui.colored_label(
@@ -398,6 +476,13 @@ impl eframe::App for PosPrintApp {398
});
476
});
399
});
477
});
400
}
478
}
479
ViewMode::Settings => {
480
egui::CentralPanel::default().show(ctx, |ui| {
481
ui.add_enabled_ui(main_enabled, |ui| {
482
self.show_settings(ui);
483
});
484
});
485
}
401
}
486
}
402
487
403
if self.show_print_dialog {
488
if self.show_print_dialog {
@@ -0,0 +1,204 @@
1
//! Persisted app preferences (trusted URL origins, default page width).
2
3
use std::fs;
4
use std::path::PathBuf;
5
6
use serde::{Deserialize, Serialize};
7
8
const CONFIG_VERSION: u32 = 1;
9
10
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
11
pub struct AppConfig {
12
#[serde(default = "default_config_version")]
13
pub version: u32,
14
/// Default paper width for **New** documents (mm).
15
#[serde(default = "default_page_width_mm")]
16
pub default_page_width_mm: f32,
17
/// Hostnames allowed to use `noconfirm=1` without asking again.
18
#[serde(default)]
19
pub trusted_origins: Vec<String>,
20
}
21
22
fn default_config_version() -> u32 {
23
CONFIG_VERSION
24
}
25
26
fn default_page_width_mm() -> f32 {
27
80.0
28
}
29
30
impl Default for AppConfig {
31
fn default() -> Self {
32
Self {
33
version: CONFIG_VERSION,
34
default_page_width_mm: default_page_width_mm(),
35
trusted_origins: Vec::new(),
36
}
37
}
38
}
39
40
impl AppConfig {
41
pub fn load() -> Self {
42
Self::load_from_path(&config_path())
43
}
44
45
pub fn load_from_path(path: &std::path::Path) -> Self {
46
match fs::read_to_string(path) {
47
Ok(text) => match serde_json::from_str::<AppConfig>(&text) {
48
Ok(mut cfg) => {
49
cfg.normalize();
50
cfg
51
}
52
Err(_) => Self::default(),
53
},
54
Err(_) => Self::default(),
55
}
56
}
57
58
pub fn save(&self) -> Result<(), String> {
59
self.save_to_path(&config_path())
60
}
61
62
pub fn save_to_path(&self, path: &std::path::Path) -> Result<(), String> {
63
if let Some(parent) = path.parent() {
64
fs::create_dir_all(parent).map_err(|e| e.to_string())?;
65
}
66
let mut cfg = self.clone();
67
cfg.normalize();
68
let json = serde_json::to_string_pretty(&cfg).map_err(|e| e.to_string())?;
69
fs::write(path, json).map_err(|e| e.to_string())
70
}
71
72
pub fn is_trusted(&self, origin: &str) -> bool {
73
let Some(host) = normalize_origin(origin) else {
74
return false;
75
};
76
self.trusted_origins.iter().any(|o| o == &host)
77
}
78
79
pub fn trust_origin(&mut self, origin: &str) -> bool {
80
let Some(host) = normalize_origin(origin) else {
81
return false;
82
};
83
if !self.trusted_origins.iter().any(|o| o == &host) {
84
self.trusted_origins.push(host);
85
self.trusted_origins.sort();
86
}
87
true
88
}
89
90
pub fn revoke_origin(&mut self, origin: &str) {
91
let Some(host) = normalize_origin(origin) else {
92
return;
93
};
94
self.trusted_origins.retain(|o| o != &host);
95
}
96
97
fn normalize(&mut self) {
98
self.version = CONFIG_VERSION;
99
if !self.default_page_width_mm.is_finite() || self.default_page_width_mm < 40.0 {
100
self.default_page_width_mm = 40.0;
101
} else if self.default_page_width_mm > 120.0 {
102
self.default_page_width_mm = 120.0;
103
}
104
let mut hosts: Vec<String> = self
105
.trusted_origins
106
.iter()
107
.filter_map(|o| normalize_origin(o))
108
.collect();
109
hosts.sort();
110
hosts.dedup();
111
self.trusted_origins = hosts;
112
}
113
}
114
115
/// Config file path: `%APPDATA%/posprint/config.json` (Windows) or
116
/// `$XDG_CONFIG_HOME/posprint/config.json` / `~/.config/posprint/config.json` (Unix).
117
pub fn config_path() -> PathBuf {
118
#[cfg(windows)]
119
{
120
let base = std::env::var_os("APPDATA")
121
.map(PathBuf::from)
122
.unwrap_or_else(|| PathBuf::from("."));
123
base.join("posprint").join("config.json")
124
}
125
#[cfg(not(windows))]
126
{
127
let base = std::env::var_os("XDG_CONFIG_HOME")
128
.map(PathBuf::from)
129
.or_else(|| {
130
std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config"))
131
})
132
.unwrap_or_else(|| PathBuf::from("."));
133
base.join("posprint").join("config.json")
134
}
135
}
136
137
/// Normalize a caller-supplied origin to a lowercase hostname.
138
/// Accepts `example.com`, `https://example.com/path`, `http://localhost:3000`.
139
pub fn normalize_origin(raw: &str) -> Option<String> {
140
let s = raw.trim();
141
if s.is_empty() {
142
return None;
143
}
144
let without_scheme = s
145
.strip_prefix("https://")
146
.or_else(|| s.strip_prefix("http://"))
147
.or_else(|| s.strip_prefix("HTTPS://"))
148
.or_else(|| s.strip_prefix("HTTP://"))
149
.unwrap_or(s);
150
let host_port = without_scheme.split('/').next()?.trim();
151
if host_port.is_empty() {
152
return None;
153
}
154
// Drop port for trust matching (example.com:443 → example.com).
155
let host = host_port.split(':').next()?.trim();
156
if host.is_empty() {
157
return None;
158
}
159
Some(host.to_ascii_lowercase())
160
}
161
162
#[cfg(test)]
163
mod tests {
164
use super::*;
165
166
#[test]
167
fn normalize_strips_scheme_path_and_port() {
168
assert_eq!(
169
normalize_origin("https://Shop.Example.com/checkout").as_deref(),
170
Some("shop.example.com")
171
);
172
assert_eq!(
173
normalize_origin("http://localhost:5173/").as_deref(),
174
Some("localhost")
175
);
176
assert_eq!(normalize_origin("example.com").as_deref(), Some("example.com"));
177
assert_eq!(normalize_origin(" ").as_deref(), None);
178
}
179
180
#[test]
181
fn trust_and_revoke_roundtrip() {
182
let mut cfg = AppConfig::default();
183
assert!(!cfg.is_trusted("https://a.example"));
184
assert!(cfg.trust_origin("https://a.example/x"));
185
assert!(cfg.is_trusted("a.example"));
186
assert!(cfg.is_trusted("HTTPS://A.Example"));
187
cfg.revoke_origin("a.example");
188
assert!(!cfg.is_trusted("a.example"));
189
}
190
191
#[test]
192
fn save_load_roundtrip_in_temp_dir() {
193
let dir = tempfile::tempdir().unwrap();
194
let path = dir.path().join("posprint").join("config.json");
195
let mut cfg = AppConfig::default();
196
cfg.default_page_width_mm = 58.0;
197
cfg.trust_origin("pos.example");
198
cfg.save_to_path(&path).unwrap();
199
200
let loaded = AppConfig::load_from_path(&path);
201
assert_eq!(loaded.default_page_width_mm, 58.0);
202
assert!(loaded.is_trusted("pos.example"));
203
}
204
}
@@ -0,0 +1,204 @@1
//! Persisted app preferences (trusted URL origins, default page width).
2
3
use std::fs;
4
use std::path::PathBuf;
5
6
use serde::{Deserialize, Serialize};
7
8
const CONFIG_VERSION: u32 = 1;
9
10
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
11
pub struct AppConfig {
12
#[serde(default = "default_config_version")]
13
pub version: u32,
14
/// Default paper width for **New** documents (mm).
15
#[serde(default = "default_page_width_mm")]
16
pub default_page_width_mm: f32,
17
/// Hostnames allowed to use `noconfirm=1` without asking again.
18
#[serde(default)]
19
pub trusted_origins: Vec<String>,
20
}
21
22
fn default_config_version() -> u32 {
23
CONFIG_VERSION
24
}
25
26
fn default_page_width_mm() -> f32 {
27
80.0
28
}
29
30
impl Default for AppConfig {
31
fn default() -> Self {
32
Self {
33
version: CONFIG_VERSION,
34
default_page_width_mm: default_page_width_mm(),
35
trusted_origins: Vec::new(),
36
}
37
}
38
}
39
40
impl AppConfig {
41
pub fn load() -> Self {
42
Self::load_from_path(&config_path())
43
}
44
45
pub fn load_from_path(path: &std::path::Path) -> Self {
46
match fs::read_to_string(path) {
47
Ok(text) => match serde_json::from_str::<AppConfig>(&text) {
48
Ok(mut cfg) => {
49
cfg.normalize();
50
cfg
51
}
52
Err(_) => Self::default(),
53
},
54
Err(_) => Self::default(),
55
}
56
}
57
58
pub fn save(&self) -> Result<(), String> {
59
self.save_to_path(&config_path())
60
}
61
62
pub fn save_to_path(&self, path: &std::path::Path) -> Result<(), String> {
63
if let Some(parent) = path.parent() {
64
fs::create_dir_all(parent).map_err(|e| e.to_string())?;
65
}
66
let mut cfg = self.clone();
67
cfg.normalize();
68
let json = serde_json::to_string_pretty(&cfg).map_err(|e| e.to_string())?;
69
fs::write(path, json).map_err(|e| e.to_string())
70
}
71
72
pub fn is_trusted(&self, origin: &str) -> bool {
73
let Some(host) = normalize_origin(origin) else {
74
return false;
75
};
76
self.trusted_origins.iter().any(|o| o == &host)
77
}
78
79
pub fn trust_origin(&mut self, origin: &str) -> bool {
80
let Some(host) = normalize_origin(origin) else {
81
return false;
82
};
83
if !self.trusted_origins.iter().any(|o| o == &host) {
84
self.trusted_origins.push(host);
85
self.trusted_origins.sort();
86
}
87
true
88
}
89
90
pub fn revoke_origin(&mut self, origin: &str) {
91
let Some(host) = normalize_origin(origin) else {
92
return;
93
};
94
self.trusted_origins.retain(|o| o != &host);
95
}
96
97
fn normalize(&mut self) {
98
self.version = CONFIG_VERSION;
99
if !self.default_page_width_mm.is_finite() || self.default_page_width_mm < 40.0 {
100
self.default_page_width_mm = 40.0;
101
} else if self.default_page_width_mm > 120.0 {
102
self.default_page_width_mm = 120.0;
103
}
104
let mut hosts: Vec<String> = self
105
.trusted_origins
106
.iter()
107
.filter_map(|o| normalize_origin(o))
108
.collect();
109
hosts.sort();
110
hosts.dedup();
111
self.trusted_origins = hosts;
112
}
113
}
114
115
/// Config file path: `%APPDATA%/posprint/config.json` (Windows) or
116
/// `$XDG_CONFIG_HOME/posprint/config.json` / `~/.config/posprint/config.json` (Unix).
117
pub fn config_path() -> PathBuf {
118
#[cfg(windows)]
119
{
120
let base = std::env::var_os("APPDATA")
121
.map(PathBuf::from)
122
.unwrap_or_else(|| PathBuf::from("."));
123
base.join("posprint").join("config.json")
124
}
125
#[cfg(not(windows))]
126
{
127
let base = std::env::var_os("XDG_CONFIG_HOME")
128
.map(PathBuf::from)
129
.or_else(|| {
130
std::env::var_os("HOME").map(|h| PathBuf::from(h).join(".config"))
131
})
132
.unwrap_or_else(|| PathBuf::from("."));
133
base.join("posprint").join("config.json")
134
}
135
}
136
137
/// Normalize a caller-supplied origin to a lowercase hostname.
138
/// Accepts `example.com`, `https://example.com/path`, `http://localhost:3000`.
139
pub fn normalize_origin(raw: &str) -> Option<String> {
140
let s = raw.trim();
141
if s.is_empty() {
142
return None;
143
}
144
let without_scheme = s
145
.strip_prefix("https://")
146
.or_else(|| s.strip_prefix("http://"))
147
.or_else(|| s.strip_prefix("HTTPS://"))
148
.or_else(|| s.strip_prefix("HTTP://"))
149
.unwrap_or(s);
150
let host_port = without_scheme.split('/').next()?.trim();
151
if host_port.is_empty() {
152
return None;
153
}
154
// Drop port for trust matching (example.com:443 → example.com).
155
let host = host_port.split(':').next()?.trim();
156
if host.is_empty() {
157
return None;
158
}
159
Some(host.to_ascii_lowercase())
160
}
161
162
#[cfg(test)]
163
mod tests {
164
use super::*;
165
166
#[test]
167
fn normalize_strips_scheme_path_and_port() {
168
assert_eq!(
169
normalize_origin("https://Shop.Example.com/checkout").as_deref(),
170
Some("shop.example.com")
171
);
172
assert_eq!(
173
normalize_origin("http://localhost:5173/").as_deref(),
174
Some("localhost")
175
);
176
assert_eq!(normalize_origin("example.com").as_deref(), Some("example.com"));
177
assert_eq!(normalize_origin(" ").as_deref(), None);
178
}
179
180
#[test]
181
fn trust_and_revoke_roundtrip() {
182
let mut cfg = AppConfig::default();
183
assert!(!cfg.is_trusted("https://a.example"));
184
assert!(cfg.trust_origin("https://a.example/x"));
185
assert!(cfg.is_trusted("a.example"));
186
assert!(cfg.is_trusted("HTTPS://A.Example"));
187
cfg.revoke_origin("a.example");
188
assert!(!cfg.is_trusted("a.example"));
189
}
190
191
#[test]
192
fn save_load_roundtrip_in_temp_dir() {
193
let dir = tempfile::tempdir().unwrap();
194
let path = dir.path().join("posprint").join("config.json");
195
let mut cfg = AppConfig::default();
196
cfg.default_page_width_mm = 58.0;
197
cfg.trust_origin("pos.example");
198
cfg.save_to_path(&path).unwrap();
199
200
let loaded = AppConfig::load_from_path(&path);
201
assert_eq!(loaded.default_page_width_mm, 58.0);
202
assert!(loaded.is_trusted("pos.example"));
203
}
204
}
@@ -1,4 +1,5 @@
1
1
pub mod cli;
2
pub mod config;
2
3
pub mod datetime;
3
4
pub mod dsl;
4
5
pub mod editor_assist;
@@ -1,4 +1,5 @@1
pub mod cli;
1
pub mod cli;
2
pub mod config;
2
pub mod datetime;
3
pub mod datetime;
3
pub mod dsl;
4
pub mod dsl;
4
pub mod editor_assist;
5
pub mod editor_assist;
@@ -10,7 +10,6 @@ use std::sync::Arc;
10
10
11
11
use clap::Parser;
12
12
13
use posprint::io::PosFile;
14
13
use posprint::protocol_url::{self, is_posprint_url};
15
14
16
15
fn load_viewport_icon() -> Option<Arc<eframe::egui::IconData>> {
@@ -25,7 +24,7 @@ fn main() -> eframe::Result<()> {
25
24
// Protocol URLs must be handled before clap: browsers pass the full URL as argv.
26
25
if let Some(url) = std::env::args().nth(1).filter(|a| is_posprint_url(a)) {
27
26
return match protocol_url::parse_posprint_url(&url) {
28
Ok(file) => run_print_only_pos_file(file),
27
Ok(launch) => run_print_only_launch(launch),
29
28
Err(e) => run_print_only_error(format!("Invalid posprint:// URL: {e}")),
30
29
};
31
30
}
@@ -67,13 +66,8 @@ fn run_print_only_path(path: std::path::PathBuf) -> eframe::Result<()> {
67
66
run_print_only_app(print_only_app::PrintOnlyApp::new(path))
68
67
}
69
68
70
fn run_print_only_pos_file(file: PosFile) -> eframe::Result<()> {
71
let label = file
72
.metadata
73
.title
74
.clone()
75
.unwrap_or_else(|| "posprint://".into());
76
run_print_only_app(print_only_app::PrintOnlyApp::from_pos_file(file, label))
69
fn run_print_only_launch(launch: protocol_url::PosprintLaunch) -> eframe::Result<()> {
70
run_print_only_app(print_only_app::PrintOnlyApp::from_launch(launch))
77
71
}
78
72
79
73
fn run_print_only_error(message: String) -> eframe::Result<()> {
@@ -10,7 +10,6 @@ use std::sync::Arc;10
10
11
use clap::Parser;
11
use clap::Parser;
12
12
13
use posprint::io::PosFile;
14
use posprint::protocol_url::{self, is_posprint_url};
13
use posprint::protocol_url::{self, is_posprint_url};
15
14
16
fn load_viewport_icon() -> Option<Arc<eframe::egui::IconData>> {
15
fn load_viewport_icon() -> Option<Arc<eframe::egui::IconData>> {
@@ -25,7 +24,7 @@ fn main() -> eframe::Result<()> {25
// Protocol URLs must be handled before clap: browsers pass the full URL as argv.
24
// Protocol URLs must be handled before clap: browsers pass the full URL as argv.
26
if let Some(url) = std::env::args().nth(1).filter(|a| is_posprint_url(a)) {
25
if let Some(url) = std::env::args().nth(1).filter(|a| is_posprint_url(a)) {
27
return match protocol_url::parse_posprint_url(&url) {
26
return match protocol_url::parse_posprint_url(&url) {
28
Ok(file) => run_print_only_pos_file(file),
27
Ok(launch) => run_print_only_launch(launch),
29
Err(e) => run_print_only_error(format!("Invalid posprint:// URL: {e}")),
28
Err(e) => run_print_only_error(format!("Invalid posprint:// URL: {e}")),
30
};
29
};
31
}
30
}
@@ -67,13 +66,8 @@ fn run_print_only_path(path: std::path::PathBuf) -> eframe::Result<()> {67
run_print_only_app(print_only_app::PrintOnlyApp::new(path))
66
run_print_only_app(print_only_app::PrintOnlyApp::new(path))
68
}
67
}
69
68
70
fn run_print_only_pos_file(file: PosFile) -> eframe::Result<()> {
69
fn run_print_only_launch(launch: protocol_url::PosprintLaunch) -> eframe::Result<()> {
71
let label = file
70
run_print_only_app(print_only_app::PrintOnlyApp::from_launch(launch))
72
.metadata
73
.title
74
.clone()
75
.unwrap_or_else(|| "posprint://".into());
76
run_print_only_app(print_only_app::PrintOnlyApp::from_pos_file(file, label))
77
}
71
}
78
72
79
fn run_print_only_error(message: String) -> eframe::Result<()> {
73
fn run_print_only_error(message: String) -> eframe::Result<()> {
@@ -4,7 +4,9 @@ use std::path::PathBuf;
4
4
5
5
use eframe::egui;
6
6
7
use posprint::config::AppConfig;
7
8
use posprint::io::{PosFile, PosMetadata};
9
use posprint::protocol_url::PosprintLaunch;
8
10
9
11
use crate::preview_panel::show_preview_panel;
10
12
use crate::print_dialog::{PrintDialog, PrintDialogAction, PrintExecuteResult};
@@ -19,20 +21,17 @@ pub struct PrintOnlyApp {
19
21
preview_zoom: f32,
20
22
fatal_error: Option<String>,
21
23
exit_requested: bool,
24
/// Auto-print once printers are ready (after trust if needed).
25
auto_print: bool,
26
/// Pending first-time trust confirmation for this hostname.
27
pending_trust: Option<String>,
28
auto_print_attempted: bool,
22
29
}
23
30
24
31
impl PrintOnlyApp {
25
32
pub fn new(path: PathBuf) -> Self {
26
let mut app = Self {
27
body: String::new(),
28
metadata: PosMetadata::default(),
29
file_path: Some(path.clone()),
30
title_override: None,
31
dialog: PrintDialog::default(),
32
preview_zoom: 1.0,
33
fatal_error: None,
34
exit_requested: false,
35
};
33
let mut app = Self::blank();
34
app.file_path = Some(path.clone());
36
35
37
36
match PosFile::load_from_path(&path) {
38
37
Ok(file) => {
@@ -49,32 +48,67 @@ impl PrintOnlyApp {
49
48
}
50
49
51
50
pub fn from_pos_file(file: PosFile, source_label: impl Into<String>) -> Self {
52
let mut app = Self {
53
body: file.body,
54
metadata: file.metadata,
55
file_path: None,
56
title_override: Some(source_label.into()),
57
dialog: PrintDialog::default(),
58
preview_zoom: 1.0,
59
fatal_error: None,
60
exit_requested: false,
61
};
51
let mut app = Self::blank();
52
app.body = file.body;
53
app.metadata = file.metadata;
54
app.title_override = Some(source_label.into());
62
55
if let Err(e) = app.dialog.prepare(&app.body) {
63
56
app.fatal_error = Some(e);
64
57
}
65
58
app
66
59
}
67
60
61
pub fn from_launch(launch: PosprintLaunch) -> Self {
62
let label = launch
63
.file
64
.metadata
65
.title
66
.clone()
67
.unwrap_or_else(|| "posprint://".into());
68
let mut app = Self::from_pos_file(launch.file, label);
69
if !launch.noconfirm {
70
return app;
71
}
72
73
match launch.origin.as_deref() {
74
None => {
75
app.fatal_error = Some(
76
"noconfirm=1 requires origin=<hostname> so posprint can ask whether to trust that site."
77
.into(),
78
);
79
}
80
Some(origin) => {
81
let cfg = AppConfig::load();
82
if cfg.is_trusted(origin) {
83
app.auto_print = true;
84
} else {
85
app.pending_trust = Some(origin.to_string());
86
}
87
}
88
}
89
app
90
}
91
68
92
pub fn from_error(message: impl Into<String>) -> Self {
93
let mut app = Self::blank();
94
app.title_override = Some("posprint://".into());
95
app.fatal_error = Some(message.into());
96
app
97
}
98
99
fn blank() -> Self {
69
100
Self {
70
101
body: String::new(),
71
102
metadata: PosMetadata::default(),
72
103
file_path: None,
73
title_override: Some("posprint://".into()),
104
title_override: None,
74
105
dialog: PrintDialog::default(),
75
106
preview_zoom: 1.0,
76
fatal_error: Some(message.into()),
107
fatal_error: None,
77
108
exit_requested: false,
109
auto_print: false,
110
pending_trust: None,
111
auto_print_attempted: false,
78
112
}
79
113
}
80
114
@@ -94,6 +128,25 @@ impl PrintOnlyApp {
94
128
fn request_exit(&mut self) {
95
129
self.exit_requested = true;
96
130
}
131
132
fn try_auto_print(&mut self, ctx: &egui::Context) {
133
if !self.auto_print || self.auto_print_attempted || self.fatal_error.is_some() {
134
return;
135
}
136
if self.dialog.printers_loading {
137
ctx.request_repaint();
138
return;
139
}
140
self.auto_print_attempted = true;
141
if self
142
.dialog
143
.execute_print(&self.body, &self.metadata, self.file_path.as_ref())
144
== PrintExecuteResult::Printed
145
{
146
self.request_exit();
147
}
148
// On failure, keep the dialog open so the user can fix params/printer.
149
}
97
150
}
98
151
99
152
impl eframe::App for PrintOnlyApp {
@@ -106,6 +159,39 @@ impl eframe::App for PrintOnlyApp {
106
159
self.dialog.poll_printer_discovery(ctx);
107
160
ctx.send_viewport_cmd(egui::ViewportCommand::Title(self.title()));
108
161
162
if let Some(origin) = self.pending_trust.clone() {
163
egui::CentralPanel::default().show(ctx, |ui| {
164
ui.heading("Trust this site?");
165
ui.separator();
166
ui.label(format!(
167
"A page from “{origin}” wants to print without confirmation (noconfirm)."
168
));
169
ui.label(
170
"If you trust this site, posprint will allow future noconfirm prints from this domain without asking again.",
171
);
172
ui.add_space(12.0);
173
ui.horizontal(|ui| {
174
if ui.button("Trust and print").clicked() {
175
let mut cfg = AppConfig::load();
176
cfg.trust_origin(&origin);
177
if let Err(e) = cfg.save() {
178
self.fatal_error = Some(format!("Could not save trust setting: {e}"));
179
self.pending_trust = None;
180
} else {
181
self.pending_trust = None;
182
self.auto_print = true;
183
}
184
}
185
if ui.button("Cancel").clicked() {
186
self.request_exit();
187
}
188
});
189
ui.add_space(8.0);
190
ui.label("You can revoke trust later under Settings in the designer.");
191
});
192
return;
193
}
194
109
195
if let Some(err) = self.fatal_error.clone() {
110
196
egui::CentralPanel::default().show(ctx, |ui| {
111
197
ui.heading("Print");
@@ -118,6 +204,8 @@ impl eframe::App for PrintOnlyApp {
118
204
return;
119
205
}
120
206
207
self.try_auto_print(ctx);
208
121
209
let mut action = PrintDialogAction::None;
122
210
123
211
egui::CentralPanel::default().show(ctx, |ui| {
@@ -4,7 +4,9 @@ use std::path::PathBuf;4
4
5
use eframe::egui;
5
use eframe::egui;
6
6
7
use posprint::config::AppConfig;
7
use posprint::io::{PosFile, PosMetadata};
8
use posprint::io::{PosFile, PosMetadata};
9
use posprint::protocol_url::PosprintLaunch;
8
10
9
use crate::preview_panel::show_preview_panel;
11
use crate::preview_panel::show_preview_panel;
10
use crate::print_dialog::{PrintDialog, PrintDialogAction, PrintExecuteResult};
12
use crate::print_dialog::{PrintDialog, PrintDialogAction, PrintExecuteResult};
@@ -19,20 +21,17 @@ pub struct PrintOnlyApp {19
preview_zoom: f32,
21
preview_zoom: f32,
20
fatal_error: Option<String>,
22
fatal_error: Option<String>,
21
exit_requested: bool,
23
exit_requested: bool,
24
/// Auto-print once printers are ready (after trust if needed).
25
auto_print: bool,
26
/// Pending first-time trust confirmation for this hostname.
27
pending_trust: Option<String>,
28
auto_print_attempted: bool,
22
}
29
}
23
30
24
impl PrintOnlyApp {
31
impl PrintOnlyApp {
25
pub fn new(path: PathBuf) -> Self {
32
pub fn new(path: PathBuf) -> Self {
26
let mut app = Self {
33
let mut app = Self::blank();
27
body: String::new(),
34
app.file_path = Some(path.clone());
28
metadata: PosMetadata::default(),
29
file_path: Some(path.clone()),
30
title_override: None,
31
dialog: PrintDialog::default(),
32
preview_zoom: 1.0,
33
fatal_error: None,
34
exit_requested: false,
35
};
36
35
37
match PosFile::load_from_path(&path) {
36
match PosFile::load_from_path(&path) {
38
Ok(file) => {
37
Ok(file) => {
@@ -49,32 +48,67 @@ impl PrintOnlyApp {49
}
48
}
50
49
51
pub fn from_pos_file(file: PosFile, source_label: impl Into<String>) -> Self {
50
pub fn from_pos_file(file: PosFile, source_label: impl Into<String>) -> Self {
52
let mut app = Self {
51
let mut app = Self::blank();
53
body: file.body,
52
app.body = file.body;
54
metadata: file.metadata,
53
app.metadata = file.metadata;
55
file_path: None,
54
app.title_override = Some(source_label.into());
56
title_override: Some(source_label.into()),
57
dialog: PrintDialog::default(),
58
preview_zoom: 1.0,
59
fatal_error: None,
60
exit_requested: false,
61
};
62
if let Err(e) = app.dialog.prepare(&app.body) {
55
if let Err(e) = app.dialog.prepare(&app.body) {
63
app.fatal_error = Some(e);
56
app.fatal_error = Some(e);
64
}
57
}
65
app
58
app
66
}
59
}
67
60
61
pub fn from_launch(launch: PosprintLaunch) -> Self {
62
let label = launch
63
.file
64
.metadata
65
.title
66
.clone()
67
.unwrap_or_else(|| "posprint://".into());
68
let mut app = Self::from_pos_file(launch.file, label);
69
if !launch.noconfirm {
70
return app;
71
}
72
73
match launch.origin.as_deref() {
74
None => {
75
app.fatal_error = Some(
76
"noconfirm=1 requires origin=<hostname> so posprint can ask whether to trust that site."
77
.into(),
78
);
79
}
80
Some(origin) => {
81
let cfg = AppConfig::load();
82
if cfg.is_trusted(origin) {
83
app.auto_print = true;
84
} else {
85
app.pending_trust = Some(origin.to_string());
86
}
87
}
88
}
89
app
90
}
91
68
pub fn from_error(message: impl Into<String>) -> Self {
92
pub fn from_error(message: impl Into<String>) -> Self {
93
let mut app = Self::blank();
94
app.title_override = Some("posprint://".into());
95
app.fatal_error = Some(message.into());
96
app
97
}
98
99
fn blank() -> Self {
69
Self {
100
Self {
70
body: String::new(),
101
body: String::new(),
71
metadata: PosMetadata::default(),
102
metadata: PosMetadata::default(),
72
file_path: None,
103
file_path: None,
73
title_override: Some("posprint://".into()),
104
title_override: None,
74
dialog: PrintDialog::default(),
105
dialog: PrintDialog::default(),
75
preview_zoom: 1.0,
106
preview_zoom: 1.0,
76
fatal_error: Some(message.into()),
107
fatal_error: None,
77
exit_requested: false,
108
exit_requested: false,
109
auto_print: false,
110
pending_trust: None,
111
auto_print_attempted: false,
78
}
112
}
79
}
113
}
80
114
@@ -94,6 +128,25 @@ impl PrintOnlyApp {94
fn request_exit(&mut self) {
128
fn request_exit(&mut self) {
95
self.exit_requested = true;
129
self.exit_requested = true;
96
}
130
}
131
132
fn try_auto_print(&mut self, ctx: &egui::Context) {
133
if !self.auto_print || self.auto_print_attempted || self.fatal_error.is_some() {
134
return;
135
}
136
if self.dialog.printers_loading {
137
ctx.request_repaint();
138
return;
139
}
140
self.auto_print_attempted = true;
141
if self
142
.dialog
143
.execute_print(&self.body, &self.metadata, self.file_path.as_ref())
144
== PrintExecuteResult::Printed
145
{
146
self.request_exit();
147
}
148
// On failure, keep the dialog open so the user can fix params/printer.
149
}
97
}
150
}
98
151
99
impl eframe::App for PrintOnlyApp {
152
impl eframe::App for PrintOnlyApp {
@@ -106,6 +159,39 @@ impl eframe::App for PrintOnlyApp {106
self.dialog.poll_printer_discovery(ctx);
159
self.dialog.poll_printer_discovery(ctx);
107
ctx.send_viewport_cmd(egui::ViewportCommand::Title(self.title()));
160
ctx.send_viewport_cmd(egui::ViewportCommand::Title(self.title()));
108
161
162
if let Some(origin) = self.pending_trust.clone() {
163
egui::CentralPanel::default().show(ctx, |ui| {
164
ui.heading("Trust this site?");
165
ui.separator();
166
ui.label(format!(
167
"A page from “{origin}” wants to print without confirmation (noconfirm)."
168
));
169
ui.label(
170
"If you trust this site, posprint will allow future noconfirm prints from this domain without asking again.",
171
);
172
ui.add_space(12.0);
173
ui.horizontal(|ui| {
174
if ui.button("Trust and print").clicked() {
175
let mut cfg = AppConfig::load();
176
cfg.trust_origin(&origin);
177
if let Err(e) = cfg.save() {
178
self.fatal_error = Some(format!("Could not save trust setting: {e}"));
179
self.pending_trust = None;
180
} else {
181
self.pending_trust = None;
182
self.auto_print = true;
183
}
184
}
185
if ui.button("Cancel").clicked() {
186
self.request_exit();
187
}
188
});
189
ui.add_space(8.0);
190
ui.label("You can revoke trust later under Settings in the designer.");
191
});
192
return;
193
}
194
109
if let Some(err) = self.fatal_error.clone() {
195
if let Some(err) = self.fatal_error.clone() {
110
egui::CentralPanel::default().show(ctx, |ui| {
196
egui::CentralPanel::default().show(ctx, |ui| {
111
ui.heading("Print");
197
ui.heading("Print");
@@ -118,6 +204,8 @@ impl eframe::App for PrintOnlyApp {118
return;
204
return;
119
}
205
}
120
206
207
self.try_auto_print(ctx);
208
121
let mut action = PrintDialogAction::None;
209
let mut action = PrintDialogAction::None;
122
210
123
egui::CentralPanel::default().show(ctx, |ui| {
211
egui::CentralPanel::default().show(ctx, |ui| {
@@ -9,6 +9,7 @@ use flate2::read::DeflateDecoder;
9
9
use flate2::write::DeflateEncoder;
10
10
use flate2::Compression;
11
11
12
use crate::config::normalize_origin;
12
13
use crate::io::PosFile;
13
14
14
15
/// Soft warning threshold for cross-platform protocol handoff (~Windows cmdline limit).
@@ -51,6 +52,23 @@ impl From<serde_json::Error> for ProtocolUrlError {
51
52
}
52
53
}
53
54
55
/// Decoded `posprint://` launch request.
56
#[derive(Debug, Clone, PartialEq)]
57
pub struct PosprintLaunch {
58
pub file: PosFile,
59
/// When true, print without waiting for the Print button (subject to domain trust).
60
pub noconfirm: bool,
61
/// Normalized hostname from `origin=` (required for first-time trust when noconfirm).
62
pub origin: Option<String>,
63
}
64
65
/// Optional extras when encoding a URL.
66
#[derive(Debug, Clone, Default)]
67
pub struct EncodeOptions {
68
pub noconfirm: bool,
69
pub origin: Option<String>,
70
}
71
54
72
/// True when `s` looks like a `posprint:` / `posprint://` protocol URL.
55
73
pub fn is_posprint_url(s: &str) -> bool {
56
74
let s = s.trim();
@@ -60,6 +78,14 @@ pub fn is_posprint_url(s: &str) -> bool {
60
78
61
79
/// Encode a `.pos` file as `posprint://print?v=1&d=…` (raw deflate + base64url, no padding).
62
80
pub fn encode_posprint_url(file: &PosFile) -> Result<String, ProtocolUrlError> {
81
encode_posprint_url_with_options(file, &EncodeOptions::default())
82
}
83
84
/// Encode with optional `noconfirm` / `origin` query parameters.
85
pub fn encode_posprint_url_with_options(
86
file: &PosFile,
87
options: &EncodeOptions,
88
) -> Result<String, ProtocolUrlError> {
63
89
let json = serde_json::to_vec(file)?;
64
90
let mut encoder = DeflateEncoder::new(Vec::new(), Compression::best());
65
91
encoder
@@ -69,11 +95,21 @@ pub fn encode_posprint_url(file: &PosFile) -> Result<String, ProtocolUrlError> {
69
95
.finish()
70
96
.map_err(|e| ProtocolUrlError::Inflate(e.to_string()))?;
71
97
let b64 = URL_SAFE_NO_PAD.encode(compressed);
72
Ok(format!("posprint://print?v=1&d={b64}"))
98
let mut url = format!("posprint://print?v=1&d={b64}");
99
if options.noconfirm {
100
url.push_str("&noconfirm=1");
101
}
102
if let Some(raw) = options.origin.as_deref() {
103
if let Some(host) = normalize_origin(raw) {
104
url.push_str("&origin=");
105
url.push_str(&percent_encode_component(&host));
106
}
107
}
108
Ok(url)
73
109
}
74
110
75
/// Decode a `posprint://print?v=1&d=…` URL into a [`PosFile`].
76
pub fn parse_posprint_url(url: &str) -> Result<PosFile, ProtocolUrlError> {
111
/// Decode a `posprint://print?v=1&d=…` URL into a [`PosprintLaunch`].
112
pub fn parse_posprint_url(url: &str) -> Result<PosprintLaunch, ProtocolUrlError> {
77
113
let url = url.trim();
78
114
if !is_posprint_url(url) {
79
115
return Err(ProtocolUrlError::NotPosprintUrl);
@@ -98,6 +134,8 @@ pub fn parse_posprint_url(url: &str) -> Result<PosFile, ProtocolUrlError> {
98
134
99
135
let mut version: Option<String> = None;
100
136
let mut payload: Option<String> = None;
137
let mut noconfirm = false;
138
let mut origin_raw: Option<String> = None;
101
139
for pair in query.split('&') {
102
140
if pair.is_empty() {
103
141
continue;
@@ -107,6 +145,8 @@ pub fn parse_posprint_url(url: &str) -> Result<PosFile, ProtocolUrlError> {
107
145
match key.as_str() {
108
146
"v" => version = Some(percent_decode_str(value)?),
109
147
"d" => payload = Some(percent_decode_str(value)?),
148
"noconfirm" => noconfirm = parse_bool_flag(value),
149
"origin" => origin_raw = Some(percent_decode_str(value)?),
110
150
_ => {}
111
151
}
112
152
}
@@ -131,7 +171,37 @@ pub fn parse_posprint_url(url: &str) -> Result<PosFile, ProtocolUrlError> {
131
171
if file.version != 1 {
132
172
return Err(ProtocolUrlError::UnsupportedPosVersion(file.version));
133
173
}
134
Ok(file)
174
175
let origin = origin_raw.as_deref().and_then(normalize_origin);
176
Ok(PosprintLaunch {
177
file,
178
noconfirm,
179
origin,
180
})
181
}
182
183
fn parse_bool_flag(value: &str) -> bool {
184
let v = value.trim();
185
if v.is_empty() {
186
return true;
187
}
188
matches!(
189
v.to_ascii_lowercase().as_str(),
190
"1" | "true" | "yes" | "on"
191
)
192
}
193
194
fn percent_encode_component(input: &str) -> String {
195
let mut out = String::with_capacity(input.len());
196
for b in input.bytes() {
197
match b {
198
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
199
out.push(b as char);
200
}
201
_ => out.push_str(&format!("%{b:02X}")),
202
}
203
}
204
out
135
205
}
136
206
137
207
fn percent_decode_str(input: &str) -> Result<String, ProtocolUrlError> {
@@ -204,7 +274,37 @@ mod tests {
204
274
let url = encode_posprint_url(&file).unwrap();
205
275
assert!(url.starts_with("posprint://print?v=1&d="));
206
276
let decoded = parse_posprint_url(&url).unwrap();
207
assert_eq!(decoded, file);
277
assert_eq!(decoded.file, file);
278
assert!(!decoded.noconfirm);
279
assert!(decoded.origin.is_none());
280
}
281
282
#[test]
283
fn encodes_and_parses_noconfirm_and_origin() {
284
let file = sample_file();
285
let url = encode_posprint_url_with_options(
286
&file,
287
&EncodeOptions {
288
noconfirm: true,
289
origin: Some("https://Shop.Example.com/x".into()),
290
},
291
)
292
.unwrap();
293
assert!(url.contains("&noconfirm=1"));
294
assert!(url.contains("&origin=shop.example.com"));
295
let launch = parse_posprint_url(&url).unwrap();
296
assert!(launch.noconfirm);
297
assert_eq!(launch.origin.as_deref(), Some("shop.example.com"));
298
}
299
300
#[test]
301
fn parses_noconfirm_without_value() {
302
let file = sample_file();
303
let base = encode_posprint_url(&file).unwrap();
304
let url = format!("{base}&noconfirm&origin=pos.local");
305
let launch = parse_posprint_url(&url).unwrap();
306
assert!(launch.noconfirm);
307
assert_eq!(launch.origin.as_deref(), Some("pos.local"));
208
308
}
209
309
210
310
#[test]
@@ -9,6 +9,7 @@ use flate2::read::DeflateDecoder;9
use flate2::write::DeflateEncoder;
9
use flate2::write::DeflateEncoder;
10
use flate2::Compression;
10
use flate2::Compression;
11
11
12
use crate::config::normalize_origin;
12
use crate::io::PosFile;
13
use crate::io::PosFile;
13
14
14
/// Soft warning threshold for cross-platform protocol handoff (~Windows cmdline limit).
15
/// Soft warning threshold for cross-platform protocol handoff (~Windows cmdline limit).
@@ -51,6 +52,23 @@ impl From<serde_json::Error> for ProtocolUrlError {51
}
52
}
52
}
53
}
53
54
55
/// Decoded `posprint://` launch request.
56
#[derive(Debug, Clone, PartialEq)]
57
pub struct PosprintLaunch {
58
pub file: PosFile,
59
/// When true, print without waiting for the Print button (subject to domain trust).
60
pub noconfirm: bool,
61
/// Normalized hostname from `origin=` (required for first-time trust when noconfirm).
62
pub origin: Option<String>,
63
}
64
65
/// Optional extras when encoding a URL.
66
#[derive(Debug, Clone, Default)]
67
pub struct EncodeOptions {
68
pub noconfirm: bool,
69
pub origin: Option<String>,
70
}
71
54
/// True when `s` looks like a `posprint:` / `posprint://` protocol URL.
72
/// True when `s` looks like a `posprint:` / `posprint://` protocol URL.
55
pub fn is_posprint_url(s: &str) -> bool {
73
pub fn is_posprint_url(s: &str) -> bool {
56
let s = s.trim();
74
let s = s.trim();
@@ -60,6 +78,14 @@ pub fn is_posprint_url(s: &str) -> bool {60
78
61
/// Encode a `.pos` file as `posprint://print?v=1&d=…` (raw deflate + base64url, no padding).
79
/// Encode a `.pos` file as `posprint://print?v=1&d=…` (raw deflate + base64url, no padding).
62
pub fn encode_posprint_url(file: &PosFile) -> Result<String, ProtocolUrlError> {
80
pub fn encode_posprint_url(file: &PosFile) -> Result<String, ProtocolUrlError> {
81
encode_posprint_url_with_options(file, &EncodeOptions::default())
82
}
83
84
/// Encode with optional `noconfirm` / `origin` query parameters.
85
pub fn encode_posprint_url_with_options(
86
file: &PosFile,
87
options: &EncodeOptions,
88
) -> Result<String, ProtocolUrlError> {
63
let json = serde_json::to_vec(file)?;
89
let json = serde_json::to_vec(file)?;
64
let mut encoder = DeflateEncoder::new(Vec::new(), Compression::best());
90
let mut encoder = DeflateEncoder::new(Vec::new(), Compression::best());
65
encoder
91
encoder
@@ -69,11 +95,21 @@ pub fn encode_posprint_url(file: &PosFile) -> Result<String, ProtocolUrlError> {69
.finish()
95
.finish()
70
.map_err(|e| ProtocolUrlError::Inflate(e.to_string()))?;
96
.map_err(|e| ProtocolUrlError::Inflate(e.to_string()))?;
71
let b64 = URL_SAFE_NO_PAD.encode(compressed);
97
let b64 = URL_SAFE_NO_PAD.encode(compressed);
72
Ok(format!("posprint://print?v=1&d={b64}"))
98
let mut url = format!("posprint://print?v=1&d={b64}");
99
if options.noconfirm {
100
url.push_str("&noconfirm=1");
101
}
102
if let Some(raw) = options.origin.as_deref() {
103
if let Some(host) = normalize_origin(raw) {
104
url.push_str("&origin=");
105
url.push_str(&percent_encode_component(&host));
106
}
107
}
108
Ok(url)
73
}
109
}
74
110
75
/// Decode a `posprint://print?v=1&d=…` URL into a [`PosFile`].
111
/// Decode a `posprint://print?v=1&d=…` URL into a [`PosprintLaunch`].
76
pub fn parse_posprint_url(url: &str) -> Result<PosFile, ProtocolUrlError> {
112
pub fn parse_posprint_url(url: &str) -> Result<PosprintLaunch, ProtocolUrlError> {
77
let url = url.trim();
113
let url = url.trim();
78
if !is_posprint_url(url) {
114
if !is_posprint_url(url) {
79
return Err(ProtocolUrlError::NotPosprintUrl);
115
return Err(ProtocolUrlError::NotPosprintUrl);
@@ -98,6 +134,8 @@ pub fn parse_posprint_url(url: &str) -> Result<PosFile, ProtocolUrlError> {98
134
99
let mut version: Option<String> = None;
135
let mut version: Option<String> = None;
100
let mut payload: Option<String> = None;
136
let mut payload: Option<String> = None;
137
let mut noconfirm = false;
138
let mut origin_raw: Option<String> = None;
101
for pair in query.split('&') {
139
for pair in query.split('&') {
102
if pair.is_empty() {
140
if pair.is_empty() {
103
continue;
141
continue;
@@ -107,6 +145,8 @@ pub fn parse_posprint_url(url: &str) -> Result<PosFile, ProtocolUrlError> {107
match key.as_str() {
145
match key.as_str() {
108
"v" => version = Some(percent_decode_str(value)?),
146
"v" => version = Some(percent_decode_str(value)?),
109
"d" => payload = Some(percent_decode_str(value)?),
147
"d" => payload = Some(percent_decode_str(value)?),
148
"noconfirm" => noconfirm = parse_bool_flag(value),
149
"origin" => origin_raw = Some(percent_decode_str(value)?),
110
_ => {}
150
_ => {}
111
}
151
}
112
}
152
}
@@ -131,7 +171,37 @@ pub fn parse_posprint_url(url: &str) -> Result<PosFile, ProtocolUrlError> {131
if file.version != 1 {
171
if file.version != 1 {
132
return Err(ProtocolUrlError::UnsupportedPosVersion(file.version));
172
return Err(ProtocolUrlError::UnsupportedPosVersion(file.version));
133
}
173
}
134
Ok(file)
174
175
let origin = origin_raw.as_deref().and_then(normalize_origin);
176
Ok(PosprintLaunch {
177
file,
178
noconfirm,
179
origin,
180
})
181
}
182
183
fn parse_bool_flag(value: &str) -> bool {
184
let v = value.trim();
185
if v.is_empty() {
186
return true;
187
}
188
matches!(
189
v.to_ascii_lowercase().as_str(),
190
"1" | "true" | "yes" | "on"
191
)
192
}
193
194
fn percent_encode_component(input: &str) -> String {
195
let mut out = String::with_capacity(input.len());
196
for b in input.bytes() {
197
match b {
198
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'_' | b'.' | b'~' => {
199
out.push(b as char);
200
}
201
_ => out.push_str(&format!("%{b:02X}")),
202
}
203
}
204
out
135
}
205
}
136
206
137
fn percent_decode_str(input: &str) -> Result<String, ProtocolUrlError> {
207
fn percent_decode_str(input: &str) -> Result<String, ProtocolUrlError> {
@@ -204,7 +274,37 @@ mod tests {204
let url = encode_posprint_url(&file).unwrap();
274
let url = encode_posprint_url(&file).unwrap();
205
assert!(url.starts_with("posprint://print?v=1&d="));
275
assert!(url.starts_with("posprint://print?v=1&d="));
206
let decoded = parse_posprint_url(&url).unwrap();
276
let decoded = parse_posprint_url(&url).unwrap();
207
assert_eq!(decoded, file);
277
assert_eq!(decoded.file, file);
278
assert!(!decoded.noconfirm);
279
assert!(decoded.origin.is_none());
280
}
281
282
#[test]
283
fn encodes_and_parses_noconfirm_and_origin() {
284
let file = sample_file();
285
let url = encode_posprint_url_with_options(
286
&file,
287
&EncodeOptions {
288
noconfirm: true,
289
origin: Some("https://Shop.Example.com/x".into()),
290
},
291
)
292
.unwrap();
293
assert!(url.contains("&noconfirm=1"));
294
assert!(url.contains("&origin=shop.example.com"));
295
let launch = parse_posprint_url(&url).unwrap();
296
assert!(launch.noconfirm);
297
assert_eq!(launch.origin.as_deref(), Some("shop.example.com"));
298
}
299
300
#[test]
301
fn parses_noconfirm_without_value() {
302
let file = sample_file();
303
let base = encode_posprint_url(&file).unwrap();
304
let url = format!("{base}&noconfirm&origin=pos.local");
305
let launch = parse_posprint_url(&url).unwrap();
306
assert!(launch.noconfirm);
307
assert_eq!(launch.origin.as_deref(), Some("pos.local"));
208
}
308
}
209
309
210
#[test]
310
#[test]