BlueGit

timfa posprint

Add posprint:// deep links with embedded .pos documents.

Register the protocol on Windows/Linux, support http(s) @image downloads, and ship PHP/Node/browser helpers plus POSPRINT-URL docs.

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

timfa Tim Falken · pushed by timfa

Authored 2026-07-21 · 3 months ago

Hash
4ac56a022ccebb876dc5d2cd93c380d72249ddcd
Parent
6b4a2c8a
26 files changed +966 −58
Cargo.lock +126 −0
@@ -451,6 +451,12 @@ dependencies = [
451 451 "image",
452 452 ]
453 453
454 [[package]]
455 name = "base64"
456 version = "0.22.1"
457 source = "registry+https://github.com/rust-lang/crates.io-index"
458 checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
459
454 460 [[package]]
455 461 name = "bit-set"
456 462 version = "0.8.0"
@@ -1351,6 +1357,17 @@ dependencies = [
1351 1357 "unicode-width 0.2.2",
1352 1358 ]
1353 1359
1360 [[package]]
1361 name = "getrandom"
1362 version = "0.2.17"
1363 source = "registry+https://github.com/rust-lang/crates.io-index"
1364 checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
1365 dependencies = [
1366 "cfg-if",
1367 "libc",
1368 "wasi",
1369 ]
1370
1354 1371 [[package]]
1355 1372 name = "getrandom"
1356 1373 version = "0.3.4"
@@ -2772,9 +2789,11 @@ name = "posprint"
2772 2789 version = "0.3.1"
2773 2790 dependencies = [
2774 2791 "barcoders",
2792 "base64",
2775 2793 "chrono",
2776 2794 "clap",
2777 2795 "eframe",
2796 "flate2",
2778 2797 "ico",
2779 2798 "image",
2780 2799 "libc",
@@ -2786,6 +2805,7 @@ dependencies = [
2786 2805 "serde_json",
2787 2806 "serialport",
2788 2807 "tempfile",
2808 "ureq",
2789 2809 "winreg",
2790 2810 "winres",
2791 2811 ]
@@ -3130,6 +3150,20 @@ version = "0.8.53"
3130 3150 source = "registry+https://github.com/rust-lang/crates.io-index"
3131 3151 checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4"
3132 3152
3153 [[package]]
3154 name = "ring"
3155 version = "0.17.14"
3156 source = "registry+https://github.com/rust-lang/crates.io-index"
3157 checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
3158 dependencies = [
3159 "cc",
3160 "cfg-if",
3161 "getrandom 0.2.17",
3162 "libc",
3163 "untrusted",
3164 "windows-sys 0.52.0",
3165 ]
3166
3133 3167 [[package]]
3134 3168 name = "rusb"
3135 3169 version = "0.9.4"
@@ -3187,6 +3221,41 @@ dependencies = [
3187 3221 "windows-sys 0.61.2",
3188 3222 ]
3189 3223
3224 [[package]]
3225 name = "rustls"
3226 version = "0.23.42"
3227 source = "registry+https://github.com/rust-lang/crates.io-index"
3228 checksum = "3c54fcab019b409d04215d3a17cb438fd7fbf192ee61461f20f4fe18704bc138"
3229 dependencies = [
3230 "log",
3231 "once_cell",
3232 "ring",
3233 "rustls-pki-types",
3234 "rustls-webpki",
3235 "subtle",
3236 "zeroize",
3237 ]
3238
3239 [[package]]
3240 name = "rustls-pki-types"
3241 version = "1.15.0"
3242 source = "registry+https://github.com/rust-lang/crates.io-index"
3243 checksum = "764899a24af3980067ee14bc143654f297b22eaebfe3c7b6b211920a5a59b046"
3244 dependencies = [
3245 "zeroize",
3246 ]
3247
3248 [[package]]
3249 name = "rustls-webpki"
3250 version = "0.103.13"
3251 source = "registry+https://github.com/rust-lang/crates.io-index"
3252 checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e"
3253 dependencies = [
3254 "ring",
3255 "rustls-pki-types",
3256 "untrusted",
3257 ]
3258
3190 3259 [[package]]
3191 3260 name = "rustversion"
3192 3261 version = "1.0.23"
@@ -3482,6 +3551,12 @@ dependencies = [
3482 3551 "syn",
3483 3552 ]
3484 3553
3554 [[package]]
3555 name = "subtle"
3556 version = "2.6.1"
3557 source = "registry+https://github.com/rust-lang/crates.io-index"
3558 checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
3559
3485 3560 [[package]]
3486 3561 name = "syn"
3487 3562 version = "2.0.119"
@@ -3732,6 +3807,27 @@ version = "0.2.6"
3732 3807 source = "registry+https://github.com/rust-lang/crates.io-index"
3733 3808 checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
3734 3809
3810 [[package]]
3811 name = "untrusted"
3812 version = "0.9.0"
3813 source = "registry+https://github.com/rust-lang/crates.io-index"
3814 checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
3815
3816 [[package]]
3817 name = "ureq"
3818 version = "2.12.1"
3819 source = "registry+https://github.com/rust-lang/crates.io-index"
3820 checksum = "02d1a66277ed75f640d608235660df48c8e3c19f3b4edb6a263315626cc3c01d"
3821 dependencies = [
3822 "base64",
3823 "log",
3824 "once_cell",
3825 "rustls",
3826 "rustls-pki-types",
3827 "url",
3828 "webpki-roots 0.26.11",
3829 ]
3830
3735 3831 [[package]]
3736 3832 name = "url"
3737 3833 version = "2.5.8"
@@ -3807,6 +3903,12 @@ dependencies = [
3807 3903 "winapi-util",
3808 3904 ]
3809 3905
3906 [[package]]
3907 name = "wasi"
3908 version = "0.11.1+wasi-snapshot-preview1"
3909 source = "registry+https://github.com/rust-lang/crates.io-index"
3910 checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
3911
3810 3912 [[package]]
3811 3913 name = "wasip2"
3812 3914 version = "1.0.4+wasi-0.2.12"
@@ -4042,6 +4144,24 @@ dependencies = [
4042 4144 "web-sys",
4043 4145 ]
4044 4146
4147 [[package]]
4148 name = "webpki-roots"
4149 version = "0.26.11"
4150 source = "registry+https://github.com/rust-lang/crates.io-index"
4151 checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9"
4152 dependencies = [
4153 "webpki-roots 1.0.9",
4154 ]
4155
4156 [[package]]
4157 name = "webpki-roots"
4158 version = "1.0.9"
4159 source = "registry+https://github.com/rust-lang/crates.io-index"
4160 checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a"
4161 dependencies = [
4162 "rustls-pki-types",
4163 ]
4164
4045 4165 [[package]]
4046 4166 name = "weezl"
4047 4167 version = "0.1.12"
@@ -4755,6 +4875,12 @@ dependencies = [
4755 4875 "synstructure",
4756 4876 ]
4757 4877
4878 [[package]]
4879 name = "zeroize"
4880 version = "1.9.0"
4881 source = "registry+https://github.com/rust-lang/crates.io-index"
4882 checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"
4883
4758 4884 [[package]]
4759 4885 name = "zerotrie"
4760 4886 version = "0.2.4"
@@ -451,6 +451,12 @@ dependencies = [
451 "image",
451 "image",
452]
452]
453
453
454[[package]]
455name = "base64"
456version = "0.22.1"
457source = "registry+https://github.com/rust-lang/crates.io-index"
458checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
459
454[[package]]
460[[package]]
455name = "bit-set"
461name = "bit-set"
456version = "0.8.0"
462version = "0.8.0"
@@ -1351,6 +1357,17 @@ dependencies = [
1351 "unicode-width 0.2.2",
1357 "unicode-width 0.2.2",
1352]
1358]
1353
1359
1360[[package]]
1361name = "getrandom"
1362version = "0.2.17"
1363source = "registry+https://github.com/rust-lang/crates.io-index"
1364checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
1365dependencies = [
1366 "cfg-if",
1367 "libc",
1368 "wasi",
1369]
1370
1354[[package]]
1371[[package]]
1355name = "getrandom"
1372name = "getrandom"
1356version = "0.3.4"
1373version = "0.3.4"
@@ -2772,9 +2789,11 @@ name = "posprint"
2772version = "0.3.1"
2789version = "0.3.1"
2773dependencies = [
2790dependencies = [
2774 "barcoders",
2791 "barcoders",
2792 "base64",
2775 "chrono",
2793 "chrono",
2776 "clap",
2794 "clap",
2777 "eframe",
2795 "eframe",
2796 "flate2",
2778 "ico",
2797 "ico",
2779 "image",
2798 "image",
2780 "libc",
2799 "libc",
@@ -2786,6 +2805,7 @@ dependencies = [
2786 "serde_json",
2805 "serde_json",
2787 "serialport",
2806 "serialport",
2788 "tempfile",
2807 "tempfile",
2808 "ureq",
2789 "winreg",
2809 "winreg",
2790 "winres",
2810 "winres",
2791]
2811]
@@ -3130,6 +3150,20 @@ version = "0.8.53"
3130source = "registry+https://github.com/rust-lang/crates.io-index"
3150source = "registry+https://github.com/rust-lang/crates.io-index"
3131checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4"
3151checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4"
3132
3152
3153[[package]]
3154name = "ring"
3155version = "0.17.14"
3156source = "registry+https://github.com/rust-lang/crates.io-index"
3157checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
3158dependencies = [
3159 "cc",
3160 "cfg-if",
3161 "getrandom 0.2.17",
3162 "libc",
3163 "untrusted",
3164 "windows-sys 0.52.0",
3165]
3166
3133[[package]]
3167[[package]]
3134name = "rusb"
3168name = "rusb"
3135version = "0.9.4"
3169version = "0.9.4"
@@ -3187,6 +3221,41 @@ dependencies = [
3187 "windows-sys 0.61.2",
3221 "windows-sys 0.61.2",
3188]
3222]
3189
3223
3224[[package]]
3225name = "rustls"
3226version = "0.23.42"
3227source = "registry+https://github.com/rust-lang/crates.io-index"
3228checksum = "3c54fcab019b409d04215d3a17cb438fd7fbf192ee61461f20f4fe18704bc138"
3229dependencies = [
3230 "log",
3231 "once_cell",
3232 "ring",
3233 "rustls-pki-types",
3234 "rustls-webpki",
3235 "subtle",
3236 "zeroize",
3237]
3238
3239[[package]]
3240name = "rustls-pki-types"
3241version = "1.15.0"
3242source = "registry+https://github.com/rust-lang/crates.io-index"
3243checksum = "764899a24af3980067ee14bc143654f297b22eaebfe3c7b6b211920a5a59b046"
3244dependencies = [
3245 "zeroize",
3246]
3247
3248[[package]]
3249name = "rustls-webpki"
3250version = "0.103.13"
3251source = "registry+https://github.com/rust-lang/crates.io-index"
3252checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e"
3253dependencies = [
3254 "ring",
3255 "rustls-pki-types",
3256 "untrusted",
3257]
3258
3190[[package]]
3259[[package]]
3191name = "rustversion"
3260name = "rustversion"
3192version = "1.0.23"
3261version = "1.0.23"
@@ -3482,6 +3551,12 @@ dependencies = [
3482 "syn",
3551 "syn",
3483]
3552]
3484
3553
3554[[package]]
3555name = "subtle"
3556version = "2.6.1"
3557source = "registry+https://github.com/rust-lang/crates.io-index"
3558checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
3559
3485[[package]]
3560[[package]]
3486name = "syn"
3561name = "syn"
3487version = "2.0.119"
3562version = "2.0.119"
@@ -3732,6 +3807,27 @@ version = "0.2.6"
3732source = "registry+https://github.com/rust-lang/crates.io-index"
3807source = "registry+https://github.com/rust-lang/crates.io-index"
3733checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
3808checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
3734
3809
3810[[package]]
3811name = "untrusted"
3812version = "0.9.0"
3813source = "registry+https://github.com/rust-lang/crates.io-index"
3814checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
3815
3816[[package]]
3817name = "ureq"
3818version = "2.12.1"
3819source = "registry+https://github.com/rust-lang/crates.io-index"
3820checksum = "02d1a66277ed75f640d608235660df48c8e3c19f3b4edb6a263315626cc3c01d"
3821dependencies = [
3822 "base64",
3823 "log",
3824 "once_cell",
3825 "rustls",
3826 "rustls-pki-types",
3827 "url",
3828 "webpki-roots 0.26.11",
3829]
3830
3735[[package]]
3831[[package]]
3736name = "url"
3832name = "url"
3737version = "2.5.8"
3833version = "2.5.8"
@@ -3807,6 +3903,12 @@ dependencies = [
3807 "winapi-util",
3903 "winapi-util",
3808]
3904]
3809
3905
3906[[package]]
3907name = "wasi"
3908version = "0.11.1+wasi-snapshot-preview1"
3909source = "registry+https://github.com/rust-lang/crates.io-index"
3910checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
3911
3810[[package]]
3912[[package]]
3811name = "wasip2"
3913name = "wasip2"
3812version = "1.0.4+wasi-0.2.12"
3914version = "1.0.4+wasi-0.2.12"
@@ -4042,6 +4144,24 @@ dependencies = [
4042 "web-sys",
4144 "web-sys",
4043]
4145]
4044
4146
4147[[package]]
4148name = "webpki-roots"
4149version = "0.26.11"
4150source = "registry+https://github.com/rust-lang/crates.io-index"
4151checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9"
4152dependencies = [
4153 "webpki-roots 1.0.9",
4154]
4155
4156[[package]]
4157name = "webpki-roots"
4158version = "1.0.9"
4159source = "registry+https://github.com/rust-lang/crates.io-index"
4160checksum = "7dcd9d09a39985f5344844e66b0c530a33843579125f23e21e9f0f220850f22a"
4161dependencies = [
4162 "rustls-pki-types",
4163]
4164
4045[[package]]
4165[[package]]
4046name = "weezl"
4166name = "weezl"
4047version = "0.1.12"
4167version = "0.1.12"
@@ -4755,6 +4875,12 @@ dependencies = [
4755 "synstructure",
4875 "synstructure",
4756]
4876]
4757
4877
4878[[package]]
4879name = "zeroize"
4880version = "1.9.0"
4881source = "registry+https://github.com/rust-lang/crates.io-index"
4882checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"
4883
4758[[package]]
4884[[package]]
4759name = "zerotrie"
4885name = "zerotrie"
4760version = "0.2.4"
4886version = "0.2.4"
Cargo.toml +4 −0
@@ -23,6 +23,9 @@ rusb = "0.9"
23 23 chrono = { version = "0.4", default-features = false, features = ["clock", "std", "alloc"] }
24 24 libc = "0.2"
25 25 tempfile = "3"
26 flate2 = "1"
27 base64 = "0.22"
28 ureq = { version = "2", default-features = false, features = ["tls"] }
26 29
27 30 [dev-dependencies]
28 31 tempfile = "3"
@@ -51,6 +54,7 @@ Designer for POS receipt templates with live preview and USB ESC/POS printing.""
51 54 assets = [
52 55 ["target/release/posprint", "usr/bin/", "755"],
53 56 ["packaging/posprint.desktop", "usr/share/applications/", "644"],
57 ["packaging/posprint-url.desktop", "usr/share/applications/", "644"],
54 58 ["packaging/mime/posprint.xml", "usr/share/mime/packages/", "644"],
55 59 ["packaging/linux/posprint-print.desktop", "usr/share/kio/servicemenus/", "644"],
56 60 ["packaging/linux/posprint-print-thunar.xml", "usr/share/thunar/uca/", "644"],
@@ -23,6 +23,9 @@ rusb = "0.9"
23chrono = { version = "0.4", default-features = false, features = ["clock", "std", "alloc"] }
23chrono = { version = "0.4", default-features = false, features = ["clock", "std", "alloc"] }
24libc = "0.2"
24libc = "0.2"
25tempfile = "3"
25tempfile = "3"
26flate2 = "1"
27base64 = "0.22"
28ureq = { version = "2", default-features = false, features = ["tls"] }
26
29
27[dev-dependencies]
30[dev-dependencies]
28tempfile = "3"
31tempfile = "3"
@@ -51,6 +54,7 @@ Designer for POS receipt templates with live preview and USB ESC/POS printing.""
51assets = [
54assets = [
52 ["target/release/posprint", "usr/bin/", "755"],
55 ["target/release/posprint", "usr/bin/", "755"],
53 ["packaging/posprint.desktop", "usr/share/applications/", "644"],
56 ["packaging/posprint.desktop", "usr/share/applications/", "644"],
57 ["packaging/posprint-url.desktop", "usr/share/applications/", "644"],
54 ["packaging/mime/posprint.xml", "usr/share/mime/packages/", "644"],
58 ["packaging/mime/posprint.xml", "usr/share/mime/packages/", "644"],
55 ["packaging/linux/posprint-print.desktop", "usr/share/kio/servicemenus/", "644"],
59 ["packaging/linux/posprint-print.desktop", "usr/share/kio/servicemenus/", "644"],
56 ["packaging/linux/posprint-print-thunar.xml", "usr/share/thunar/uca/", "644"],
60 ["packaging/linux/posprint-print-thunar.xml", "usr/share/thunar/uca/", "644"],
README.md +4 −1
@@ -68,6 +68,7 @@ Tag a version (e.g. `0.3.1`) to trigger release builds.
68 68 | [DSL-SPEC.md](docs/DSL-SPEC.md) | Document markup language (`.pos` body syntax) |
69 69 | [FILE-FORMAT.md](docs/FILE-FORMAT.md) | `.pos` file envelope (metadata + body) |
70 70 | [PRINTING.md](docs/PRINTING.md) | Printer discovery, transport, ESC/POS pipeline |
71 | [POSPRINT-URL.md](docs/POSPRINT-URL.md) | `posprint://` deep links and `lib/` helpers |
71 72 | [BUILD.md](docs/BUILD.md) | Local build scripts and Linux package formats |
72 73
73 74 Documentation must stay aligned with the codebase; see `.cursor/rules/documentation.mdc`.
@@ -84,6 +85,8 @@ Documentation must stay aligned with the codebase; see `.cursor/rules/documentat
84 85 | `rfd` | Native open/save dialogs |
85 86 | `barcoders` | Raster barcode rendering |
86 87 | `qrcode` | Raster QR rendering |
87 | `clap` | CLI `print` / `cli-help` |
88 | `clap` | CLI `print` / `link` / `cli-help` |
89 | `flate2` / `base64` | `posprint://` URL payload |
90 | `ureq` | Download `@image http(s)://…` |
88 91
89 92 ESC/POS encoding is implemented in-tree.
@@ -68,6 +68,7 @@ Tag a version (e.g. `0.3.1`) to trigger release builds.
68| [DSL-SPEC.md](docs/DSL-SPEC.md) | Document markup language (`.pos` body syntax) |
68| [DSL-SPEC.md](docs/DSL-SPEC.md) | Document markup language (`.pos` body syntax) |
69| [FILE-FORMAT.md](docs/FILE-FORMAT.md) | `.pos` file envelope (metadata + body) |
69| [FILE-FORMAT.md](docs/FILE-FORMAT.md) | `.pos` file envelope (metadata + body) |
70| [PRINTING.md](docs/PRINTING.md) | Printer discovery, transport, ESC/POS pipeline |
70| [PRINTING.md](docs/PRINTING.md) | Printer discovery, transport, ESC/POS pipeline |
71| [POSPRINT-URL.md](docs/POSPRINT-URL.md) | `posprint://` deep links and `lib/` helpers |
71| [BUILD.md](docs/BUILD.md) | Local build scripts and Linux package formats |
72| [BUILD.md](docs/BUILD.md) | Local build scripts and Linux package formats |
72
73
73Documentation must stay aligned with the codebase; see `.cursor/rules/documentation.mdc`.
74Documentation must stay aligned with the codebase; see `.cursor/rules/documentation.mdc`.
@@ -84,6 +85,8 @@ Documentation must stay aligned with the codebase; see `.cursor/rules/documentat
84| `rfd` | Native open/save dialogs |
85| `rfd` | Native open/save dialogs |
85| `barcoders` | Raster barcode rendering |
86| `barcoders` | Raster barcode rendering |
86| `qrcode` | Raster QR rendering |
87| `qrcode` | Raster QR rendering |
87| `clap` | CLI `print` / `cli-help` |
88| `clap` | CLI `print` / `link` / `cli-help` |
89| `flate2` / `base64` | `posprint://` URL payload |
90| `ureq` | Download `@image http(s)://…` |
88
91
89ESC/POS encoding is implemented in-tree.
92ESC/POS encoding is implemented in-tree.
docs/ARCHITECTURE.md +6 −2
@@ -22,7 +22,7 @@ src/
22 22 ├── app.rs # Full designer UI
23 23 ├── print_only_app.rs # Print-only window (--print)
24 24 ├── print_dialog.rs # Shared print dialog
25 ├── cli.rs # clap: print, cli-help
25 ├── cli.rs # clap: print, link, cli-help
26 26 ├── lib.rs # crate root; HELP_MARKDOWN
27 27 ├── dsl/ # Parser and AST
28 28 ├── params.rs # Parameter collect / substitute / preview samples
@@ -31,6 +31,8 @@ src/
31 31 ├── text_wrap.rs # Shared wrap (preview + print)
32 32 ├── datetime.rs # @date / @time formatting
33 33 ├── raster.rs # Barcode / QR bitmaps
34 ├── image_load.rs # Local + http(s) @image loading
35 ├── protocol_url.rs # posprint:// encode/decode
34 36 ├── editor_assist.rs # @ autocomplete, Insert snippets
35 37 ├── help_view.rs # Markdown help renderer
36 38 ├── io/mod.rs # PosFile, PosMetadata
@@ -39,7 +41,7 @@ src/
39 41 │ ├── mod.rs # list_printers, SerialTransport, MockTransport
40 42 │ ├── usb_direct.rs # USB printer-class (rusb)
41 43 │ └── win_spool.rs # Windows spooler (Windows)
42 └── shell_integration/ # OS “Print” context menu helpers
44 └── shell_integration.rs # .pos Print verb + posprint:// protocol (Windows)
43 45 ```
44 46
45 47 ### External dependencies
@@ -54,6 +56,8 @@ src/
54 56 | `rfd` | Native open/save dialogs |
55 57 | `barcoders` / `qrcode` | Raster barcodes and QR |
56 58 | `clap` | CLI |
59 | `flate2` / `base64` | `posprint://` payloads |
60 | `ureq` | `@image http(s)` download |
57 61 | `chrono` | Date/time |
58 62 | `pulldown-cmark` | In-app Help markdown |
59 63
@@ -22,7 +22,7 @@ src/
22├── app.rs # Full designer UI
22├── app.rs # Full designer UI
23├── print_only_app.rs # Print-only window (--print)
23├── print_only_app.rs # Print-only window (--print)
24├── print_dialog.rs # Shared print dialog
24├── print_dialog.rs # Shared print dialog
25├── cli.rs # clap: print, cli-help
25├── cli.rs # clap: print, link, cli-help
26├── lib.rs # crate root; HELP_MARKDOWN
26├── lib.rs # crate root; HELP_MARKDOWN
27├── dsl/ # Parser and AST
27├── dsl/ # Parser and AST
28├── params.rs # Parameter collect / substitute / preview samples
28├── params.rs # Parameter collect / substitute / preview samples
@@ -31,6 +31,8 @@ src/
31├── text_wrap.rs # Shared wrap (preview + print)
31├── text_wrap.rs # Shared wrap (preview + print)
32├── datetime.rs # @date / @time formatting
32├── datetime.rs # @date / @time formatting
33├── raster.rs # Barcode / QR bitmaps
33├── raster.rs # Barcode / QR bitmaps
34├── image_load.rs # Local + http(s) @image loading
35├── protocol_url.rs # posprint:// encode/decode
34├── editor_assist.rs # @ autocomplete, Insert snippets
36├── editor_assist.rs # @ autocomplete, Insert snippets
35├── help_view.rs # Markdown help renderer
37├── help_view.rs # Markdown help renderer
36├── io/mod.rs # PosFile, PosMetadata
38├── io/mod.rs # PosFile, PosMetadata
@@ -39,7 +41,7 @@ src/
39│ ├── mod.rs # list_printers, SerialTransport, MockTransport
41│ ├── mod.rs # list_printers, SerialTransport, MockTransport
40│ ├── usb_direct.rs # USB printer-class (rusb)
42│ ├── usb_direct.rs # USB printer-class (rusb)
41│ └── win_spool.rs # Windows spooler (Windows)
43│ └── win_spool.rs # Windows spooler (Windows)
42└── shell_integration/ # OS “Print” context menu helpers
44└── shell_integration.rs # .pos Print verb + posprint:// protocol (Windows)
43```
45```
44
46
45### External dependencies
47### External dependencies
@@ -54,6 +56,8 @@ src/
54| `rfd` | Native open/save dialogs |
56| `rfd` | Native open/save dialogs |
55| `barcoders` / `qrcode` | Raster barcodes and QR |
57| `barcoders` / `qrcode` | Raster barcodes and QR |
56| `clap` | CLI |
58| `clap` | CLI |
59| `flate2` / `base64` | `posprint://` payloads |
60| `ureq` | `@image http(s)` download |
57| `chrono` | Date/time |
61| `chrono` | Date/time |
58| `pulldown-cmark` | In-app Help markdown |
62| `pulldown-cmark` | In-app Help markdown |
59
63
docs/HELP-CLI-LINUX.md +11 −1
@@ -8,12 +8,14 @@ Run `posprint cli-help` to print this section from the binary (no GUI required).
8 8
9 9 ```bash
10 10 posprint print <file.pos> --printer <DEVICE> --set Name=Value [--set Other=Value ...]
11 posprint link <file.pos>
11 12 ```
12 13
13 14 Short form:
14 15
15 16 ```bash
16 17 posprint print receipt.pos -p /dev/ttyUSB0 --set StoreName="My Shop" --set DocumentNumber=1001
18 posprint link receipt.pos
17 19 ```
18 20
19 21 ## Rules
@@ -23,6 +25,7 @@ posprint print receipt.pos -p /dev/ttyUSB0 --set StoreName="My Shop" --set Docum
23 25 - Checkbox params (`$[Name]`): use `true`/`false` (also `1`/`0`, `yes`/`no`).
24 26 - If any text `${Name}` is missing or empty, or a `$[Name]` is omitted / not a boolean, the command **fails**.
25 27 - The GUI is not started when using the `print` subcommand.
28 - **`posprint link`** encodes the `.pos` file as a `posprint://` URL on stdout (see [POSPRINT-URL.md](POSPRINT-URL.md)). Warns if the URL is very long.
26 29
27 30 ## Permissions
28 31
@@ -63,7 +66,14 @@ Use the device node shown when the printer is connected.
63 66
64 67 ```bash
65 68 posprint print --help
69 posprint link --help
66 70 posprint --help
67 71 ```
68 72
69 Launch the graphical designer by running `posprint` with **no** subcommand.
73 Launch the graphical designer by running `posprint` with **no** subcommand. Opening a `posprint://…` URL (from a browser) starts the print dialog only.
74
75 After package install, if `posprint://` links do not open:
76
77 ```bash
78 xdg-mime default posprint-url.desktop x-scheme-handler/posprint
79 ```
@@ -8,12 +8,14 @@ Run `posprint cli-help` to print this section from the binary (no GUI required).
8
8
9```bash
9```bash
10posprint print <file.pos> --printer <DEVICE> --set Name=Value [--set Other=Value ...]
10posprint print <file.pos> --printer <DEVICE> --set Name=Value [--set Other=Value ...]
11posprint link <file.pos>
11```
12```
12
13
13Short form:
14Short form:
14
15
15```bash
16```bash
16posprint print receipt.pos -p /dev/ttyUSB0 --set StoreName="My Shop" --set DocumentNumber=1001
17posprint print receipt.pos -p /dev/ttyUSB0 --set StoreName="My Shop" --set DocumentNumber=1001
18posprint link receipt.pos
17```
19```
18
20
19## Rules
21## Rules
@@ -23,6 +25,7 @@ posprint print receipt.pos -p /dev/ttyUSB0 --set StoreName="My Shop" --set Docum
23- Checkbox params (`$[Name]`): use `true`/`false` (also `1`/`0`, `yes`/`no`).
25- Checkbox params (`$[Name]`): use `true`/`false` (also `1`/`0`, `yes`/`no`).
24- If any text `${Name}` is missing or empty, or a `$[Name]` is omitted / not a boolean, the command **fails**.
26- If any text `${Name}` is missing or empty, or a `$[Name]` is omitted / not a boolean, the command **fails**.
25- The GUI is not started when using the `print` subcommand.
27- The GUI is not started when using the `print` subcommand.
28- **`posprint link`** encodes the `.pos` file as a `posprint://` URL on stdout (see [POSPRINT-URL.md](POSPRINT-URL.md)). Warns if the URL is very long.
26
29
27## Permissions
30## Permissions
28
31
@@ -63,7 +66,14 @@ Use the device node shown when the printer is connected.
63
66
64```bash
67```bash
65posprint print --help
68posprint print --help
69posprint link --help
66posprint --help
70posprint --help
67```
71```
68
72
69Launch the graphical designer by running `posprint` with **no** subcommand.
73Launch the graphical designer by running `posprint` with **no** subcommand. Opening a `posprint://…` URL (from a browser) starts the print dialog only.
74
75After package install, if `posprint://` links do not open:
76
77```bash
78xdg-mime default posprint-url.desktop x-scheme-handler/posprint
79```
docs/HELP-CLI-WINDOWS.md +5 −1
@@ -8,12 +8,14 @@ Run `posprint cli-help` to print this section from the binary (no GUI required).
8 8
9 9 ```powershell
10 10 posprint print <file.pos> --printer <PORT> --set Name=Value [--set Other=Value ...]
11 posprint link <file.pos>
11 12 ```
12 13
13 14 Short form:
14 15
15 16 ```powershell
16 17 posprint print receipt.pos -p COM3 --set StoreName="My Shop" --set DocumentNumber=1001
18 posprint link receipt.pos
17 19 ```
18 20
19 21 ## Rules
@@ -23,6 +25,7 @@ posprint print receipt.pos -p COM3 --set StoreName="My Shop" --set DocumentNumbe
23 25 - Checkbox params (`$[Name]`): use `true`/`false` (also `1`/`0`, `yes`/`no`).
24 26 - If any text `${Name}` is missing or empty, or a `$[Name]` is omitted / not a boolean, the command **fails**.
25 27 - The GUI is not started when using the `print` subcommand.
28 - **`posprint link`** encodes the `.pos` file as a `posprint://` URL on stdout (see [POSPRINT-URL.md](POSPRINT-URL.md)). Warns if the URL is very long.
26 29
27 30 ## Examples
28 31
@@ -53,7 +56,8 @@ posprint print C:\receipts\sale.pos -p COM3 `
53 56
54 57 ```powershell
55 58 posprint print --help
59 posprint link --help
56 60 posprint --help
57 61 ```
58 62
59 Launch the graphical designer by running `posprint` with **no** subcommand.
63 Launch the graphical designer by running `posprint` with **no** subcommand. Opening a `posprint://…` URL (from a browser) starts the print dialog only.
@@ -8,12 +8,14 @@ Run `posprint cli-help` to print this section from the binary (no GUI required).
8
8
9```powershell
9```powershell
10posprint print <file.pos> --printer <PORT> --set Name=Value [--set Other=Value ...]
10posprint print <file.pos> --printer <PORT> --set Name=Value [--set Other=Value ...]
11posprint link <file.pos>
11```
12```
12
13
13Short form:
14Short form:
14
15
15```powershell
16```powershell
16posprint print receipt.pos -p COM3 --set StoreName="My Shop" --set DocumentNumber=1001
17posprint print receipt.pos -p COM3 --set StoreName="My Shop" --set DocumentNumber=1001
18posprint link receipt.pos
17```
19```
18
20
19## Rules
21## Rules
@@ -23,6 +25,7 @@ posprint print receipt.pos -p COM3 --set StoreName="My Shop" --set DocumentNumbe
23- Checkbox params (`$[Name]`): use `true`/`false` (also `1`/`0`, `yes`/`no`).
25- Checkbox params (`$[Name]`): use `true`/`false` (also `1`/`0`, `yes`/`no`).
24- If any text `${Name}` is missing or empty, or a `$[Name]` is omitted / not a boolean, the command **fails**.
26- If any text `${Name}` is missing or empty, or a `$[Name]` is omitted / not a boolean, the command **fails**.
25- The GUI is not started when using the `print` subcommand.
27- The GUI is not started when using the `print` subcommand.
28- **`posprint link`** encodes the `.pos` file as a `posprint://` URL on stdout (see [POSPRINT-URL.md](POSPRINT-URL.md)). Warns if the URL is very long.
26
29
27## Examples
30## Examples
28
31
@@ -53,7 +56,8 @@ posprint print C:\receipts\sale.pos -p COM3 `
53
56
54```powershell
57```powershell
55posprint print --help
58posprint print --help
59posprint link --help
56posprint --help
60posprint --help
57```
61```
58
62
59Launch the graphical designer by running `posprint` with **no** subcommand.
63Launch the graphical designer by running `posprint` with **no** subcommand. Opening a `posprint://…` URL (from a browser) starts the print dialog only.
docs/HELP.md +20 −0
@@ -159,9 +159,12 @@ Blank lines in the editor also feed one line (same as `@feed 1`).
159 159
160 160 ```markdown
161 161 @image logo.png
162 @image https://example.com/logo.png width=50%
162 163 @image ${LogoPath} width=50% align=center
163 164 ```
164 165
166 Local paths resolve relative to the `.pos` file. `http://` and `https://` URLs are downloaded when preview or print needs the image.
167
165 168 ### Barcode
166 169
167 170 **Native** (printer draws barcode via ESC/POS):
@@ -283,11 +286,28 @@ Printers may appear as:
283 286
284 287 ```bash
285 288 posprint print receipt.pos -p COM3 --set StoreName=Shop
289 posprint link receipt.pos
286 290 posprint cli-help
287 291 ```
288 292
289 293 `-p` accepts a serial port name, USB device label from discovery, or (on Windows) a spooler queue name. See platform CLI help via `posprint cli-help`.
290 294
295 `posprint link` prints a `posprint://` deep link for the file (see [POSPRINT-URL.md](POSPRINT-URL.md)).
296
297 ---
298
299 ## posprint:// links
300
301 Websites can open the print dialog with an embedded template:
302
303 ```
304 posprint://print?v=1&d=…
305 ```
306
307 Encoding helpers live in [`lib/`](../lib/). Full guide: [POSPRINT-URL.md](POSPRINT-URL.md).
308
309 `@image` may use `https://…` or `http://…` (downloaded when preview/print needs the image).
310
291 311 ---
292 312
293 313 ## `.pos` file format
@@ -159,9 +159,12 @@ Blank lines in the editor also feed one line (same as `@feed 1`).
159
159
160```markdown
160```markdown
161@image logo.png
161@image logo.png
162@image https://example.com/logo.png width=50%
162@image ${LogoPath} width=50% align=center
163@image ${LogoPath} width=50% align=center
163```
164```
164
165
166Local paths resolve relative to the `.pos` file. `http://` and `https://` URLs are downloaded when preview or print needs the image.
167
165### Barcode
168### Barcode
166
169
167**Native** (printer draws barcode via ESC/POS):
170**Native** (printer draws barcode via ESC/POS):
@@ -283,11 +286,28 @@ Printers may appear as:
283
286
284```bash
287```bash
285posprint print receipt.pos -p COM3 --set StoreName=Shop
288posprint print receipt.pos -p COM3 --set StoreName=Shop
289posprint link receipt.pos
286posprint cli-help
290posprint cli-help
287```
291```
288
292
289`-p` accepts a serial port name, USB device label from discovery, or (on Windows) a spooler queue name. See platform CLI help via `posprint cli-help`.
293`-p` accepts a serial port name, USB device label from discovery, or (on Windows) a spooler queue name. See platform CLI help via `posprint cli-help`.
290
294
295`posprint link` prints a `posprint://` deep link for the file (see [POSPRINT-URL.md](POSPRINT-URL.md)).
296
297---
298
299## posprint:// links
300
301Websites can open the print dialog with an embedded template:
302
303```
304posprint://print?v=1&d=…
305```
306
307Encoding helpers live in [`lib/`](../lib/). Full guide: [POSPRINT-URL.md](POSPRINT-URL.md).
308
309`@image` may use `https://…` or `http://…` (downloaded when preview/print needs the image).
310
291---
311---
292
312
293## `.pos` file format
313## `.pos` file format
docs/POSPRINT-URL.md added +141 −0
@@ -0,0 +1,141 @@
1 # posprint:// URLs
2
3 Magnet-style deep links that open **posprint’s print dialog** with an embedded `.pos` document. Useful from websites where posprint is installed on the client, not on the server.
4
5 Full reference: create URLs from PHP, Node.js, or browser JavaScript using the helpers in [`lib/`](../lib/).
6
7 ---
8
9 ## Format
10
11 ```
12 posprint://print?v=1&d=<BASE64URL(raw_deflate(utf8(.pos JSON)))>
13 ```
14
15 | Part | Meaning |
16 |------|---------|
17 | `posprint://` | Custom protocol (registered on install / first run) |
18 | `print` | Open the print-only dialog (same UX as `posprint --print`) |
19 | `v=1` | URL payload version |
20 | `d=` | Compressed `.pos` file (JSON with `version`, `metadata`, `body`) |
21
22 **Parameters are not in the URL.** The user fills `${Name}` / `$[Name]` in the dialog.
23
24 **Images:** keep logos out of the URL. Use `@image https://…` (or `http://…`) in the template body; posprint downloads them when needed.
25
26 ---
27
28 ## Size limits
29
30 Cross-platform bottleneck is usually the **Windows command line (~8191 characters)** for `"posprint.exe" "<url>"`.
31
32 | Guidance | Size |
33 |----------|------|
34 | Soft warning (`posprint link`) | ~7000 characters URL length |
35 | Practical `.pos` JSON | ~3–6 KB uncompressed (often more if it compresses well) |
36
37 Prefer short templates + remote `@image https://…` over embedding image bytes in the JSON.
38
39 ---
40
41 ## Create a URL
42
43 ### CLI
44
45 ```bash
46 posprint link receipt.pos
47 ```
48
49 Prints one `posprint://…` line. Warns if the URL is longer than ~7000 characters.
50
51 ### Libraries
52
53 | Runtime | Path |
54 |---------|------|
55 | PHP | [`lib/php/posprint_url.php`](../lib/php/posprint_url.php) |
56 | Node.js | [`lib/node/posprint_url.js`](../lib/node/posprint_url.js) |
57 | Browser | [`lib/browser/posprint_url.js`](../lib/browser/posprint_url.js) |
58
59 All three use the same encoding: **UTF-8 JSON → raw deflate (RFC 1951) → base64url (no padding)**.
60
61 #### PHP
62
63 ```php
64 require 'lib/php/posprint_url.php';
65
66 $url = posprint_url([
67 'version' => 1,
68 'metadata' => ['page_width_mm' => 53, 'chars_per_line' => 32],
69 'body' => "@barcode RASTER CODE128 \${data}\nHello\n@cut\n",
70 ]);
71 // <a href="<?= htmlspecialchars($url) ?>">Print</a>
72 ```
73
74 #### Node.js
75
76 ```js
77 const { posprintUrl } = require('./lib/node/posprint_url');
78
79 const url = posprintUrl({
80 version: 1,
81 metadata: { page_width_mm: 53, chars_per_line: 32 },
82 body: '@barcode RASTER CODE128 ${data}\nHello\n@cut\n',
83 });
84 ```
85
86 #### Browser
87
88 ```html
89 <script type="module">
90 import { posprintUrl } from './lib/browser/posprint_url.js';
91 const url = await posprintUrl({
92 version: 1,
93 metadata: { page_width_mm: 53 },
94 body: '@barcode RASTER CODE128 ${data}\nHello\n@cut\n',
95 });
96 location.href = url;
97 </script>
98 ```
99
100 `CompressionStream('deflate-raw')` is required (modern Chromium / Firefox / Safari).
101
102 ---
103
104 ## Protocol registration
105
106 | Platform | How |
107 |----------|-----|
108 | **Windows** | On each launch, posprint registers `HKCU\Software\Classes\posprint` → `"<exe>" "%1"` |
109 | **Linux (deb/Arch)** | Ships `posprint-url.desktop` with `MimeType=x-scheme-handler/posprint` |
110
111 After a Linux package install, if links do not open:
112
113 ```bash
114 xdg-mime default posprint-url.desktop x-scheme-handler/posprint
115 ```
116
117 Run the GUI once (or any `posprint` launch) on Windows so the registry key exists.
118
119 ---
120
121 ## Example template body
122
123 ```markdown
124 @barcode RASTER CODE128 ${data}
125 Hello from posprint://
126 @cut
127 ```
128
129 Corresponding minimal `.pos` JSON:
130
131 ```json
132 {
133 "version": 1,
134 "metadata": {
135 "title": "URL demo",
136 "page_width_mm": 53,
137 "chars_per_line": 32
138 },
139 "body": "@barcode RASTER CODE128 ${data}\nHello from posprint://\n@cut\n"
140 }
141 ```
@@ -0,0 +1,141 @@
1# posprint:// URLs
2
3Magnet-style deep links that open **posprint’s print dialog** with an embedded `.pos` document. Useful from websites where posprint is installed on the client, not on the server.
4
5Full reference: create URLs from PHP, Node.js, or browser JavaScript using the helpers in [`lib/`](../lib/).
6
7---
8
9## Format
10
11```
12posprint://print?v=1&d=<BASE64URL(raw_deflate(utf8(.pos JSON)))>
13```
14
15| Part | Meaning |
16|------|---------|
17| `posprint://` | Custom protocol (registered on install / first run) |
18| `print` | Open the print-only dialog (same UX as `posprint --print`) |
19| `v=1` | URL payload version |
20| `d=` | Compressed `.pos` file (JSON with `version`, `metadata`, `body`) |
21
22**Parameters are not in the URL.** The user fills `${Name}` / `$[Name]` in the dialog.
23
24**Images:** keep logos out of the URL. Use `@image https://…` (or `http://…`) in the template body; posprint downloads them when needed.
25
26---
27
28## Size limits
29
30Cross-platform bottleneck is usually the **Windows command line (~8191 characters)** for `"posprint.exe" "<url>"`.
31
32| Guidance | Size |
33|----------|------|
34| Soft warning (`posprint link`) | ~7000 characters URL length |
35| Practical `.pos` JSON | ~3–6 KB uncompressed (often more if it compresses well) |
36
37Prefer short templates + remote `@image https://…` over embedding image bytes in the JSON.
38
39---
40
41## Create a URL
42
43### CLI
44
45```bash
46posprint link receipt.pos
47```
48
49Prints one `posprint://…` line. Warns if the URL is longer than ~7000 characters.
50
51### Libraries
52
53| Runtime | Path |
54|---------|------|
55| PHP | [`lib/php/posprint_url.php`](../lib/php/posprint_url.php) |
56| Node.js | [`lib/node/posprint_url.js`](../lib/node/posprint_url.js) |
57| Browser | [`lib/browser/posprint_url.js`](../lib/browser/posprint_url.js) |
58
59All three use the same encoding: **UTF-8 JSON → raw deflate (RFC 1951) → base64url (no padding)**.
60
61#### PHP
62
63```php
64require 'lib/php/posprint_url.php';
65
66$url = posprint_url([
67 'version' => 1,
68 'metadata' => ['page_width_mm' => 53, 'chars_per_line' => 32],
69 'body' => "@barcode RASTER CODE128 \${data}\nHello\n@cut\n",
70]);
71// <a href="<?= htmlspecialchars($url) ?>">Print</a>
72```
73
74#### Node.js
75
76```js
77const { posprintUrl } = require('./lib/node/posprint_url');
78
79const url = posprintUrl({
80 version: 1,
81 metadata: { page_width_mm: 53, chars_per_line: 32 },
82 body: '@barcode RASTER CODE128 ${data}\nHello\n@cut\n',
83});
84```
85
86#### Browser
87
88```html
89<script type="module">
90 import { posprintUrl } from './lib/browser/posprint_url.js';
91 const url = await posprintUrl({
92 version: 1,
93 metadata: { page_width_mm: 53 },
94 body: '@barcode RASTER CODE128 ${data}\nHello\n@cut\n',
95 });
96 location.href = url;
97</script>
98```
99
100`CompressionStream('deflate-raw')` is required (modern Chromium / Firefox / Safari).
101
102---
103
104## Protocol registration
105
106| Platform | How |
107|----------|-----|
108| **Windows** | On each launch, posprint registers `HKCU\Software\Classes\posprint` → `"<exe>" "%1"` |
109| **Linux (deb/Arch)** | Ships `posprint-url.desktop` with `MimeType=x-scheme-handler/posprint` |
110
111After a Linux package install, if links do not open:
112
113```bash
114xdg-mime default posprint-url.desktop x-scheme-handler/posprint
115```
116
117Run the GUI once (or any `posprint` launch) on Windows so the registry key exists.
118
119---
120
121## Example template body
122
123```markdown
124@barcode RASTER CODE128 ${data}
125Hello from posprint://
126@cut
127```
128
129Corresponding minimal `.pos` JSON:
130
131```json
132{
133 "version": 1,
134 "metadata": {
135 "title": "URL demo",
136 "page_width_mm": 53,
137 "chars_per_line": 32
138 },
139 "body": "@barcode RASTER CODE128 ${data}\nHello from posprint://\n@cut\n"
140}
141```
docs/PRINTING.md +3 −1
@@ -145,13 +145,15 @@ Status polling (paper out, cover open) is **not** implemented.
145 145
146 146 ## Images and rasters
147 147
148 1. Resolve path relative to the `.pos` file (or absolute).
148 1. If the path is `http://` or `https://`, download (timeout + size limit, process cache); otherwise resolve relative to the `.pos` file (or absolute).
149 149 2. Decode with `image`, convert to luma, scale to printable width (`chars_per_line × 12` dots).
150 150 3. Threshold to 1-bit; emit `GS v 0` (`1D 76 30 00` + width/height LE + bitmap).
151 151 4. Append **LF** after the raster so following content (including blank-line feeds) advances correctly.
152 152
153 153 Preview draws the same bitmaps on the canvas (scaled for screen).
154 154
155 `posprint://` print links embed the `.pos` JSON in the URL; use remote `@image https://…` for logos. See [POSPRINT-URL.md](POSPRINT-URL.md).
156
155 157 ---
156 158
157 159 ## Testing without hardware
@@ -145,13 +145,15 @@ Status polling (paper out, cover open) is **not** implemented.
145
145
146## Images and rasters
146## Images and rasters
147
147
1481. Resolve path relative to the `.pos` file (or absolute).
1481. If the path is `http://` or `https://`, download (timeout + size limit, process cache); otherwise resolve relative to the `.pos` file (or absolute).
1492. Decode with `image`, convert to luma, scale to printable width (`chars_per_line × 12` dots).
1492. Decode with `image`, convert to luma, scale to printable width (`chars_per_line × 12` dots).
1503. Threshold to 1-bit; emit `GS v 0` (`1D 76 30 00` + width/height LE + bitmap).
1503. Threshold to 1-bit; emit `GS v 0` (`1D 76 30 00` + width/height LE + bitmap).
1514. Append **LF** after the raster so following content (including blank-line feeds) advances correctly.
1514. Append **LF** after the raster so following content (including blank-line feeds) advances correctly.
152
152
153Preview draws the same bitmaps on the canvas (scaled for screen).
153Preview draws the same bitmaps on the canvas (scaled for screen).
154
154
155`posprint://` print links embed the `.pos` JSON in the URL; use remote `@image https://…` for logos. See [POSPRINT-URL.md](POSPRINT-URL.md).
156
155---
157---
156
158
157## Testing without hardware
159## Testing without hardware
examples/url-demo.pos added +9 −0
@@ -0,0 +1,9 @@
1 {
2 "version": 1,
3 "metadata": {
4 "title": "URL demo",
5 "page_width_mm": 53.0,
6 "chars_per_line": 32
7 },
8 "body": "@barcode RASTER CODE128 ${data}\nHello from posprint://\n@cut\n"
9 }
@@ -0,0 +1,9 @@
1{
2 "version": 1,
3 "metadata": {
4 "title": "URL demo",
5 "page_width_mm": 53.0,
6 "chars_per_line": 32
7 },
8 "body": "@barcode RASTER CODE128 ${data}\nHello from posprint://\n@cut\n"
9}
lib/README.md added +13 −0
@@ -0,0 +1,13 @@
1 # posprint URL helper libraries
2
3 Small helpers that turn a `.pos` document into a `posprint://` deep link.
4
5 See [docs/POSPRINT-URL.md](../docs/POSPRINT-URL.md) for the full URL format and size limits.
6
7 | Folder | Runtime |
8 |--------|---------|
9 | [`php/`](php/) | PHP (`gzdeflate`) |
10 | [`node/`](node/) | Node.js (`zlib.deflateRawSync`) |
11 | [`browser/`](browser/) | ES module (`CompressionStream('deflate-raw')`) |
12
13 All implementations must stay byte-compatible with Rust `src/protocol_url.rs`.
@@ -0,0 +1,13 @@
1# posprint URL helper libraries
2
3Small helpers that turn a `.pos` document into a `posprint://` deep link.
4
5See [docs/POSPRINT-URL.md](../docs/POSPRINT-URL.md) for the full URL format and size limits.
6
7| Folder | Runtime |
8|--------|---------|
9| [`php/`](php/) | PHP (`gzdeflate`) |
10| [`node/`](node/) | Node.js (`zlib.deflateRawSync`) |
11| [`browser/`](browser/) | ES module (`CompressionStream('deflate-raw')`) |
12
13All implementations must stay byte-compatible with Rust `src/protocol_url.rs`.
lib/browser/posprint_url.js added +29 −0
@@ -0,0 +1,29 @@
1 /**
2 * Build a posprint:// URL from a .pos document (object or JSON string).
3 *
4 * Encoding: UTF-8 JSON → raw deflate → base64url (no padding).
5 * Requires CompressionStream('deflate-raw') (modern browsers).
6 *
7 * @param {object|string} pos
8 * @returns {Promise<string>}
9 */
10 export async function posprintUrl(pos) {
11 const json = typeof pos === 'string' ? pos : JSON.stringify(pos);
12 if (typeof CompressionStream === 'undefined') {
13 throw new Error("CompressionStream('deflate-raw') is not available in this browser");
14 }
15
16 const stream = new Blob([json]).stream().pipeThrough(new CompressionStream('deflate-raw'));
17 const buffer = await new Response(stream).arrayBuffer();
18 const b64 = bytesToBase64Url(new Uint8Array(buffer));
19 return `posprint://print?v=1&d=${b64}`;
20 }
21
22 function bytesToBase64Url(bytes) {
23 let binary = '';
24 for (let i = 0; i < bytes.length; i++) {
25 binary += String.fromCharCode(bytes[i]);
26 }
27 const b64 = btoa(binary);
28 return b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, '');
29 }
@@ -0,0 +1,29 @@
1/**
2 * Build a posprint:// URL from a .pos document (object or JSON string).
3 *
4 * Encoding: UTF-8 JSON → raw deflate → base64url (no padding).
5 * Requires CompressionStream('deflate-raw') (modern browsers).
6 *
7 * @param {object|string} pos
8 * @returns {Promise<string>}
9 */
10export async function posprintUrl(pos) {
11 const json = typeof pos === 'string' ? pos : JSON.stringify(pos);
12 if (typeof CompressionStream === 'undefined') {
13 throw new Error("CompressionStream('deflate-raw') is not available in this browser");
14 }
15
16 const stream = new Blob([json]).stream().pipeThrough(new CompressionStream('deflate-raw'));
17 const buffer = await new Response(stream).arrayBuffer();
18 const b64 = bytesToBase64Url(new Uint8Array(buffer));
19 return `posprint://print?v=1&d=${b64}`;
20}
21
22function bytesToBase64Url(bytes) {
23 let binary = '';
24 for (let i = 0; i < bytes.length; i++) {
25 binary += String.fromCharCode(bytes[i]);
26 }
27 const b64 = btoa(binary);
28 return b64.replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/g, '');
29}
lib/node/posprint_url.js added +20 −0
@@ -0,0 +1,20 @@
1 'use strict';
2
3 const zlib = require('zlib');
4
5 /**
6 * Build a posprint:// URL from a .pos document (object or JSON string).
7 *
8 * Encoding: UTF-8 JSON → raw deflate → base64url (no padding).
9 *
10 * @param {object|string} pos
11 * @returns {string}
12 */
13 function posprintUrl(pos) {
14 const json = typeof pos === 'string' ? pos : JSON.stringify(pos);
15 const compressed = zlib.deflateRawSync(Buffer.from(json, 'utf8'), { level: 9 });
16 const b64 = compressed.toString('base64url');
17 return `posprint://print?v=1&d=${b64}`;
18 }
19
20 module.exports = { posprintUrl };
@@ -0,0 +1,20 @@
1'use strict';
2
3const zlib = require('zlib');
4
5/**
6 * Build a posprint:// URL from a .pos document (object or JSON string).
7 *
8 * Encoding: UTF-8 JSON → raw deflate → base64url (no padding).
9 *
10 * @param {object|string} pos
11 * @returns {string}
12 */
13function posprintUrl(pos) {
14 const json = typeof pos === 'string' ? pos : JSON.stringify(pos);
15 const compressed = zlib.deflateRawSync(Buffer.from(json, 'utf8'), { level: 9 });
16 const b64 = compressed.toString('base64url');
17 return `posprint://print?v=1&d=${b64}`;
18}
19
20module.exports = { posprintUrl };
lib/php/posprint_url.php added +31 −0
@@ -0,0 +1,31 @@
1 <?php
2 /**
3 * Build a posprint:// URL from a .pos document (array or JSON string).
4 *
5 * Encoding: UTF-8 JSON → raw deflate (gzdeflate) → base64url (no padding).
6 *
7 * @param array|string $pos PosFile as associative array or JSON string
8 * @return string posprint://print?v=1&d=…
9 * @throws InvalidArgumentException
10 */
11 function posprint_url($pos): string
12 {
13 if (is_array($pos)) {
14 $json = json_encode($pos, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
15 if ($json === false) {
16 throw new InvalidArgumentException('json_encode failed: ' . json_last_error_msg());
17 }
18 } elseif (is_string($pos)) {
19 $json = $pos;
20 } else {
21 throw new InvalidArgumentException('pos must be array or JSON string');
22 }
23
24 $compressed = gzdeflate($json, 9);
25 if ($compressed === false) {
26 throw new InvalidArgumentException('gzdeflate failed');
27 }
28
29 $b64 = rtrim(strtr(base64_encode($compressed), '+/', '-_'), '=');
30 return 'posprint://print?v=1&d=' . $b64;
31 }
@@ -0,0 +1,31 @@
1<?php
2/**
3 * Build a posprint:// URL from a .pos document (array or JSON string).
4 *
5 * Encoding: UTF-8 JSON → raw deflate (gzdeflate) → base64url (no padding).
6 *
7 * @param array|string $pos PosFile as associative array or JSON string
8 * @return string posprint://print?v=1&d=…
9 * @throws InvalidArgumentException
10 */
11function posprint_url($pos): string
12{
13 if (is_array($pos)) {
14 $json = json_encode($pos, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE);
15 if ($json === false) {
16 throw new InvalidArgumentException('json_encode failed: ' . json_last_error_msg());
17 }
18 } elseif (is_string($pos)) {
19 $json = $pos;
20 } else {
21 throw new InvalidArgumentException('pos must be array or JSON string');
22 }
23
24 $compressed = gzdeflate($json, 9);
25 if ($compressed === false) {
26 throw new InvalidArgumentException('gzdeflate failed');
27 }
28
29 $b64 = rtrim(strtr(base64_encode($compressed), '+/', '-_'), '=');
30 return 'posprint://print?v=1&d=' . $b64;
31}
packaging/arch/PKGBUILD +1 −0
@@ -47,6 +47,7 @@ package() {
47 47 install -Dm644 LICENSE "$pkgdir/usr/share/licenses/$pkgname/LICENSE"
48 48 install -Dm644 README.md "$pkgdir/usr/share/doc/$pkgname/README.md"
49 49 install -Dm644 packaging/posprint.desktop "$pkgdir/usr/share/applications/posprint.desktop"
50 install -Dm644 packaging/posprint-url.desktop "$pkgdir/usr/share/applications/posprint-url.desktop"
50 51 install -Dm644 packaging/mime/posprint.xml "$pkgdir/usr/share/mime/packages/posprint.xml"
51 52 install -Dm644 packaging/linux/posprint-print.desktop "$pkgdir/usr/share/kio/servicemenus/posprint-print.desktop"
52 53 install -Dm644 packaging/linux/posprint-print-thunar.xml "$pkgdir/usr/share/thunar/uca/posprint-print.xml"
@@ -47,6 +47,7 @@ package() {
47 install -Dm644 LICENSE "$pkgdir/usr/share/licenses/$pkgname/LICENSE"
47 install -Dm644 LICENSE "$pkgdir/usr/share/licenses/$pkgname/LICENSE"
48 install -Dm644 README.md "$pkgdir/usr/share/doc/$pkgname/README.md"
48 install -Dm644 README.md "$pkgdir/usr/share/doc/$pkgname/README.md"
49 install -Dm644 packaging/posprint.desktop "$pkgdir/usr/share/applications/posprint.desktop"
49 install -Dm644 packaging/posprint.desktop "$pkgdir/usr/share/applications/posprint.desktop"
50 install -Dm644 packaging/posprint-url.desktop "$pkgdir/usr/share/applications/posprint-url.desktop"
50 install -Dm644 packaging/mime/posprint.xml "$pkgdir/usr/share/mime/packages/posprint.xml"
51 install -Dm644 packaging/mime/posprint.xml "$pkgdir/usr/share/mime/packages/posprint.xml"
51 install -Dm644 packaging/linux/posprint-print.desktop "$pkgdir/usr/share/kio/servicemenus/posprint-print.desktop"
52 install -Dm644 packaging/linux/posprint-print.desktop "$pkgdir/usr/share/kio/servicemenus/posprint-print.desktop"
52 install -Dm644 packaging/linux/posprint-print-thunar.xml "$pkgdir/usr/share/thunar/uca/posprint-print.xml"
53 install -Dm644 packaging/linux/posprint-print-thunar.xml "$pkgdir/usr/share/thunar/uca/posprint-print.xml"
packaging/posprint-url.desktop added +11 −0
@@ -0,0 +1,11 @@
1 [Desktop Entry]
2 Type=Application
3 Name=posprint URL handler
4 Comment=Open posprint:// print links
5 Exec=posprint %u
6 Icon=posprint
7 Terminal=false
8 Categories=Office;Utility;
9 MimeType=x-scheme-handler/posprint;
10 NoDisplay=true
11 StartupNotify=true
@@ -0,0 +1,11 @@
1[Desktop Entry]
2Type=Application
3Name=posprint URL handler
4Comment=Open posprint:// print links
5Exec=posprint %u
6Icon=posprint
7Terminal=false
8Categories=Office;Utility;
9MimeType=x-scheme-handler/posprint;
10NoDisplay=true
11StartupNotify=true
src/cli.rs +35 −5
@@ -3,7 +3,9 @@ use std::path::PathBuf;
3 3
4 4 use clap::{Parser, Subcommand};
5 5
6 use crate::io::PosFile;
6 7 use crate::pipeline;
8 use crate::protocol_url::{self, WARN_URL_LEN};
7 9
8 10 #[derive(Parser, Debug)]
9 11 #[command(
@@ -41,6 +43,11 @@ pub enum Commands {
41 43 #[arg(long = "set", value_name = "NAME=VALUE")]
42 44 set: Vec<String>,
43 45 },
46 /// Encode a `.pos` file as a `posprint://` URL (for websites / deep links)
47 Link {
48 /// Path to the `.pos` template file
49 file: PathBuf,
50 },
44 51 }
45 52
46 53 pub fn run(cli: Cli) -> i32 {
@@ -56,6 +63,13 @@ pub fn run(cli: Cli) -> i32 {
56 63 1
57 64 }
58 65 },
66 Some(Commands::Link { file }) => match run_link(&file) {
67 Ok(()) => 0,
68 Err(e) => {
69 eprintln!("{e}");
70 1
71 }
72 },
59 73 None => {
60 74 eprintln!(
61 75 "No subcommand specified. Run `posprint --help` or start without arguments for the GUI."
@@ -70,6 +84,19 @@ fn run_print(file: &PathBuf, printer: &str, set: &[String]) -> Result<(), String
70 84 pipeline::print_pos_file(file, printer, &params).map_err(|e| e.to_string())
71 85 }
72 86
87 fn run_link(file: &PathBuf) -> Result<(), String> {
88 let pos = PosFile::load_from_path(file).map_err(|e| format!("load failed: {e:?}"))?;
89 let url = protocol_url::encode_posprint_url(&pos).map_err(|e| e.to_string())?;
90 if url.len() > WARN_URL_LEN {
91 eprintln!(
92 "warning: URL is {} characters (soft limit ~{WARN_URL_LEN}). Windows may truncate protocol URLs near 8KB total command line.",
93 url.len()
94 );
95 }
96 println!("{url}");
97 Ok(())
98 }
99
73 100 pub fn parse_params(pairs: &[String]) -> Result<HashMap<String, String>, String> {
74 101 let mut map = HashMap::new();
75 102 for pair in pairs {
@@ -110,10 +137,13 @@ mod tests {
110 137
111 138 #[test]
112 139 fn cli_help_subcommand_prints_docs() {
113 assert_eq!(run(Cli {
114 command: Some(Commands::CliHelp),
115 print: false,
116 file: None,
117 }), 0);
140 assert_eq!(
141 run(Cli {
142 command: Some(Commands::CliHelp),
143 print: false,
144 file: None,
145 }),
146 0
147 );
118 148 }
119 149 }
@@ -3,7 +3,9 @@ use std::path::PathBuf;
3
3
4use clap::{Parser, Subcommand};
4use clap::{Parser, Subcommand};
5
5
6use crate::io::PosFile;
6use crate::pipeline;
7use crate::pipeline;
8use crate::protocol_url::{self, WARN_URL_LEN};
7
9
8#[derive(Parser, Debug)]
10#[derive(Parser, Debug)]
9#[command(
11#[command(
@@ -41,6 +43,11 @@ pub enum Commands {
41 #[arg(long = "set", value_name = "NAME=VALUE")]
43 #[arg(long = "set", value_name = "NAME=VALUE")]
42 set: Vec<String>,
44 set: Vec<String>,
43 },
45 },
46 /// Encode a `.pos` file as a `posprint://` URL (for websites / deep links)
47 Link {
48 /// Path to the `.pos` template file
49 file: PathBuf,
50 },
44}
51}
45
52
46pub fn run(cli: Cli) -> i32 {
53pub fn run(cli: Cli) -> i32 {
@@ -56,6 +63,13 @@ pub fn run(cli: Cli) -> i32 {
56 1
63 1
57 }
64 }
58 },
65 },
66 Some(Commands::Link { file }) => match run_link(&file) {
67 Ok(()) => 0,
68 Err(e) => {
69 eprintln!("{e}");
70 1
71 }
72 },
59 None => {
73 None => {
60 eprintln!(
74 eprintln!(
61 "No subcommand specified. Run `posprint --help` or start without arguments for the GUI."
75 "No subcommand specified. Run `posprint --help` or start without arguments for the GUI."
@@ -70,6 +84,19 @@ fn run_print(file: &PathBuf, printer: &str, set: &[String]) -> Result<(), String
70 pipeline::print_pos_file(file, printer, &params).map_err(|e| e.to_string())
84 pipeline::print_pos_file(file, printer, &params).map_err(|e| e.to_string())
71}
85}
72
86
87fn run_link(file: &PathBuf) -> Result<(), String> {
88 let pos = PosFile::load_from_path(file).map_err(|e| format!("load failed: {e:?}"))?;
89 let url = protocol_url::encode_posprint_url(&pos).map_err(|e| e.to_string())?;
90 if url.len() > WARN_URL_LEN {
91 eprintln!(
92 "warning: URL is {} characters (soft limit ~{WARN_URL_LEN}). Windows may truncate protocol URLs near 8KB total command line.",
93 url.len()
94 );
95 }
96 println!("{url}");
97 Ok(())
98}
99
73pub fn parse_params(pairs: &[String]) -> Result<HashMap<String, String>, String> {
100pub fn parse_params(pairs: &[String]) -> Result<HashMap<String, String>, String> {
74 let mut map = HashMap::new();
101 let mut map = HashMap::new();
75 for pair in pairs {
102 for pair in pairs {
@@ -110,10 +137,13 @@ mod tests {
110
137
111 #[test]
138 #[test]
112 fn cli_help_subcommand_prints_docs() {
139 fn cli_help_subcommand_prints_docs() {
113 assert_eq!(run(Cli {
140 assert_eq!(
114 command: Some(Commands::CliHelp),
141 run(Cli {
115 print: false,
142 command: Some(Commands::CliHelp),
116 file: None,
143 print: false,
117 }), 0);
144 file: None,
145 }),
146 0
147 );
118 }
148 }
119}
149}
src/escpos.rs +2 −13
@@ -295,8 +295,8 @@ impl EscPosEncoder {
295 295 }
296 296
297 297 fn encode_image(&mut self, path: &str, width: ImageWidth) -> Result<(), EscPosError> {
298 let resolved = resolve_image_path(path, self.base_dir.as_deref());
299 let img = image::open(&resolved).map_err(|e| EscPosError::Image(e.to_string()))?;
298 let img = crate::image_load::load_image(path, self.base_dir.as_deref())
299 .map_err(|e| EscPosError::Image(e.to_string()))?;
300 300 self.encode_gray_raster(&img.to_luma8(), width)
301 301 }
302 302
@@ -344,17 +344,6 @@ impl EscPosEncoder {
344 344 }
345 345 }
346 346
347 fn resolve_image_path(path: &str, base_dir: Option<&Path>) -> std::path::PathBuf {
348 let p = Path::new(path);
349 if p.is_absolute() {
350 p.to_path_buf()
351 } else if let Some(base) = base_dir {
352 base.join(p)
353 } else {
354 p.to_path_buf()
355 }
356 }
357
358 347 fn inlines_to_plain(inlines: &[Inline]) -> String {
359 348 let mut out = String::new();
360 349 for inline in inlines {
@@ -295,8 +295,8 @@ impl EscPosEncoder {
295 }
295 }
296
296
297 fn encode_image(&mut self, path: &str, width: ImageWidth) -> Result<(), EscPosError> {
297 fn encode_image(&mut self, path: &str, width: ImageWidth) -> Result<(), EscPosError> {
298 let resolved = resolve_image_path(path, self.base_dir.as_deref());
298 let img = crate::image_load::load_image(path, self.base_dir.as_deref())
299 let img = image::open(&resolved).map_err(|e| EscPosError::Image(e.to_string()))?;
299 .map_err(|e| EscPosError::Image(e.to_string()))?;
300 self.encode_gray_raster(&img.to_luma8(), width)
300 self.encode_gray_raster(&img.to_luma8(), width)
301 }
301 }
302
302
@@ -344,17 +344,6 @@ impl EscPosEncoder {
344 }
344 }
345}
345}
346
346
347fn resolve_image_path(path: &str, base_dir: Option<&Path>) -> std::path::PathBuf {
348 let p = Path::new(path);
349 if p.is_absolute() {
350 p.to_path_buf()
351 } else if let Some(base) = base_dir {
352 base.join(p)
353 } else {
354 p.to_path_buf()
355 }
356}
357
358fn inlines_to_plain(inlines: &[Inline]) -> String {
347fn inlines_to_plain(inlines: &[Inline]) -> String {
359 let mut out = String::new();
348 let mut out = String::new();
360 for inline in inlines {
349 for inline in inlines {
src/image_load.rs added +141 −0
@@ -0,0 +1,141 @@
1 //! Load images from local paths or `http(s)://` URLs.
2
3 use std::collections::HashMap;
4 use std::io::Read;
5 use std::path::{Path, PathBuf};
6 use std::sync::{Mutex, OnceLock};
7 use std::time::Duration;
8
9 use image::DynamicImage;
10
11 const MAX_DOWNLOAD_BYTES: u64 = 5 * 1024 * 1024;
12 const DOWNLOAD_TIMEOUT_SECS: u64 = 10;
13
14 #[derive(Debug)]
15 pub enum ImageLoadError {
16 Message(String),
17 }
18
19 impl std::fmt::Display for ImageLoadError {
20 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
21 match self {
22 Self::Message(m) => write!(f, "{m}"),
23 }
24 }
25 }
26
27 impl std::error::Error for ImageLoadError {}
28
29 fn cache() -> std::sync::MutexGuard<'static, HashMap<String, Vec<u8>>> {
30 static CACHE: OnceLock<Mutex<HashMap<String, Vec<u8>>>> = OnceLock::new();
31 CACHE
32 .get_or_init(|| Mutex::new(HashMap::new()))
33 .lock()
34 .unwrap_or_else(|e| e.into_inner())
35 }
36
37 pub fn is_http_url(path: &str) -> bool {
38 let lower = path.trim().to_ascii_lowercase();
39 lower.starts_with("https://") || lower.starts_with("http://")
40 }
41
42 /// Open a local image path or download an `http`/`https` URL (cached per process).
43 pub fn load_image(path: &str, base_dir: Option<&Path>) -> Result<DynamicImage, ImageLoadError> {
44 let path = path.trim();
45 if path.is_empty() {
46 return Err(ImageLoadError::Message("image path is empty".into()));
47 }
48
49 if is_http_url(path) {
50 let bytes = download_cached(path)?;
51 return image::load_from_memory(&bytes)
52 .map_err(|e| ImageLoadError::Message(format!("decode {path}: {e}")));
53 }
54
55 if path.contains("://") {
56 return Err(ImageLoadError::Message(format!(
57 "unsupported image URL scheme (only http/https): {path}"
58 )));
59 }
60
61 let resolved = resolve_image_path(path, base_dir);
62 image::open(&resolved).map_err(|e| ImageLoadError::Message(format!("image {path}: {e}")))
63 }
64
65 fn download_cached(url: &str) -> Result<Vec<u8>, ImageLoadError> {
66 {
67 let guard = cache();
68 if let Some(bytes) = guard.get(url) {
69 return Ok(bytes.clone());
70 }
71 }
72
73 let bytes = download(url)?;
74 cache().insert(url.to_string(), bytes.clone());
75 Ok(bytes)
76 }
77
78 fn download(url: &str) -> Result<Vec<u8>, ImageLoadError> {
79 let agent = ureq::AgentBuilder::new()
80 .timeout_connect(Duration::from_secs(DOWNLOAD_TIMEOUT_SECS))
81 .timeout_read(Duration::from_secs(DOWNLOAD_TIMEOUT_SECS))
82 .build();
83
84 let response = agent
85 .get(url)
86 .call()
87 .map_err(|e| ImageLoadError::Message(format!("download {url}: {e}")))?;
88
89 let len = response
90 .header("Content-Length")
91 .and_then(|v| v.parse::<u64>().ok());
92 if let Some(len) = len {
93 if len > MAX_DOWNLOAD_BYTES {
94 return Err(ImageLoadError::Message(format!(
95 "download {url}: Content-Length {len} exceeds {MAX_DOWNLOAD_BYTES} byte limit"
96 )));
97 }
98 }
99
100 let mut reader = response.into_reader().take(MAX_DOWNLOAD_BYTES + 1);
101 let mut bytes = Vec::new();
102 reader
103 .read_to_end(&mut bytes)
104 .map_err(|e| ImageLoadError::Message(format!("download {url}: {e}")))?;
105 if bytes.len() as u64 > MAX_DOWNLOAD_BYTES {
106 return Err(ImageLoadError::Message(format!(
107 "download {url}: response exceeds {MAX_DOWNLOAD_BYTES} byte limit"
108 )));
109 }
110 Ok(bytes)
111 }
112
113 pub fn resolve_image_path(path: &str, base_dir: Option<&Path>) -> PathBuf {
114 let p = Path::new(path);
115 if p.is_absolute() {
116 p.to_path_buf()
117 } else if let Some(base) = base_dir {
118 base.join(p)
119 } else {
120 p.to_path_buf()
121 }
122 }
123
124 #[cfg(test)]
125 mod tests {
126 use super::*;
127
128 #[test]
129 fn detects_http_urls() {
130 assert!(is_http_url("https://example.com/a.png"));
131 assert!(is_http_url("http://example.com/a.png"));
132 assert!(!is_http_url("logo.png"));
133 assert!(!is_http_url("file:///tmp/a.png"));
134 }
135
136 #[test]
137 fn rejects_non_http_schemes() {
138 let err = load_image("file:///tmp/x.png", None).unwrap_err();
139 assert!(err.to_string().contains("unsupported"));
140 }
141 }
@@ -0,0 +1,141 @@
1//! Load images from local paths or `http(s)://` URLs.
2
3use std::collections::HashMap;
4use std::io::Read;
5use std::path::{Path, PathBuf};
6use std::sync::{Mutex, OnceLock};
7use std::time::Duration;
8
9use image::DynamicImage;
10
11const MAX_DOWNLOAD_BYTES: u64 = 5 * 1024 * 1024;
12const DOWNLOAD_TIMEOUT_SECS: u64 = 10;
13
14#[derive(Debug)]
15pub enum ImageLoadError {
16 Message(String),
17}
18
19impl std::fmt::Display for ImageLoadError {
20 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
21 match self {
22 Self::Message(m) => write!(f, "{m}"),
23 }
24 }
25}
26
27impl std::error::Error for ImageLoadError {}
28
29fn cache() -> std::sync::MutexGuard<'static, HashMap<String, Vec<u8>>> {
30 static CACHE: OnceLock<Mutex<HashMap<String, Vec<u8>>>> = OnceLock::new();
31 CACHE
32 .get_or_init(|| Mutex::new(HashMap::new()))
33 .lock()
34 .unwrap_or_else(|e| e.into_inner())
35}
36
37pub fn is_http_url(path: &str) -> bool {
38 let lower = path.trim().to_ascii_lowercase();
39 lower.starts_with("https://") || lower.starts_with("http://")
40}
41
42/// Open a local image path or download an `http`/`https` URL (cached per process).
43pub fn load_image(path: &str, base_dir: Option<&Path>) -> Result<DynamicImage, ImageLoadError> {
44 let path = path.trim();
45 if path.is_empty() {
46 return Err(ImageLoadError::Message("image path is empty".into()));
47 }
48
49 if is_http_url(path) {
50 let bytes = download_cached(path)?;
51 return image::load_from_memory(&bytes)
52 .map_err(|e| ImageLoadError::Message(format!("decode {path}: {e}")));
53 }
54
55 if path.contains("://") {
56 return Err(ImageLoadError::Message(format!(
57 "unsupported image URL scheme (only http/https): {path}"
58 )));
59 }
60
61 let resolved = resolve_image_path(path, base_dir);
62 image::open(&resolved).map_err(|e| ImageLoadError::Message(format!("image {path}: {e}")))
63}
64
65fn download_cached(url: &str) -> Result<Vec<u8>, ImageLoadError> {
66 {
67 let guard = cache();
68 if let Some(bytes) = guard.get(url) {
69 return Ok(bytes.clone());
70 }
71 }
72
73 let bytes = download(url)?;
74 cache().insert(url.to_string(), bytes.clone());
75 Ok(bytes)
76}
77
78fn download(url: &str) -> Result<Vec<u8>, ImageLoadError> {
79 let agent = ureq::AgentBuilder::new()
80 .timeout_connect(Duration::from_secs(DOWNLOAD_TIMEOUT_SECS))
81 .timeout_read(Duration::from_secs(DOWNLOAD_TIMEOUT_SECS))
82 .build();
83
84 let response = agent
85 .get(url)
86 .call()
87 .map_err(|e| ImageLoadError::Message(format!("download {url}: {e}")))?;
88
89 let len = response
90 .header("Content-Length")
91 .and_then(|v| v.parse::<u64>().ok());
92 if let Some(len) = len {
93 if len > MAX_DOWNLOAD_BYTES {
94 return Err(ImageLoadError::Message(format!(
95 "download {url}: Content-Length {len} exceeds {MAX_DOWNLOAD_BYTES} byte limit"
96 )));
97 }
98 }
99
100 let mut reader = response.into_reader().take(MAX_DOWNLOAD_BYTES + 1);
101 let mut bytes = Vec::new();
102 reader
103 .read_to_end(&mut bytes)
104 .map_err(|e| ImageLoadError::Message(format!("download {url}: {e}")))?;
105 if bytes.len() as u64 > MAX_DOWNLOAD_BYTES {
106 return Err(ImageLoadError::Message(format!(
107 "download {url}: response exceeds {MAX_DOWNLOAD_BYTES} byte limit"
108 )));
109 }
110 Ok(bytes)
111}
112
113pub fn resolve_image_path(path: &str, base_dir: Option<&Path>) -> PathBuf {
114 let p = Path::new(path);
115 if p.is_absolute() {
116 p.to_path_buf()
117 } else if let Some(base) = base_dir {
118 base.join(p)
119 } else {
120 p.to_path_buf()
121 }
122}
123
124#[cfg(test)]
125mod tests {
126 use super::*;
127
128 #[test]
129 fn detects_http_urls() {
130 assert!(is_http_url("https://example.com/a.png"));
131 assert!(is_http_url("http://example.com/a.png"));
132 assert!(!is_http_url("logo.png"));
133 assert!(!is_http_url("file:///tmp/a.png"));
134 }
135
136 #[test]
137 fn rejects_non_http_schemes() {
138 let err = load_image("file:///tmp/x.png", None).unwrap_err();
139 assert!(err.to_string().contains("unsupported"));
140 }
141}
src/io/mod.rs +2 −1
@@ -54,7 +54,8 @@ impl PosFile {
54 54
55 55 pub fn load_from_path(path: &std::path::Path) -> Result<Self, LoadError> {
56 56 let json = std::fs::read_to_string(path)?;
57 let file = PosFile::from_json(&json).map_err(LoadError::Json)?;
57 let json = json.strip_prefix('\u{feff}').unwrap_or(&json);
58 let file = PosFile::from_json(json).map_err(LoadError::Json)?;
58 59 if file.version != 1 {
59 60 return Err(LoadError::UnsupportedVersion(file.version));
60 61 }
@@ -54,7 +54,8 @@ impl PosFile {
54
54
55 pub fn load_from_path(path: &std::path::Path) -> Result<Self, LoadError> {
55 pub fn load_from_path(path: &std::path::Path) -> Result<Self, LoadError> {
56 let json = std::fs::read_to_string(path)?;
56 let json = std::fs::read_to_string(path)?;
57 let file = PosFile::from_json(&json).map_err(LoadError::Json)?;
57 let json = json.strip_prefix('\u{feff}').unwrap_or(&json);
58 let file = PosFile::from_json(json).map_err(LoadError::Json)?;
58 if file.version != 1 {
59 if file.version != 1 {
59 return Err(LoadError::UnsupportedVersion(file.version));
60 return Err(LoadError::UnsupportedVersion(file.version));
60 }
61 }
src/lib.rs +2 −0
@@ -4,11 +4,13 @@ pub mod dsl;
4 4 pub mod editor_assist;
5 5 pub mod escpos;
6 6 pub mod help_view;
7 pub mod image_load;
7 8 pub mod io;
8 9 pub mod params;
9 10 pub mod pipeline;
10 11 pub mod preview;
11 12 pub mod print;
13 pub mod protocol_url;
12 14 pub mod raster;
13 15 pub mod text_wrap;
14 16 pub mod undo;
@@ -4,11 +4,13 @@ pub mod dsl;
4pub mod editor_assist;
4pub mod editor_assist;
5pub mod escpos;
5pub mod escpos;
6pub mod help_view;
6pub mod help_view;
7pub mod image_load;
7pub mod io;
8pub mod io;
8pub mod params;
9pub mod params;
9pub mod pipeline;
10pub mod pipeline;
10pub mod preview;
11pub mod preview;
11pub mod print;
12pub mod print;
13pub mod protocol_url;
12pub mod raster;
14pub mod raster;
13pub mod text_wrap;
15pub mod text_wrap;
14pub mod undo;
16pub mod undo;
src/main.rs +32 −6
@@ -9,6 +9,9 @@ use std::sync::Arc;
9 9
10 10 use clap::Parser;
11 11
12 use posprint::io::PosFile;
13 use posprint::protocol_url::{self, is_posprint_url};
14
12 15 fn load_viewport_icon() -> Option<Arc<eframe::egui::IconData>> {
13 16 eframe::icon_data::from_png_bytes(include_bytes!("../pos-logo.png"))
14 17 .ok()
@@ -16,7 +19,15 @@ fn load_viewport_icon() -> Option<Arc<eframe::egui::IconData>> {
16 19 }
17 20
18 21 fn main() -> eframe::Result<()> {
19 shell_integration::ensure_print_context_menu();
22 shell_integration::ensure_shell_integration();
23
24 // Protocol URLs must be handled before clap: browsers pass the full URL as argv.
25 if let Some(url) = std::env::args().nth(1).filter(|a| is_posprint_url(a)) {
26 return match protocol_url::parse_posprint_url(&url) {
27 Ok(file) => run_print_only_pos_file(file),
28 Err(e) => run_print_only_error(format!("Invalid posprint:// URL: {e}")),
29 };
30 }
20 31
21 32 let cli = posprint::cli::Cli::parse();
22 33 if cli.command.is_some() {
@@ -28,7 +39,7 @@ fn main() -> eframe::Result<()> {
28 39 eprintln!("--print requires a .pos file path");
29 40 std::process::exit(1);
30 41 };
31 return run_print_only(path);
42 return run_print_only_path(path);
32 43 }
33 44
34 45 let open_file = cli.file;
@@ -51,7 +62,24 @@ fn main() -> eframe::Result<()> {
51 62 )
52 63 }
53 64
54 fn run_print_only(path: std::path::PathBuf) -> eframe::Result<()> {
65 fn run_print_only_path(path: std::path::PathBuf) -> eframe::Result<()> {
66 run_print_only_app(print_only_app::PrintOnlyApp::new(path))
67 }
68
69 fn run_print_only_pos_file(file: PosFile) -> eframe::Result<()> {
70 let label = file
71 .metadata
72 .title
73 .clone()
74 .unwrap_or_else(|| "posprint://".into());
75 run_print_only_app(print_only_app::PrintOnlyApp::from_pos_file(file, label))
76 }
77
78 fn run_print_only_error(message: String) -> eframe::Result<()> {
79 run_print_only_app(print_only_app::PrintOnlyApp::from_error(message))
80 }
81
82 fn run_print_only_app(app: print_only_app::PrintOnlyApp) -> eframe::Result<()> {
55 83 let mut viewport = eframe::egui::ViewportBuilder::default()
56 84 .with_inner_size([440.0, 420.0])
57 85 .with_min_inner_size([380.0, 320.0]);
@@ -66,8 +94,6 @@ fn run_print_only(path: std::path::PathBuf) -> eframe::Result<()> {
66 94 eframe::run_native(
67 95 "posprint",
68 96 options,
69 Box::new(move |_cc| {
70 Ok(Box::new(print_only_app::PrintOnlyApp::new(path)) as Box<dyn eframe::App>)
71 }),
97 Box::new(move |_cc| Ok(Box::new(app) as Box<dyn eframe::App>)),
72 98 )
73 99 }
@@ -9,6 +9,9 @@ use std::sync::Arc;
9
9
10use clap::Parser;
10use clap::Parser;
11
11
12use posprint::io::PosFile;
13use posprint::protocol_url::{self, is_posprint_url};
14
12fn load_viewport_icon() -> Option<Arc<eframe::egui::IconData>> {
15fn load_viewport_icon() -> Option<Arc<eframe::egui::IconData>> {
13 eframe::icon_data::from_png_bytes(include_bytes!("../pos-logo.png"))
16 eframe::icon_data::from_png_bytes(include_bytes!("../pos-logo.png"))
14 .ok()
17 .ok()
@@ -16,7 +19,15 @@ fn load_viewport_icon() -> Option<Arc<eframe::egui::IconData>> {
16}
19}
17
20
18fn main() -> eframe::Result<()> {
21fn main() -> eframe::Result<()> {
19 shell_integration::ensure_print_context_menu();
22 shell_integration::ensure_shell_integration();
23
24 // Protocol URLs must be handled before clap: browsers pass the full URL as argv.
25 if let Some(url) = std::env::args().nth(1).filter(|a| is_posprint_url(a)) {
26 return match protocol_url::parse_posprint_url(&url) {
27 Ok(file) => run_print_only_pos_file(file),
28 Err(e) => run_print_only_error(format!("Invalid posprint:// URL: {e}")),
29 };
30 }
20
31
21 let cli = posprint::cli::Cli::parse();
32 let cli = posprint::cli::Cli::parse();
22 if cli.command.is_some() {
33 if cli.command.is_some() {
@@ -28,7 +39,7 @@ fn main() -> eframe::Result<()> {
28 eprintln!("--print requires a .pos file path");
39 eprintln!("--print requires a .pos file path");
29 std::process::exit(1);
40 std::process::exit(1);
30 };
41 };
31 return run_print_only(path);
42 return run_print_only_path(path);
32 }
43 }
33
44
34 let open_file = cli.file;
45 let open_file = cli.file;
@@ -51,7 +62,24 @@ fn main() -> eframe::Result<()> {
51 )
62 )
52}
63}
53
64
54fn run_print_only(path: std::path::PathBuf) -> eframe::Result<()> {
65fn run_print_only_path(path: std::path::PathBuf) -> eframe::Result<()> {
66 run_print_only_app(print_only_app::PrintOnlyApp::new(path))
67}
68
69fn run_print_only_pos_file(file: PosFile) -> eframe::Result<()> {
70 let label = file
71 .metadata
72 .title
73 .clone()
74 .unwrap_or_else(|| "posprint://".into());
75 run_print_only_app(print_only_app::PrintOnlyApp::from_pos_file(file, label))
76}
77
78fn run_print_only_error(message: String) -> eframe::Result<()> {
79 run_print_only_app(print_only_app::PrintOnlyApp::from_error(message))
80}
81
82fn run_print_only_app(app: print_only_app::PrintOnlyApp) -> eframe::Result<()> {
55 let mut viewport = eframe::egui::ViewportBuilder::default()
83 let mut viewport = eframe::egui::ViewportBuilder::default()
56 .with_inner_size([440.0, 420.0])
84 .with_inner_size([440.0, 420.0])
57 .with_min_inner_size([380.0, 320.0]);
85 .with_min_inner_size([380.0, 320.0]);
@@ -66,8 +94,6 @@ fn run_print_only(path: std::path::PathBuf) -> eframe::Result<()> {
66 eframe::run_native(
94 eframe::run_native(
67 "posprint",
95 "posprint",
68 options,
96 options,
69 Box::new(move |_cc| {
97 Box::new(move |_cc| Ok(Box::new(app) as Box<dyn eframe::App>)),
70 Ok(Box::new(print_only_app::PrintOnlyApp::new(path)) as Box<dyn eframe::App>)
71 }),
72 )
98 )
73}
99}
src/preview.rs +3 −15
@@ -1,5 +1,5 @@
1 1 use std::collections::HashMap;
2 use std::path::{Path, PathBuf};
2 use std::path::Path;
3 3
4 4 use image::GrayImage;
5 5
@@ -251,8 +251,7 @@ fn render_image_preview(
251 251 metadata: &PosMetadata,
252 252 base_dir: Option<&Path>,
253 253 ) -> PreviewLine {
254 let resolved = resolve_image_path(path, base_dir);
255 match image::open(&resolved) {
254 match crate::image_load::load_image(path, base_dir) {
256 255 Ok(img) => {
257 256 let gray = img.to_luma8();
258 257 let target = target_image_width(width, metadata);
@@ -263,7 +262,7 @@ fn render_image_preview(
263 262 }
264 263 }
265 264 Err(e) => PreviewLine::Error {
266 message: format!("image {path}: {e}"),
265 message: e.to_string(),
267 266 align,
268 267 },
269 268 }
@@ -304,17 +303,6 @@ fn target_image_width(width: ImageWidth, metadata: &PosMetadata) -> u32 {
304 303 }
305 304 }
306 305
307 fn resolve_image_path(path: &str, base_dir: Option<&Path>) -> PathBuf {
308 let p = Path::new(path);
309 if p.is_absolute() {
310 p.to_path_buf()
311 } else if let Some(base) = base_dir {
312 base.join(p)
313 } else {
314 p.to_path_buf()
315 }
316 }
317
318 306 /// Default ESC/POS line spacing in dots (1/6 inch at 203 DPI).
319 307 pub const PREVIEW_LINE_SPACING_DOTS: f32 = 30.0;
320 308
@@ -1,5 +1,5 @@
1use std::collections::HashMap;
1use std::collections::HashMap;
2use std::path::{Path, PathBuf};
2use std::path::Path;
3
3
4use image::GrayImage;
4use image::GrayImage;
5
5
@@ -251,8 +251,7 @@ fn render_image_preview(
251 metadata: &PosMetadata,
251 metadata: &PosMetadata,
252 base_dir: Option<&Path>,
252 base_dir: Option<&Path>,
253) -> PreviewLine {
253) -> PreviewLine {
254 let resolved = resolve_image_path(path, base_dir);
254 match crate::image_load::load_image(path, base_dir) {
255 match image::open(&resolved) {
256 Ok(img) => {
255 Ok(img) => {
257 let gray = img.to_luma8();
256 let gray = img.to_luma8();
258 let target = target_image_width(width, metadata);
257 let target = target_image_width(width, metadata);
@@ -263,7 +262,7 @@ fn render_image_preview(
263 }
262 }
264 }
263 }
265 Err(e) => PreviewLine::Error {
264 Err(e) => PreviewLine::Error {
266 message: format!("image {path}: {e}"),
265 message: e.to_string(),
267 align,
266 align,
268 },
267 },
269 }
268 }
@@ -304,17 +303,6 @@ fn target_image_width(width: ImageWidth, metadata: &PosMetadata) -> u32 {
304 }
303 }
305}
304}
306
305
307fn resolve_image_path(path: &str, base_dir: Option<&Path>) -> PathBuf {
308 let p = Path::new(path);
309 if p.is_absolute() {
310 p.to_path_buf()
311 } else if let Some(base) = base_dir {
312 base.join(p)
313 } else {
314 p.to_path_buf()
315 }
316}
317
318/// Default ESC/POS line spacing in dots (1/6 inch at 203 DPI).
306/// Default ESC/POS line spacing in dots (1/6 inch at 203 DPI).
319pub const PREVIEW_LINE_SPACING_DOTS: f32 = 30.0;
307pub const PREVIEW_LINE_SPACING_DOTS: f32 = 30.0;
320
308
src/print_only_app.rs +41 −4
@@ -11,7 +11,9 @@ use crate::print_dialog::{PrintDialog, PrintDialogAction, PrintExecuteResult};
11 11 pub struct PrintOnlyApp {
12 12 body: String,
13 13 metadata: PosMetadata,
14 file_path: PathBuf,
14 /// When set, used as title and as `@image` base directory parent.
15 file_path: Option<PathBuf>,
16 title_override: Option<String>,
15 17 dialog: PrintDialog,
16 18 fatal_error: Option<String>,
17 19 exit_requested: bool,
@@ -22,7 +24,8 @@ impl PrintOnlyApp {
22 24 let mut app = Self {
23 25 body: String::new(),
24 26 metadata: PosMetadata::default(),
25 file_path: path.clone(),
27 file_path: Some(path.clone()),
28 title_override: None,
26 29 dialog: PrintDialog::default(),
27 30 fatal_error: None,
28 31 exit_requested: false,
@@ -42,10 +45,42 @@ impl PrintOnlyApp {
42 45 app
43 46 }
44 47
48 pub fn from_pos_file(file: PosFile, source_label: impl Into<String>) -> Self {
49 let mut app = Self {
50 body: file.body,
51 metadata: file.metadata,
52 file_path: None,
53 title_override: Some(source_label.into()),
54 dialog: PrintDialog::default(),
55 fatal_error: None,
56 exit_requested: false,
57 };
58 if let Err(e) = app.dialog.prepare(&app.body) {
59 app.fatal_error = Some(e);
60 }
61 app
62 }
63
64 pub fn from_error(message: impl Into<String>) -> Self {
65 Self {
66 body: String::new(),
67 metadata: PosMetadata::default(),
68 file_path: None,
69 title_override: Some("posprint://".into()),
70 dialog: PrintDialog::default(),
71 fatal_error: Some(message.into()),
72 exit_requested: false,
73 }
74 }
75
45 76 fn title(&self) -> String {
77 if let Some(label) = &self.title_override {
78 return format!("Print — {label}");
79 }
46 80 let name = self
47 81 .file_path
48 .file_name()
82 .as_ref()
83 .and_then(|p| p.file_name())
49 84 .map(|s| s.to_string_lossy().to_string())
50 85 .unwrap_or_else(|| "Print".into());
51 86 format!("Print — {name}")
@@ -88,7 +123,9 @@ impl eframe::App for PrintOnlyApp {
88 123 match self.dialog.show_ui(ui, "Cancel") {
89 124 PrintDialogAction::Cancel => self.request_exit(),
90 125 PrintDialogAction::Print => {
91 if self.dialog.execute_print(&self.body, &self.metadata, Some(&self.file_path))
126 if self
127 .dialog
128 .execute_print(&self.body, &self.metadata, self.file_path.as_ref())
92 129 == PrintExecuteResult::Printed
93 130 {
94 131 self.request_exit();
@@ -11,7 +11,9 @@ use crate::print_dialog::{PrintDialog, PrintDialogAction, PrintExecuteResult};
11pub struct PrintOnlyApp {
11pub struct PrintOnlyApp {
12 body: String,
12 body: String,
13 metadata: PosMetadata,
13 metadata: PosMetadata,
14 file_path: PathBuf,
14 /// When set, used as title and as `@image` base directory parent.
15 file_path: Option<PathBuf>,
16 title_override: Option<String>,
15 dialog: PrintDialog,
17 dialog: PrintDialog,
16 fatal_error: Option<String>,
18 fatal_error: Option<String>,
17 exit_requested: bool,
19 exit_requested: bool,
@@ -22,7 +24,8 @@ impl PrintOnlyApp {
22 let mut app = Self {
24 let mut app = Self {
23 body: String::new(),
25 body: String::new(),
24 metadata: PosMetadata::default(),
26 metadata: PosMetadata::default(),
25 file_path: path.clone(),
27 file_path: Some(path.clone()),
28 title_override: None,
26 dialog: PrintDialog::default(),
29 dialog: PrintDialog::default(),
27 fatal_error: None,
30 fatal_error: None,
28 exit_requested: false,
31 exit_requested: false,
@@ -42,10 +45,42 @@ impl PrintOnlyApp {
42 app
45 app
43 }
46 }
44
47
48 pub fn from_pos_file(file: PosFile, source_label: impl Into<String>) -> Self {
49 let mut app = Self {
50 body: file.body,
51 metadata: file.metadata,
52 file_path: None,
53 title_override: Some(source_label.into()),
54 dialog: PrintDialog::default(),
55 fatal_error: None,
56 exit_requested: false,
57 };
58 if let Err(e) = app.dialog.prepare(&app.body) {
59 app.fatal_error = Some(e);
60 }
61 app
62 }
63
64 pub fn from_error(message: impl Into<String>) -> Self {
65 Self {
66 body: String::new(),
67 metadata: PosMetadata::default(),
68 file_path: None,
69 title_override: Some("posprint://".into()),
70 dialog: PrintDialog::default(),
71 fatal_error: Some(message.into()),
72 exit_requested: false,
73 }
74 }
75
45 fn title(&self) -> String {
76 fn title(&self) -> String {
77 if let Some(label) = &self.title_override {
78 return format!("Print — {label}");
79 }
46 let name = self
80 let name = self
47 .file_path
81 .file_path
48 .file_name()
82 .as_ref()
83 .and_then(|p| p.file_name())
49 .map(|s| s.to_string_lossy().to_string())
84 .map(|s| s.to_string_lossy().to_string())
50 .unwrap_or_else(|| "Print".into());
85 .unwrap_or_else(|| "Print".into());
51 format!("Print — {name}")
86 format!("Print — {name}")
@@ -88,7 +123,9 @@ impl eframe::App for PrintOnlyApp {
88 match self.dialog.show_ui(ui, "Cancel") {
123 match self.dialog.show_ui(ui, "Cancel") {
89 PrintDialogAction::Cancel => self.request_exit(),
124 PrintDialogAction::Cancel => self.request_exit(),
90 PrintDialogAction::Print => {
125 PrintDialogAction::Print => {
91 if self.dialog.execute_print(&self.body, &self.metadata, Some(&self.file_path))
126 if self
127 .dialog
128 .execute_print(&self.body, &self.metadata, self.file_path.as_ref())
92 == PrintExecuteResult::Printed
129 == PrintExecuteResult::Printed
93 {
130 {
94 self.request_exit();
131 self.request_exit();
src/protocol_url.rs added +228 −0
@@ -0,0 +1,228 @@
1 //! `posprint://` URLs that embed a compressed `.pos` document (magnet-style).
2
3 use std::fmt;
4 use std::io::{Read, Write};
5
6 use base64::engine::general_purpose::URL_SAFE_NO_PAD;
7 use base64::Engine;
8 use flate2::read::DeflateDecoder;
9 use flate2::write::DeflateEncoder;
10 use flate2::Compression;
11
12 use crate::io::PosFile;
13
14 /// Soft warning threshold for cross-platform protocol handoff (~Windows cmdline limit).
15 pub const WARN_URL_LEN: usize = 7000;
16
17 #[derive(Debug)]
18 pub enum ProtocolUrlError {
19 NotPosprintUrl,
20 UnsupportedVersion(String),
21 MissingPayload,
22 InvalidEncoding(String),
23 Base64(String),
24 Inflate(String),
25 Json(String),
26 UnsupportedPosVersion(u32),
27 }
28
29 impl fmt::Display for ProtocolUrlError {
30 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31 match self {
32 Self::NotPosprintUrl => write!(f, "not a posprint:// URL"),
33 Self::UnsupportedVersion(v) => {
34 write!(f, "unsupported URL version '{v}' (expected 1)")
35 }
36 Self::MissingPayload => write!(f, "missing document payload (d=)"),
37 Self::InvalidEncoding(e) => write!(f, "invalid URL / percent-encoding: {e}"),
38 Self::Base64(e) => write!(f, "invalid base64 payload: {e}"),
39 Self::Inflate(e) => write!(f, "decompression failed: {e}"),
40 Self::Json(e) => write!(f, "invalid .pos JSON: {e}"),
41 Self::UnsupportedPosVersion(v) => write!(f, "unsupported .pos version {v}"),
42 }
43 }
44 }
45
46 impl std::error::Error for ProtocolUrlError {}
47
48 impl From<serde_json::Error> for ProtocolUrlError {
49 fn from(value: serde_json::Error) -> Self {
50 Self::Json(value.to_string())
51 }
52 }
53
54 /// True when `s` looks like a `posprint:` / `posprint://` protocol URL.
55 pub fn is_posprint_url(s: &str) -> bool {
56 let s = s.trim();
57 let lower = s.to_ascii_lowercase();
58 lower.starts_with("posprint://") || lower.starts_with("posprint:")
59 }
60
61 /// 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> {
63 let json = serde_json::to_vec(file)?;
64 let mut encoder = DeflateEncoder::new(Vec::new(), Compression::best());
65 encoder
66 .write_all(&json)
67 .map_err(|e| ProtocolUrlError::Inflate(e.to_string()))?;
68 let compressed = encoder
69 .finish()
70 .map_err(|e| ProtocolUrlError::Inflate(e.to_string()))?;
71 let b64 = URL_SAFE_NO_PAD.encode(compressed);
72 Ok(format!("posprint://print?v=1&d={b64}"))
73 }
74
75 /// Decode a `posprint://print?v=1&d=…` URL into a [`PosFile`].
76 pub fn parse_posprint_url(url: &str) -> Result<PosFile, ProtocolUrlError> {
77 let url = url.trim();
78 if !is_posprint_url(url) {
79 return Err(ProtocolUrlError::NotPosprintUrl);
80 }
81
82 let after_scheme = url
83 .split_once(':')
84 .map(|(_, rest)| rest)
85 .ok_or(ProtocolUrlError::NotPosprintUrl)?;
86 let after_scheme = after_scheme.strip_prefix("//").unwrap_or(after_scheme);
87
88 let (path, query) = match after_scheme.split_once('?') {
89 Some((path, query)) => (path, query),
90 None => (after_scheme, ""),
91 };
92 let path = path.trim_matches('/');
93 if !path.is_empty() && !path.eq_ignore_ascii_case("print") {
94 return Err(ProtocolUrlError::InvalidEncoding(format!(
95 "unknown action '{path}' (expected print)"
96 )));
97 }
98
99 let mut version: Option<String> = None;
100 let mut payload: Option<String> = None;
101 for pair in query.split('&') {
102 if pair.is_empty() {
103 continue;
104 }
105 let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
106 let key = percent_decode_str(key)?;
107 match key.as_str() {
108 "v" => version = Some(percent_decode_str(value)?),
109 "d" => payload = Some(percent_decode_str(value)?),
110 _ => {}
111 }
112 }
113
114 match version.as_deref() {
115 None | Some("1") => {}
116 Some(other) => return Err(ProtocolUrlError::UnsupportedVersion(other.to_string())),
117 }
118
119 let payload = payload.ok_or(ProtocolUrlError::MissingPayload)?;
120 let compressed = URL_SAFE_NO_PAD
121 .decode(payload.trim())
122 .map_err(|e| ProtocolUrlError::Base64(e.to_string()))?;
123
124 let mut decoder = DeflateDecoder::new(compressed.as_slice());
125 let mut json = Vec::new();
126 decoder
127 .read_to_end(&mut json)
128 .map_err(|e| ProtocolUrlError::Inflate(e.to_string()))?;
129
130 let file: PosFile = serde_json::from_slice(&json)?;
131 if file.version != 1 {
132 return Err(ProtocolUrlError::UnsupportedPosVersion(file.version));
133 }
134 Ok(file)
135 }
136
137 fn percent_decode_str(input: &str) -> Result<String, ProtocolUrlError> {
138 let bytes = percent_decode_bytes(input.as_bytes())?;
139 String::from_utf8(bytes).map_err(|e| ProtocolUrlError::InvalidEncoding(e.to_string()))
140 }
141
142 fn percent_decode_bytes(input: &[u8]) -> Result<Vec<u8>, ProtocolUrlError> {
143 let mut out = Vec::with_capacity(input.len());
144 let mut i = 0;
145 while i < input.len() {
146 match input[i] {
147 b'+' => {
148 out.push(b' ');
149 i += 1;
150 }
151 b'%' if i + 2 < input.len() => {
152 let h = from_hex(input[i + 1])?;
153 let l = from_hex(input[i + 2])?;
154 out.push((h << 4) | l);
155 i += 3;
156 }
157 b'%' => {
158 return Err(ProtocolUrlError::InvalidEncoding(
159 "truncated percent-escape".into(),
160 ));
161 }
162 c => {
163 out.push(c);
164 i += 1;
165 }
166 }
167 }
168 Ok(out)
169 }
170
171 fn from_hex(b: u8) -> Result<u8, ProtocolUrlError> {
172 match b {
173 b'0'..=b'9' => Ok(b - b'0'),
174 b'a'..=b'f' => Ok(b - b'a' + 10),
175 b'A'..=b'F' => Ok(b - b'A' + 10),
176 _ => Err(ProtocolUrlError::InvalidEncoding(format!(
177 "invalid hex digit {}",
178 b as char
179 ))),
180 }
181 }
182
183 #[cfg(test)]
184 mod tests {
185 use super::*;
186 use crate::io::PosMetadata;
187
188 fn sample_file() -> PosFile {
189 PosFile {
190 version: 1,
191 metadata: PosMetadata {
192 title: Some("Demo".into()),
193 page_width_mm: 53.0,
194 chars_per_line: Some(32),
195 codepage: Some("CP437".into()),
196 },
197 body: "@barcode RASTER CODE128 ${data}\nHello\n@cut\n".into(),
198 }
199 }
200
201 #[test]
202 fn round_trips_pos_file() {
203 let file = sample_file();
204 let url = encode_posprint_url(&file).unwrap();
205 assert!(url.starts_with("posprint://print?v=1&d="));
206 let decoded = parse_posprint_url(&url).unwrap();
207 assert_eq!(decoded, file);
208 }
209
210 #[test]
211 fn rejects_bad_version() {
212 let err = parse_posprint_url("posprint://print?v=99&d=aa").unwrap_err();
213 assert!(matches!(err, ProtocolUrlError::UnsupportedVersion(_)));
214 }
215
216 #[test]
217 fn rejects_missing_payload() {
218 let err = parse_posprint_url("posprint://print?v=1").unwrap_err();
219 assert!(matches!(err, ProtocolUrlError::MissingPayload));
220 }
221
222 #[test]
223 fn detects_scheme() {
224 assert!(is_posprint_url("posprint://print?v=1&d=x"));
225 assert!(is_posprint_url("POSPRINT:print?v=1&d=x"));
226 assert!(!is_posprint_url("https://example.com"));
227 }
228 }
@@ -0,0 +1,228 @@
1//! `posprint://` URLs that embed a compressed `.pos` document (magnet-style).
2
3use std::fmt;
4use std::io::{Read, Write};
5
6use base64::engine::general_purpose::URL_SAFE_NO_PAD;
7use base64::Engine;
8use flate2::read::DeflateDecoder;
9use flate2::write::DeflateEncoder;
10use flate2::Compression;
11
12use crate::io::PosFile;
13
14/// Soft warning threshold for cross-platform protocol handoff (~Windows cmdline limit).
15pub const WARN_URL_LEN: usize = 7000;
16
17#[derive(Debug)]
18pub enum ProtocolUrlError {
19 NotPosprintUrl,
20 UnsupportedVersion(String),
21 MissingPayload,
22 InvalidEncoding(String),
23 Base64(String),
24 Inflate(String),
25 Json(String),
26 UnsupportedPosVersion(u32),
27}
28
29impl fmt::Display for ProtocolUrlError {
30 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
31 match self {
32 Self::NotPosprintUrl => write!(f, "not a posprint:// URL"),
33 Self::UnsupportedVersion(v) => {
34 write!(f, "unsupported URL version '{v}' (expected 1)")
35 }
36 Self::MissingPayload => write!(f, "missing document payload (d=)"),
37 Self::InvalidEncoding(e) => write!(f, "invalid URL / percent-encoding: {e}"),
38 Self::Base64(e) => write!(f, "invalid base64 payload: {e}"),
39 Self::Inflate(e) => write!(f, "decompression failed: {e}"),
40 Self::Json(e) => write!(f, "invalid .pos JSON: {e}"),
41 Self::UnsupportedPosVersion(v) => write!(f, "unsupported .pos version {v}"),
42 }
43 }
44}
45
46impl std::error::Error for ProtocolUrlError {}
47
48impl From<serde_json::Error> for ProtocolUrlError {
49 fn from(value: serde_json::Error) -> Self {
50 Self::Json(value.to_string())
51 }
52}
53
54/// True when `s` looks like a `posprint:` / `posprint://` protocol URL.
55pub fn is_posprint_url(s: &str) -> bool {
56 let s = s.trim();
57 let lower = s.to_ascii_lowercase();
58 lower.starts_with("posprint://") || lower.starts_with("posprint:")
59}
60
61/// Encode a `.pos` file as `posprint://print?v=1&d=…` (raw deflate + base64url, no padding).
62pub fn encode_posprint_url(file: &PosFile) -> Result<String, ProtocolUrlError> {
63 let json = serde_json::to_vec(file)?;
64 let mut encoder = DeflateEncoder::new(Vec::new(), Compression::best());
65 encoder
66 .write_all(&json)
67 .map_err(|e| ProtocolUrlError::Inflate(e.to_string()))?;
68 let compressed = encoder
69 .finish()
70 .map_err(|e| ProtocolUrlError::Inflate(e.to_string()))?;
71 let b64 = URL_SAFE_NO_PAD.encode(compressed);
72 Ok(format!("posprint://print?v=1&d={b64}"))
73}
74
75/// Decode a `posprint://print?v=1&d=…` URL into a [`PosFile`].
76pub fn parse_posprint_url(url: &str) -> Result<PosFile, ProtocolUrlError> {
77 let url = url.trim();
78 if !is_posprint_url(url) {
79 return Err(ProtocolUrlError::NotPosprintUrl);
80 }
81
82 let after_scheme = url
83 .split_once(':')
84 .map(|(_, rest)| rest)
85 .ok_or(ProtocolUrlError::NotPosprintUrl)?;
86 let after_scheme = after_scheme.strip_prefix("//").unwrap_or(after_scheme);
87
88 let (path, query) = match after_scheme.split_once('?') {
89 Some((path, query)) => (path, query),
90 None => (after_scheme, ""),
91 };
92 let path = path.trim_matches('/');
93 if !path.is_empty() && !path.eq_ignore_ascii_case("print") {
94 return Err(ProtocolUrlError::InvalidEncoding(format!(
95 "unknown action '{path}' (expected print)"
96 )));
97 }
98
99 let mut version: Option<String> = None;
100 let mut payload: Option<String> = None;
101 for pair in query.split('&') {
102 if pair.is_empty() {
103 continue;
104 }
105 let (key, value) = pair.split_once('=').unwrap_or((pair, ""));
106 let key = percent_decode_str(key)?;
107 match key.as_str() {
108 "v" => version = Some(percent_decode_str(value)?),
109 "d" => payload = Some(percent_decode_str(value)?),
110 _ => {}
111 }
112 }
113
114 match version.as_deref() {
115 None | Some("1") => {}
116 Some(other) => return Err(ProtocolUrlError::UnsupportedVersion(other.to_string())),
117 }
118
119 let payload = payload.ok_or(ProtocolUrlError::MissingPayload)?;
120 let compressed = URL_SAFE_NO_PAD
121 .decode(payload.trim())
122 .map_err(|e| ProtocolUrlError::Base64(e.to_string()))?;
123
124 let mut decoder = DeflateDecoder::new(compressed.as_slice());
125 let mut json = Vec::new();
126 decoder
127 .read_to_end(&mut json)
128 .map_err(|e| ProtocolUrlError::Inflate(e.to_string()))?;
129
130 let file: PosFile = serde_json::from_slice(&json)?;
131 if file.version != 1 {
132 return Err(ProtocolUrlError::UnsupportedPosVersion(file.version));
133 }
134 Ok(file)
135}
136
137fn percent_decode_str(input: &str) -> Result<String, ProtocolUrlError> {
138 let bytes = percent_decode_bytes(input.as_bytes())?;
139 String::from_utf8(bytes).map_err(|e| ProtocolUrlError::InvalidEncoding(e.to_string()))
140}
141
142fn percent_decode_bytes(input: &[u8]) -> Result<Vec<u8>, ProtocolUrlError> {
143 let mut out = Vec::with_capacity(input.len());
144 let mut i = 0;
145 while i < input.len() {
146 match input[i] {
147 b'+' => {
148 out.push(b' ');
149 i += 1;
150 }
151 b'%' if i + 2 < input.len() => {
152 let h = from_hex(input[i + 1])?;
153 let l = from_hex(input[i + 2])?;
154 out.push((h << 4) | l);
155 i += 3;
156 }
157 b'%' => {
158 return Err(ProtocolUrlError::InvalidEncoding(
159 "truncated percent-escape".into(),
160 ));
161 }
162 c => {
163 out.push(c);
164 i += 1;
165 }
166 }
167 }
168 Ok(out)
169}
170
171fn from_hex(b: u8) -> Result<u8, ProtocolUrlError> {
172 match b {
173 b'0'..=b'9' => Ok(b - b'0'),
174 b'a'..=b'f' => Ok(b - b'a' + 10),
175 b'A'..=b'F' => Ok(b - b'A' + 10),
176 _ => Err(ProtocolUrlError::InvalidEncoding(format!(
177 "invalid hex digit {}",
178 b as char
179 ))),
180 }
181}
182
183#[cfg(test)]
184mod tests {
185 use super::*;
186 use crate::io::PosMetadata;
187
188 fn sample_file() -> PosFile {
189 PosFile {
190 version: 1,
191 metadata: PosMetadata {
192 title: Some("Demo".into()),
193 page_width_mm: 53.0,
194 chars_per_line: Some(32),
195 codepage: Some("CP437".into()),
196 },
197 body: "@barcode RASTER CODE128 ${data}\nHello\n@cut\n".into(),
198 }
199 }
200
201 #[test]
202 fn round_trips_pos_file() {
203 let file = sample_file();
204 let url = encode_posprint_url(&file).unwrap();
205 assert!(url.starts_with("posprint://print?v=1&d="));
206 let decoded = parse_posprint_url(&url).unwrap();
207 assert_eq!(decoded, file);
208 }
209
210 #[test]
211 fn rejects_bad_version() {
212 let err = parse_posprint_url("posprint://print?v=99&d=aa").unwrap_err();
213 assert!(matches!(err, ProtocolUrlError::UnsupportedVersion(_)));
214 }
215
216 #[test]
217 fn rejects_missing_payload() {
218 let err = parse_posprint_url("posprint://print?v=1").unwrap_err();
219 assert!(matches!(err, ProtocolUrlError::MissingPayload));
220 }
221
222 #[test]
223 fn detects_scheme() {
224 assert!(is_posprint_url("posprint://print?v=1&d=x"));
225 assert!(is_posprint_url("POSPRINT:print?v=1&d=x"));
226 assert!(!is_posprint_url("https://example.com"));
227 }
228}
src/shell_integration.rs +46 −8
@@ -1,23 +1,25 @@
1 //! Register a Explorer / file-manager "Print" action for `.pos` templates.
1 //! Register Explorer / file-manager integration and the `posprint://` URL protocol.
2 2
3 3 /// Install or refresh shell integration (best-effort; ignores errors).
4 pub fn ensure_print_context_menu() {
4 pub fn ensure_shell_integration() {
5 5 #[cfg(windows)]
6 windows::register_print_context_menu();
6 windows::register_all();
7 7 }
8 8
9 9 #[cfg(windows)]
10 10 mod windows {
11 11 use std::path::Path;
12 12
13 pub fn register_print_context_menu() {
13 pub fn register_all() {
14 14 let Ok(exe) = std::env::current_exe() else {
15 15 return;
16 16 };
17 let Some(cmd) = print_command_for_exe(&exe) else {
18 return;
19 };
20 let _ = write_user_context_menu(&cmd);
17 if let Some(cmd) = print_command_for_exe(&exe) {
18 let _ = write_user_context_menu(&cmd);
19 }
20 if let Some(cmd) = url_command_for_exe(&exe) {
21 let _ = write_url_protocol(&cmd);
22 }
21 23 }
22 24
23 25 pub fn print_command_for_exe(exe: &Path) -> Option<String> {
@@ -28,6 +30,14 @@ mod windows {
28 30 Some(format!("\"{exe}\" --print \"%1\""))
29 31 }
30 32
33 pub fn url_command_for_exe(exe: &Path) -> Option<String> {
34 let exe = exe.to_string_lossy();
35 if exe.is_empty() {
36 return None;
37 }
38 Some(format!("\"{exe}\" \"%1\""))
39 }
40
31 41 fn write_user_context_menu(command: &str) -> Result<(), String> {
32 42 use winreg::enums::HKEY_CURRENT_USER;
33 43 use winreg::RegKey;
@@ -51,6 +61,28 @@ mod windows {
51 61 Ok(())
52 62 }
53 63
64 fn write_url_protocol(command: &str) -> Result<(), String> {
65 use winreg::enums::HKEY_CURRENT_USER;
66 use winreg::RegKey;
67
68 const ROOT: &str = r"Software\Classes\posprint";
69 const COMMAND_KEY: &str = r"Software\Classes\posprint\shell\open\command";
70
71 let hkcu = RegKey::predef(HKEY_CURRENT_USER);
72 let (root, _) = hkcu.create_subkey(ROOT).map_err(|e| e.to_string())?;
73 root.set_value("", &"URL:posprint Protocol")
74 .map_err(|e| e.to_string())?;
75 root.set_value("URL Protocol", &"")
76 .map_err(|e| e.to_string())?;
77
78 let (cmd, _) = hkcu
79 .create_subkey(COMMAND_KEY)
80 .map_err(|e| e.to_string())?;
81 cmd.set_value("", &command)
82 .map_err(|e| e.to_string())?;
83 Ok(())
84 }
85
54 86 #[cfg(test)]
55 87 mod tests {
56 88 use super::*;
@@ -60,5 +92,11 @@ mod windows {
60 92 let cmd = print_command_for_exe(Path::new(r"C:\Apps\posprint.exe")).unwrap();
61 93 assert_eq!(cmd, r#""C:\Apps\posprint.exe" --print "%1""#);
62 94 }
95
96 #[test]
97 fn builds_url_command() {
98 let cmd = url_command_for_exe(Path::new(r"C:\Apps\posprint.exe")).unwrap();
99 assert_eq!(cmd, r#""C:\Apps\posprint.exe" "%1""#);
100 }
63 101 }
64 102 }
@@ -1,23 +1,25 @@
1//! Register a Explorer / file-manager "Print" action for `.pos` templates.
1//! Register Explorer / file-manager integration and the `posprint://` URL protocol.
2
2
3/// Install or refresh shell integration (best-effort; ignores errors).
3/// Install or refresh shell integration (best-effort; ignores errors).
4pub fn ensure_print_context_menu() {
4pub fn ensure_shell_integration() {
5 #[cfg(windows)]
5 #[cfg(windows)]
6 windows::register_print_context_menu();
6 windows::register_all();
7}
7}
8
8
9#[cfg(windows)]
9#[cfg(windows)]
10mod windows {
10mod windows {
11 use std::path::Path;
11 use std::path::Path;
12
12
13 pub fn register_print_context_menu() {
13 pub fn register_all() {
14 let Ok(exe) = std::env::current_exe() else {
14 let Ok(exe) = std::env::current_exe() else {
15 return;
15 return;
16 };
16 };
17 let Some(cmd) = print_command_for_exe(&exe) else {
17 if let Some(cmd) = print_command_for_exe(&exe) {
18 return;
18 let _ = write_user_context_menu(&cmd);
19 };
19 }
20 let _ = write_user_context_menu(&cmd);
20 if let Some(cmd) = url_command_for_exe(&exe) {
21 let _ = write_url_protocol(&cmd);
22 }
21 }
23 }
22
24
23 pub fn print_command_for_exe(exe: &Path) -> Option<String> {
25 pub fn print_command_for_exe(exe: &Path) -> Option<String> {
@@ -28,6 +30,14 @@ mod windows {
28 Some(format!("\"{exe}\" --print \"%1\""))
30 Some(format!("\"{exe}\" --print \"%1\""))
29 }
31 }
30
32
33 pub fn url_command_for_exe(exe: &Path) -> Option<String> {
34 let exe = exe.to_string_lossy();
35 if exe.is_empty() {
36 return None;
37 }
38 Some(format!("\"{exe}\" \"%1\""))
39 }
40
31 fn write_user_context_menu(command: &str) -> Result<(), String> {
41 fn write_user_context_menu(command: &str) -> Result<(), String> {
32 use winreg::enums::HKEY_CURRENT_USER;
42 use winreg::enums::HKEY_CURRENT_USER;
33 use winreg::RegKey;
43 use winreg::RegKey;
@@ -51,6 +61,28 @@ mod windows {
51 Ok(())
61 Ok(())
52 }
62 }
53
63
64 fn write_url_protocol(command: &str) -> Result<(), String> {
65 use winreg::enums::HKEY_CURRENT_USER;
66 use winreg::RegKey;
67
68 const ROOT: &str = r"Software\Classes\posprint";
69 const COMMAND_KEY: &str = r"Software\Classes\posprint\shell\open\command";
70
71 let hkcu = RegKey::predef(HKEY_CURRENT_USER);
72 let (root, _) = hkcu.create_subkey(ROOT).map_err(|e| e.to_string())?;
73 root.set_value("", &"URL:posprint Protocol")
74 .map_err(|e| e.to_string())?;
75 root.set_value("URL Protocol", &"")
76 .map_err(|e| e.to_string())?;
77
78 let (cmd, _) = hkcu
79 .create_subkey(COMMAND_KEY)
80 .map_err(|e| e.to_string())?;
81 cmd.set_value("", &command)
82 .map_err(|e| e.to_string())?;
83 Ok(())
84 }
85
54 #[cfg(test)]
86 #[cfg(test)]
55 mod tests {
87 mod tests {
56 use super::*;
88 use super::*;
@@ -60,5 +92,11 @@ mod windows {
60 let cmd = print_command_for_exe(Path::new(r"C:\Apps\posprint.exe")).unwrap();
92 let cmd = print_command_for_exe(Path::new(r"C:\Apps\posprint.exe")).unwrap();
61 assert_eq!(cmd, r#""C:\Apps\posprint.exe" --print "%1""#);
93 assert_eq!(cmd, r#""C:\Apps\posprint.exe" --print "%1""#);
62 }
94 }
95
96 #[test]
97 fn builds_url_command() {
98 let cmd = url_command_for_exe(Path::new(r"C:\Apps\posprint.exe")).unwrap();
99 assert_eq!(cmd, r#""C:\Apps\posprint.exe" "%1""#);
100 }
63 }
101 }
64}
102}