fixes
@@ -79,6 +79,15 @@ version = "0.2.2"
79
79
source = "registry+https://github.com/rust-lang/crates.io-index"
80
80
checksum = "fc7eb209b1518d6bb87b283c20095f5228ecda460da70b44f0802523dea6da04"
81
81
82
[[package]]
83
name = "android_system_properties"
84
version = "0.1.5"
85
source = "registry+https://github.com/rust-lang/crates.io-index"
86
checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311"
87
dependencies = [
88
"libc",
89
]
90
82
91
[[package]]
83
92
name = "anstream"
84
93
version = "1.0.0"
@@ -516,6 +525,12 @@ dependencies = [
516
525
"syn",
517
526
]
518
527
528
[[package]]
529
name = "byteorder"
530
version = "1.5.0"
531
source = "registry+https://github.com/rust-lang/crates.io-index"
532
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
533
519
534
[[package]]
520
535
name = "byteorder-lite"
521
536
version = "0.1.0"
@@ -600,6 +615,17 @@ dependencies = [
600
615
"libc",
601
616
]
602
617
618
[[package]]
619
name = "chrono"
620
version = "0.4.45"
621
source = "registry+https://github.com/rust-lang/crates.io-index"
622
checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"
623
dependencies = [
624
"iana-time-zone",
625
"num-traits",
626
"windows-link",
627
]
628
603
629
[[package]]
604
630
name = "clap"
605
631
version = "4.6.1"
@@ -1226,6 +1252,15 @@ dependencies = [
1226
1252
"windows-link",
1227
1253
]
1228
1254
1255
[[package]]
1256
name = "getopts"
1257
version = "0.2.24"
1258
source = "registry+https://github.com/rust-lang/crates.io-index"
1259
checksum = "cfe4fbac503b8d1f88e6676011885f34b7174f46e59956bba534ba83abded4df"
1260
dependencies = [
1261
"unicode-width",
1262
]
1263
1229
1264
[[package]]
1230
1265
name = "getrandom"
1231
1266
version = "0.3.4"
@@ -1370,6 +1405,40 @@ version = "0.4.3"
1370
1405
source = "registry+https://github.com/rust-lang/crates.io-index"
1371
1406
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
1372
1407
1408
[[package]]
1409
name = "iana-time-zone"
1410
version = "0.1.65"
1411
source = "registry+https://github.com/rust-lang/crates.io-index"
1412
checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470"
1413
dependencies = [
1414
"android_system_properties",
1415
"core-foundation-sys",
1416
"iana-time-zone-haiku",
1417
"js-sys",
1418
"log",
1419
"wasm-bindgen",
1420
"windows-core",
1421
]
1422
1423
[[package]]
1424
name = "iana-time-zone-haiku"
1425
version = "0.1.2"
1426
source = "registry+https://github.com/rust-lang/crates.io-index"
1427
checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"
1428
dependencies = [
1429
"cc",
1430
]
1431
1432
[[package]]
1433
name = "ico"
1434
version = "0.4.0"
1435
source = "registry+https://github.com/rust-lang/crates.io-index"
1436
checksum = "cc50b891e4acf8fe0e71ef88ec43ad82ee07b3810ad09de10f1d01f072ed4b98"
1437
dependencies = [
1438
"byteorder",
1439
"png 0.17.16",
1440
]
1441
1373
1442
[[package]]
1374
1443
name = "icu_collections"
1375
1444
version = "2.2.0"
@@ -1487,7 +1556,7 @@ dependencies = [
1487
1556
"image-webp",
1488
1557
"moxcms",
1489
1558
"num-traits",
1490
"png",
1559
"png 0.18.1",
1491
1560
"qoi",
1492
1561
"ravif",
1493
1562
"rayon",
@@ -1720,6 +1789,18 @@ dependencies = [
1720
1789
"pkg-config",
1721
1790
]
1722
1791
1792
[[package]]
1793
name = "libusb1-sys"
1794
version = "0.7.0"
1795
source = "registry+https://github.com/rust-lang/crates.io-index"
1796
checksum = "da050ade7ac4ff1ba5379af847a10a10a8e284181e060105bf8d86960ce9ce0f"
1797
dependencies = [
1798
"cc",
1799
"libc",
1800
"pkg-config",
1801
"vcpkg",
1802
]
1803
1723
1804
[[package]]
1724
1805
name = "linux-raw-sys"
1725
1806
version = "0.4.15"
@@ -2399,6 +2480,19 @@ version = "0.2.3"
2399
2480
source = "registry+https://github.com/rust-lang/crates.io-index"
2400
2481
checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6"
2401
2482
2483
[[package]]
2484
name = "png"
2485
version = "0.17.16"
2486
source = "registry+https://github.com/rust-lang/crates.io-index"
2487
checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526"
2488
dependencies = [
2489
"bitflags 1.3.2",
2490
"crc32fast",
2491
"fdeflate",
2492
"flate2",
2493
"miniz_oxide",
2494
]
2495
2402
2496
[[package]]
2403
2497
name = "png"
2404
2498
version = "0.18.1"
@@ -2437,15 +2531,22 @@ name = "posprint"
2437
2531
version = "0.1.0"
2438
2532
dependencies = [
2439
2533
"barcoders",
2534
"chrono",
2440
2535
"clap",
2441
2536
"eframe",
2537
"ico",
2442
2538
"image",
2539
"libc",
2540
"pulldown-cmark",
2443
2541
"qrcode",
2444
2542
"rfd",
2543
"rusb",
2445
2544
"serde",
2446
2545
"serde_json",
2447
2546
"serialport",
2448
2547
"tempfile",
2548
"winreg",
2549
"winres",
2449
2550
]
2450
2551
2451
2552
[[package]]
@@ -2503,6 +2604,25 @@ dependencies = [
2503
2604
"syn",
2504
2605
]
2505
2606
2607
[[package]]
2608
name = "pulldown-cmark"
2609
version = "0.13.4"
2610
source = "registry+https://github.com/rust-lang/crates.io-index"
2611
checksum = "e9f068eba8e7071c5f9511831b44f32c740d5adf574e990f946ddb53db2f314e"
2612
dependencies = [
2613
"bitflags 2.13.0",
2614
"getopts",
2615
"memchr",
2616
"pulldown-cmark-escape",
2617
"unicase",
2618
]
2619
2620
[[package]]
2621
name = "pulldown-cmark-escape"
2622
version = "0.11.0"
2623
source = "registry+https://github.com/rust-lang/crates.io-index"
2624
checksum = "007d8adb5ddab6f8e3f491ac63566a7d5002cc7ed73901f72057943fa71ae1ae"
2625
2506
2626
[[package]]
2507
2627
name = "pulp"
2508
2628
version = "0.22.3"
@@ -2763,6 +2883,16 @@ version = "0.8.53"
2763
2883
source = "registry+https://github.com/rust-lang/crates.io-index"
2764
2884
checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4"
2765
2885
2886
[[package]]
2887
name = "rusb"
2888
version = "0.9.4"
2889
source = "registry+https://github.com/rust-lang/crates.io-index"
2890
checksum = "ab9f9ff05b63a786553a4c02943b74b34a988448671001e9a27e2f0565cc05a4"
2891
dependencies = [
2892
"libc",
2893
"libusb1-sys",
2894
]
2895
2766
2896
[[package]]
2767
2897
name = "rustc_version"
2768
2898
version = "0.4.1"
@@ -3136,6 +3266,15 @@ dependencies = [
3136
3266
"zerovec",
3137
3267
]
3138
3268
3269
[[package]]
3270
name = "toml"
3271
version = "0.5.11"
3272
source = "registry+https://github.com/rust-lang/crates.io-index"
3273
checksum = "f4f7f0dd8d50a853a531c426359045b1998f04219d88799810762cd4ad314234"
3274
dependencies = [
3275
"serde",
3276
]
3277
3139
3278
[[package]]
3140
3279
name = "toml_datetime"
3141
3280
version = "1.1.1+spec-1.1.0"
@@ -3224,6 +3363,12 @@ dependencies = [
3224
3363
"thiserror 2.0.18",
3225
3364
]
3226
3365
3366
[[package]]
3367
name = "unicase"
3368
version = "2.9.0"
3369
source = "registry+https://github.com/rust-lang/crates.io-index"
3370
checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142"
3371
3227
3372
[[package]]
3228
3373
name = "unicode-ident"
3229
3374
version = "1.0.24"
@@ -3236,6 +3381,12 @@ version = "1.13.3"
3236
3381
source = "registry+https://github.com/rust-lang/crates.io-index"
3237
3382
checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"
3238
3383
3384
[[package]]
3385
name = "unicode-width"
3386
version = "0.2.2"
3387
source = "registry+https://github.com/rust-lang/crates.io-index"
3388
checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"
3389
3239
3390
[[package]]
3240
3391
name = "url"
3241
3392
version = "2.5.8"
@@ -3289,6 +3440,12 @@ dependencies = [
3289
3440
"wasm-bindgen",
3290
3441
]
3291
3442
3443
[[package]]
3444
name = "vcpkg"
3445
version = "0.2.15"
3446
source = "registry+https://github.com/rust-lang/crates.io-index"
3447
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"
3448
3292
3449
[[package]]
3293
3450
name = "version_check"
3294
3451
version = "0.9.5"
@@ -3564,12 +3721,65 @@ version = "0.4.0"
3564
3721
source = "registry+https://github.com/rust-lang/crates.io-index"
3565
3722
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
3566
3723
3724
[[package]]
3725
name = "windows-core"
3726
version = "0.62.2"
3727
source = "registry+https://github.com/rust-lang/crates.io-index"
3728
checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"
3729
dependencies = [
3730
"windows-implement",
3731
"windows-interface",
3732
"windows-link",
3733
"windows-result",
3734
"windows-strings",
3735
]
3736
3737
[[package]]
3738
name = "windows-implement"
3739
version = "0.60.2"
3740
source = "registry+https://github.com/rust-lang/crates.io-index"
3741
checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"
3742
dependencies = [
3743
"proc-macro2",
3744
"quote",
3745
"syn",
3746
]
3747
3748
[[package]]
3749
name = "windows-interface"
3750
version = "0.59.3"
3751
source = "registry+https://github.com/rust-lang/crates.io-index"
3752
checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"
3753
dependencies = [
3754
"proc-macro2",
3755
"quote",
3756
"syn",
3757
]
3758
3567
3759
[[package]]
3568
3760
name = "windows-link"
3569
3761
version = "0.2.1"
3570
3762
source = "registry+https://github.com/rust-lang/crates.io-index"
3571
3763
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
3572
3764
3765
[[package]]
3766
name = "windows-result"
3767
version = "0.4.1"
3768
source = "registry+https://github.com/rust-lang/crates.io-index"
3769
checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"
3770
dependencies = [
3771
"windows-link",
3772
]
3773
3774
[[package]]
3775
name = "windows-strings"
3776
version = "0.5.1"
3777
source = "registry+https://github.com/rust-lang/crates.io-index"
3778
checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"
3779
dependencies = [
3780
"windows-link",
3781
]
3782
3573
3783
[[package]]
3574
3784
name = "windows-sys"
3575
3785
version = "0.52.0"
@@ -3784,6 +3994,25 @@ dependencies = [
3784
3994
"memchr",
3785
3995
]
3786
3996
3997
[[package]]
3998
name = "winreg"
3999
version = "0.55.0"
4000
source = "registry+https://github.com/rust-lang/crates.io-index"
4001
checksum = "cb5a765337c50e9ec252c2069be9bf91c7df47afb103b642ba3a53bf8101be97"
4002
dependencies = [
4003
"cfg-if",
4004
"windows-sys 0.59.0",
4005
]
4006
4007
[[package]]
4008
name = "winres"
4009
version = "0.1.12"
4010
source = "registry+https://github.com/rust-lang/crates.io-index"
4011
checksum = "b68db261ef59e9e52806f688020631e987592bd83619edccda9c47d42cde4f6c"
4012
dependencies = [
4013
"toml",
4014
]
4015
3787
4016
[[package]]
3788
4017
name = "wit-bindgen"
3789
4018
version = "0.57.1"
@@ -79,6 +79,15 @@ version = "0.2.2"79
source = "registry+https://github.com/rust-lang/crates.io-index"79
source = "registry+https://github.com/rust-lang/crates.io-index"80
checksum = "fc7eb209b1518d6bb87b283c20095f5228ecda460da70b44f0802523dea6da04"80
checksum = "fc7eb209b1518d6bb87b283c20095f5228ecda460da70b44f0802523dea6da04"81
81
82
[[package]]83
name = "android_system_properties"84
version = "0.1.5"85
source = "registry+https://github.com/rust-lang/crates.io-index"86
checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311"87
dependencies = [88
"libc",89
]90
82
[[package]]91
[[package]]83
name = "anstream"92
name = "anstream"84
version = "1.0.0"93
version = "1.0.0"@@ -516,6 +525,12 @@ dependencies = [516
"syn",525
"syn",517
]526
]518
527
528
[[package]]529
name = "byteorder"530
version = "1.5.0"531
source = "registry+https://github.com/rust-lang/crates.io-index"532
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"533
519
[[package]]534
[[package]]520
name = "byteorder-lite"535
name = "byteorder-lite"521
version = "0.1.0"536
version = "0.1.0"@@ -600,6 +615,17 @@ dependencies = [600
"libc",615
"libc",601
]616
]602
617
618
[[package]]619
name = "chrono"620
version = "0.4.45"621
source = "registry+https://github.com/rust-lang/crates.io-index"622
checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"623
dependencies = [624
"iana-time-zone",625
"num-traits",626
"windows-link",627
]628
603
[[package]]629
[[package]]604
name = "clap"630
name = "clap"605
version = "4.6.1"631
version = "4.6.1"@@ -1226,6 +1252,15 @@ dependencies = [1226
"windows-link",1252
"windows-link",1227
]1253
]1228
1254
1255
[[package]]1256
name = "getopts"1257
version = "0.2.24"1258
source = "registry+https://github.com/rust-lang/crates.io-index"1259
checksum = "cfe4fbac503b8d1f88e6676011885f34b7174f46e59956bba534ba83abded4df"1260
dependencies = [1261
"unicode-width",1262
]1263
1229
[[package]]1264
[[package]]1230
name = "getrandom"1265
name = "getrandom"1231
version = "0.3.4"1266
version = "0.3.4"@@ -1370,6 +1405,40 @@ version = "0.4.3"1370
source = "registry+https://github.com/rust-lang/crates.io-index"1405
source = "registry+https://github.com/rust-lang/crates.io-index"1371
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"1406
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"1372
1407
1408
[[package]]1409
name = "iana-time-zone"1410
version = "0.1.65"1411
source = "registry+https://github.com/rust-lang/crates.io-index"1412
checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470"1413
dependencies = [1414
"android_system_properties",1415
"core-foundation-sys",1416
"iana-time-zone-haiku",1417
"js-sys",1418
"log",1419
"wasm-bindgen",1420
"windows-core",1421
]1422
1423
[[package]]1424
name = "iana-time-zone-haiku"1425
version = "0.1.2"1426
source = "registry+https://github.com/rust-lang/crates.io-index"1427
checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"1428
dependencies = [1429
"cc",1430
]1431
1432
[[package]]1433
name = "ico"1434
version = "0.4.0"1435
source = "registry+https://github.com/rust-lang/crates.io-index"1436
checksum = "cc50b891e4acf8fe0e71ef88ec43ad82ee07b3810ad09de10f1d01f072ed4b98"1437
dependencies = [1438
"byteorder",1439
"png 0.17.16",1440
]1441
1373
[[package]]1442
[[package]]1374
name = "icu_collections"1443
name = "icu_collections"1375
version = "2.2.0"1444
version = "2.2.0"@@ -1487,7 +1556,7 @@ dependencies = [1487
"image-webp",1556
"image-webp",1488
"moxcms",1557
"moxcms",1489
"num-traits",1558
"num-traits",1490
"png",1559
"png 0.18.1",1491
"qoi",1560
"qoi",1492
"ravif",1561
"ravif",1493
"rayon",1562
"rayon",@@ -1720,6 +1789,18 @@ dependencies = [1720
"pkg-config",1789
"pkg-config",1721
]1790
]1722
1791
1792
[[package]]1793
name = "libusb1-sys"1794
version = "0.7.0"1795
source = "registry+https://github.com/rust-lang/crates.io-index"1796
checksum = "da050ade7ac4ff1ba5379af847a10a10a8e284181e060105bf8d86960ce9ce0f"1797
dependencies = [1798
"cc",1799
"libc",1800
"pkg-config",1801
"vcpkg",1802
]1803
1723
[[package]]1804
[[package]]1724
name = "linux-raw-sys"1805
name = "linux-raw-sys"1725
version = "0.4.15"1806
version = "0.4.15"@@ -2399,6 +2480,19 @@ version = "0.2.3"2399
source = "registry+https://github.com/rust-lang/crates.io-index"2480
source = "registry+https://github.com/rust-lang/crates.io-index"2400
checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6"2481
checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6"2401
2482
2483
[[package]]2484
name = "png"2485
version = "0.17.16"2486
source = "registry+https://github.com/rust-lang/crates.io-index"2487
checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526"2488
dependencies = [2489
"bitflags 1.3.2",2490
"crc32fast",2491
"fdeflate",2492
"flate2",2493
"miniz_oxide",2494
]2495
2402
[[package]]2496
[[package]]2403
name = "png"2497
name = "png"2404
version = "0.18.1"2498
version = "0.18.1"@@ -2437,15 +2531,22 @@ name = "posprint"2437
version = "0.1.0"2531
version = "0.1.0"2438
dependencies = [2532
dependencies = [2439
"barcoders",2533
"barcoders",2534
"chrono",2440
"clap",2535
"clap",2441
"eframe",2536
"eframe",2537
"ico",2442
"image",2538
"image",2539
"libc",2540
"pulldown-cmark",2443
"qrcode",2541
"qrcode",2444
"rfd",2542
"rfd",2543
"rusb",2445
"serde",2544
"serde",2446
"serde_json",2545
"serde_json",2447
"serialport",2546
"serialport",2448
"tempfile",2547
"tempfile",2548
"winreg",2549
"winres",2449
]2550
]2450
2551
2451
[[package]]2552
[[package]]@@ -2503,6 +2604,25 @@ dependencies = [2503
"syn",2604
"syn",2504
]2605
]2505
2606
2607
[[package]]2608
name = "pulldown-cmark"2609
version = "0.13.4"2610
source = "registry+https://github.com/rust-lang/crates.io-index"2611
checksum = "e9f068eba8e7071c5f9511831b44f32c740d5adf574e990f946ddb53db2f314e"2612
dependencies = [2613
"bitflags 2.13.0",2614
"getopts",2615
"memchr",2616
"pulldown-cmark-escape",2617
"unicase",2618
]2619
2620
[[package]]2621
name = "pulldown-cmark-escape"2622
version = "0.11.0"2623
source = "registry+https://github.com/rust-lang/crates.io-index"2624
checksum = "007d8adb5ddab6f8e3f491ac63566a7d5002cc7ed73901f72057943fa71ae1ae"2625
2506
[[package]]2626
[[package]]2507
name = "pulp"2627
name = "pulp"2508
version = "0.22.3"2628
version = "0.22.3"@@ -2763,6 +2883,16 @@ version = "0.8.53"2763
source = "registry+https://github.com/rust-lang/crates.io-index"2883
source = "registry+https://github.com/rust-lang/crates.io-index"2764
checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4"2884
checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4"2765
2885
2886
[[package]]2887
name = "rusb"2888
version = "0.9.4"2889
source = "registry+https://github.com/rust-lang/crates.io-index"2890
checksum = "ab9f9ff05b63a786553a4c02943b74b34a988448671001e9a27e2f0565cc05a4"2891
dependencies = [2892
"libc",2893
"libusb1-sys",2894
]2895
2766
[[package]]2896
[[package]]2767
name = "rustc_version"2897
name = "rustc_version"2768
version = "0.4.1"2898
version = "0.4.1"@@ -3136,6 +3266,15 @@ dependencies = [3136
"zerovec",3266
"zerovec",3137
]3267
]3138
3268
3269
[[package]]3270
name = "toml"3271
version = "0.5.11"3272
source = "registry+https://github.com/rust-lang/crates.io-index"3273
checksum = "f4f7f0dd8d50a853a531c426359045b1998f04219d88799810762cd4ad314234"3274
dependencies = [3275
"serde",3276
]3277
3139
[[package]]3278
[[package]]3140
name = "toml_datetime"3279
name = "toml_datetime"3141
version = "1.1.1+spec-1.1.0"3280
version = "1.1.1+spec-1.1.0"@@ -3224,6 +3363,12 @@ dependencies = [3224
"thiserror 2.0.18",3363
"thiserror 2.0.18",3225
]3364
]3226
3365
3366
[[package]]3367
name = "unicase"3368
version = "2.9.0"3369
source = "registry+https://github.com/rust-lang/crates.io-index"3370
checksum = "dbc4bc3a9f746d862c45cb89d705aa10f187bb96c76001afab07a0d35ce60142"3371
3227
[[package]]3372
[[package]]3228
name = "unicode-ident"3373
name = "unicode-ident"3229
version = "1.0.24"3374
version = "1.0.24"@@ -3236,6 +3381,12 @@ version = "1.13.3"3236
source = "registry+https://github.com/rust-lang/crates.io-index"3381
source = "registry+https://github.com/rust-lang/crates.io-index"3237
checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"3382
checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"3238
3383
3384
[[package]]3385
name = "unicode-width"3386
version = "0.2.2"3387
source = "registry+https://github.com/rust-lang/crates.io-index"3388
checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254"3389
3239
[[package]]3390
[[package]]3240
name = "url"3391
name = "url"3241
version = "2.5.8"3392
version = "2.5.8"@@ -3289,6 +3440,12 @@ dependencies = [3289
"wasm-bindgen",3440
"wasm-bindgen",3290
]3441
]3291
3442
3443
[[package]]3444
name = "vcpkg"3445
version = "0.2.15"3446
source = "registry+https://github.com/rust-lang/crates.io-index"3447
checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426"3448
3292
[[package]]3449
[[package]]3293
name = "version_check"3450
name = "version_check"3294
version = "0.9.5"3451
version = "0.9.5"@@ -3564,12 +3721,65 @@ version = "0.4.0"3564
source = "registry+https://github.com/rust-lang/crates.io-index"3721
source = "registry+https://github.com/rust-lang/crates.io-index"3565
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"3722
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"3566
3723
3724
[[package]]3725
name = "windows-core"3726
version = "0.62.2"3727
source = "registry+https://github.com/rust-lang/crates.io-index"3728
checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"3729
dependencies = [3730
"windows-implement",3731
"windows-interface",3732
"windows-link",3733
"windows-result",3734
"windows-strings",3735
]3736
3737
[[package]]3738
name = "windows-implement"3739
version = "0.60.2"3740
source = "registry+https://github.com/rust-lang/crates.io-index"3741
checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf"3742
dependencies = [3743
"proc-macro2",3744
"quote",3745
"syn",3746
]3747
3748
[[package]]3749
name = "windows-interface"3750
version = "0.59.3"3751
source = "registry+https://github.com/rust-lang/crates.io-index"3752
checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358"3753
dependencies = [3754
"proc-macro2",3755
"quote",3756
"syn",3757
]3758
3567
[[package]]3759
[[package]]3568
name = "windows-link"3760
name = "windows-link"3569
version = "0.2.1"3761
version = "0.2.1"3570
source = "registry+https://github.com/rust-lang/crates.io-index"3762
source = "registry+https://github.com/rust-lang/crates.io-index"3571
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"3763
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"3572
3764
3765
[[package]]3766
name = "windows-result"3767
version = "0.4.1"3768
source = "registry+https://github.com/rust-lang/crates.io-index"3769
checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"3770
dependencies = [3771
"windows-link",3772
]3773
3774
[[package]]3775
name = "windows-strings"3776
version = "0.5.1"3777
source = "registry+https://github.com/rust-lang/crates.io-index"3778
checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"3779
dependencies = [3780
"windows-link",3781
]3782
3573
[[package]]3783
[[package]]3574
name = "windows-sys"3784
name = "windows-sys"3575
version = "0.52.0"3785
version = "0.52.0"@@ -3784,6 +3994,25 @@ dependencies = [3784
"memchr",3994
"memchr",3785
]3995
]3786
3996
3997
[[package]]3998
name = "winreg"3999
version = "0.55.0"4000
source = "registry+https://github.com/rust-lang/crates.io-index"4001
checksum = "cb5a765337c50e9ec252c2069be9bf91c7df47afb103b642ba3a53bf8101be97"4002
dependencies = [4003
"cfg-if",4004
"windows-sys 0.59.0",4005
]4006
4007
[[package]]4008
name = "winres"4009
version = "0.1.12"4010
source = "registry+https://github.com/rust-lang/crates.io-index"4011
checksum = "b68db261ef59e9e52806f688020631e987592bd83619edccda9c47d42cde4f6c"4012
dependencies = [4013
"toml",4014
]4015
3787
[[package]]4016
[[package]]3788
name = "wit-bindgen"4017
name = "wit-bindgen"3789
version = "0.57.1"4018
version = "0.57.1"@@ -5,6 +5,7 @@ edition = "2021"
5
5
description = "Designer for POS-print documents"
6
6
license = "MIT"
7
7
readme = "README.md"
8
build = "build.rs"
8
9
9
10
[dependencies]
10
11
eframe = { version = "0.31", default-features = false, features = ["default_fonts", "glow"] }
@@ -16,10 +17,23 @@ rfd = "0.15"
16
17
clap = { version = "4", features = ["derive"] }
17
18
barcoders = { version = "2", default-features = false, features = ["image", "std"] }
18
19
qrcode = "0.14"
20
pulldown-cmark = "0.13"
21
rusb = "0.9"
22
chrono = { version = "0.4", default-features = false, features = ["clock", "std", "alloc"] }
23
libc = "0.2"
24
tempfile = "3"
19
25
20
26
[dev-dependencies]
21
27
tempfile = "3"
22
28
29
[target.'cfg(windows)'.dependencies]
30
winreg = "0.55"
31
32
[build-dependencies]
33
ico = "0.4"
34
image = { version = "0.25", default-features = false, features = ["png"] }
35
winres = "0.1"
36
23
37
[profile.release]
24
38
lto = true
25
39
strip = true
@@ -35,5 +49,10 @@ extended-description = """\
35
49
Designer for POS receipt templates with live preview and USB ESC/POS printing."""
36
50
assets = [
37
51
["target/release/posprint", "usr/bin/", "755"],
52
["packaging/posprint.desktop", "usr/share/applications/", "644"],
53
["packaging/mime/posprint.xml", "usr/share/mime/packages/", "644"],
54
["packaging/linux/posprint-print.desktop", "usr/share/kio/servicemenus/", "644"],
55
["packaging/linux/posprint-print-thunar.xml", "usr/share/thunar/uca/", "644"],
56
["pos-logo.png", "usr/share/pixmaps/posprint.png", "644"],
38
57
]
39
58
depends = "$auto"
@@ -5,6 +5,7 @@ edition = "2021"5
description = "Designer for POS-print documents"
5
description = "Designer for POS-print documents"
6
license = "MIT"
6
license = "MIT"
7
readme = "README.md"
7
readme = "README.md"
8
build = "build.rs"
8
9
9
[dependencies]
10
[dependencies]
10
eframe = { version = "0.31", default-features = false, features = ["default_fonts", "glow"] }
11
eframe = { version = "0.31", default-features = false, features = ["default_fonts", "glow"] }
@@ -16,10 +17,23 @@ rfd = "0.15"16
clap = { version = "4", features = ["derive"] }
17
clap = { version = "4", features = ["derive"] }
17
barcoders = { version = "2", default-features = false, features = ["image", "std"] }
18
barcoders = { version = "2", default-features = false, features = ["image", "std"] }
18
qrcode = "0.14"
19
qrcode = "0.14"
20
pulldown-cmark = "0.13"
21
rusb = "0.9"
22
chrono = { version = "0.4", default-features = false, features = ["clock", "std", "alloc"] }
23
libc = "0.2"
24
tempfile = "3"
19
25
20
[dev-dependencies]
26
[dev-dependencies]
21
tempfile = "3"
27
tempfile = "3"
22
28
29
[target.'cfg(windows)'.dependencies]
30
winreg = "0.55"
31
32
[build-dependencies]
33
ico = "0.4"
34
image = { version = "0.25", default-features = false, features = ["png"] }
35
winres = "0.1"
36
23
[profile.release]
37
[profile.release]
24
lto = true
38
lto = true
25
strip = true
39
strip = true
@@ -35,5 +49,10 @@ extended-description = """\35
Designer for POS receipt templates with live preview and USB ESC/POS printing."""
49
Designer for POS receipt templates with live preview and USB ESC/POS printing."""
36
assets = [
50
assets = [
37
["target/release/posprint", "usr/bin/", "755"],
51
["target/release/posprint", "usr/bin/", "755"],
52
["packaging/posprint.desktop", "usr/share/applications/", "644"],
53
["packaging/mime/posprint.xml", "usr/share/mime/packages/", "644"],
54
["packaging/linux/posprint-print.desktop", "usr/share/kio/servicemenus/", "644"],
55
["packaging/linux/posprint-print-thunar.xml", "usr/share/thunar/uca/", "644"],
56
["pos-logo.png", "usr/share/pixmaps/posprint.png", "644"],
38
]
57
]
39
depends = "$auto"
58
depends = "$auto"
@@ -0,0 +1,56 @@
1
use std::env;
2
use std::fs::File;
3
use std::io::BufWriter;
4
use std::path::Path;
5
6
fn main() {
7
println!("cargo:rerun-if-changed=build.rs");
8
println!("cargo:rerun-if-changed=pos-logo.png");
9
10
if env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
11
return;
12
}
13
14
let out_dir = env::var("OUT_DIR").expect("OUT_DIR");
15
let ico_path = Path::new(&out_dir).join("pos-logo.ico");
16
write_ico("pos-logo.png", &ico_path);
17
18
winres::WindowsResource::new()
19
.set_icon(ico_path.to_string_lossy().as_ref())
20
.compile()
21
.expect("failed to embed Windows executable icon");
22
}
23
24
fn write_ico(png_path: &str, out_path: &Path) {
25
let png_bytes = std::fs::read(png_path).unwrap_or_else(|e| {
26
panic!("failed to read {png_path}: {e}");
27
});
28
let image = image::load_from_memory(&png_bytes)
29
.unwrap_or_else(|e| panic!("failed to decode {png_path}: {e}"))
30
.to_rgba8();
31
32
let mut icon_dir = ico::IconDir::new(ico::ResourceType::Icon);
33
for size in [16u32, 24, 32, 48, 64, 128, 256] {
34
let rgba = if image.width() == size && image.height() == size {
35
image.clone().into_raw()
36
} else {
37
image::imageops::resize(
38
&image,
39
size,
40
size,
41
image::imageops::FilterType::Triangle,
42
)
43
.into_raw()
44
};
45
let icon_image = ico::IconImage::from_rgba_data(size, size, rgba);
46
let entry = ico::IconDirEntry::encode(&icon_image)
47
.unwrap_or_else(|e| panic!("failed to encode {size}x{size} icon: {e}"));
48
icon_dir.add_entry(entry);
49
}
50
51
let file = File::create(out_path).unwrap_or_else(|e| panic!("failed to create {out_path:?}: {e}"));
52
let mut writer = BufWriter::new(file);
53
icon_dir
54
.write(&mut writer)
55
.unwrap_or_else(|e| panic!("failed to write {out_path:?}: {e}"));
56
}
@@ -0,0 +1,56 @@1
use std::env;
2
use std::fs::File;
3
use std::io::BufWriter;
4
use std::path::Path;
5
6
fn main() {
7
println!("cargo:rerun-if-changed=build.rs");
8
println!("cargo:rerun-if-changed=pos-logo.png");
9
10
if env::var("CARGO_CFG_TARGET_OS").as_deref() != Ok("windows") {
11
return;
12
}
13
14
let out_dir = env::var("OUT_DIR").expect("OUT_DIR");
15
let ico_path = Path::new(&out_dir).join("pos-logo.ico");
16
write_ico("pos-logo.png", &ico_path);
17
18
winres::WindowsResource::new()
19
.set_icon(ico_path.to_string_lossy().as_ref())
20
.compile()
21
.expect("failed to embed Windows executable icon");
22
}
23
24
fn write_ico(png_path: &str, out_path: &Path) {
25
let png_bytes = std::fs::read(png_path).unwrap_or_else(|e| {
26
panic!("failed to read {png_path}: {e}");
27
});
28
let image = image::load_from_memory(&png_bytes)
29
.unwrap_or_else(|e| panic!("failed to decode {png_path}: {e}"))
30
.to_rgba8();
31
32
let mut icon_dir = ico::IconDir::new(ico::ResourceType::Icon);
33
for size in [16u32, 24, 32, 48, 64, 128, 256] {
34
let rgba = if image.width() == size && image.height() == size {
35
image.clone().into_raw()
36
} else {
37
image::imageops::resize(
38
&image,
39
size,
40
size,
41
image::imageops::FilterType::Triangle,
42
)
43
.into_raw()
44
};
45
let icon_image = ico::IconImage::from_rgba_data(size, size, rgba);
46
let entry = ico::IconDirEntry::encode(&icon_image)
47
.unwrap_or_else(|e| panic!("failed to encode {size}x{size} icon: {e}"));
48
icon_dir.add_entry(entry);
49
}
50
51
let file = File::create(out_path).unwrap_or_else(|e| panic!("failed to create {out_path:?}: {e}"));
52
let mut writer = BufWriter::new(file);
53
icon_dir
54
.write(&mut writer)
55
.unwrap_or_else(|e| panic!("failed to write {out_path:?}: {e}"));
56
}
@@ -46,4 +46,9 @@ package() {
46
46
install -Dm755 target/release/posprint "$pkgdir/usr/bin/posprint"
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
install -Dm644 packaging/posprint.desktop "$pkgdir/usr/share/applications/posprint.desktop"
50
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-thunar.xml "$pkgdir/usr/share/thunar/uca/posprint-print.xml"
53
install -Dm644 pos-logo.png "$pkgdir/usr/share/pixmaps/posprint.png"
49
54
}
@@ -46,4 +46,9 @@ package() {46
install -Dm755 target/release/posprint "$pkgdir/usr/bin/posprint"
46
install -Dm755 target/release/posprint "$pkgdir/usr/bin/posprint"
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"
50
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-thunar.xml "$pkgdir/usr/share/thunar/uca/posprint-print.xml"
53
install -Dm644 pos-logo.png "$pkgdir/usr/share/pixmaps/posprint.png"
49
}
54
}
@@ -0,0 +1,13 @@
1
<?xml version="1.0" encoding="UTF-8"?>
2
<actions>
3
<action>
4
<icon>posprint</icon>
5
<name>Print</name>
6
<command>posprint --print %f</command>
7
<description>Print POS receipt template</description>
8
<patterns>
9
<pattern>*.pos</pattern>
10
</patterns>
11
<startup-notify/>
12
</action>
13
</actions>
@@ -0,0 +1,13 @@1
<?xml version="1.0" encoding="UTF-8"?>
2
<actions>
3
<action>
4
<icon>posprint</icon>
5
<name>Print</name>
6
<command>posprint --print %f</command>
7
<description>Print POS receipt template</description>
8
<patterns>
9
<pattern>*.pos</pattern>
10
</patterns>
11
<startup-notify/>
12
</action>
13
</actions>
@@ -0,0 +1,11 @@
1
[Desktop Entry]
2
Type=Service
3
ServiceTypes=KonqPopupMenu/Plugin
4
MimeType=application/x-posprint;
5
Actions=Print;
6
X-KDE-Priority=TopLevel
7
8
[Desktop Action Print]
9
Name=Print
10
Icon=posprint
11
Exec=posprint --print %f
@@ -0,0 +1,11 @@1
[Desktop Entry]
2
Type=Service
3
ServiceTypes=KonqPopupMenu/Plugin
4
MimeType=application/x-posprint;
5
Actions=Print;
6
X-KDE-Priority=TopLevel
7
8
[Desktop Action Print]
9
Name=Print
10
Icon=posprint
11
Exec=posprint --print %f
@@ -0,0 +1,6 @@
1
<?xml version="1.0" encoding="UTF-8"?>
2
<mime-type xmlns="http://www.freedesktop.org/stand-alone/xml-mime-type">
3
<comment>POS print template</comment>
4
<glob pattern="*.pos"/>
5
<icon name="posprint"/>
6
</mime-type>
@@ -0,0 +1,6 @@1
<?xml version="1.0" encoding="UTF-8"?>
2
<mime-type xmlns="http://www.freedesktop.org/stand-alone/xml-mime-type">
3
<comment>POS print template</comment>
4
<glob pattern="*.pos"/>
5
<icon name="posprint"/>
6
</mime-type>
@@ -0,0 +1,10 @@
1
[Desktop Entry]
2
Type=Application
3
Name=posprint
4
Comment=POS receipt template designer
5
Exec=posprint %f
6
Icon=posprint
7
Terminal=false
8
Categories=Office;Utility;
9
MimeType=application/x-posprint;
10
StartupNotify=true
@@ -0,0 +1,10 @@1
[Desktop Entry]
2
Type=Application
3
Name=posprint
4
Comment=POS receipt template designer
5
Exec=posprint %f
6
Icon=posprint
7
Terminal=false
8
Categories=Office;Utility;
9
MimeType=application/x-posprint;
10
StartupNotify=true
The contents of this binary file are not shown.
@@ -1,72 +1,73 @@
1
use std::collections::HashMap;
2
1
use std::path::PathBuf;
3
2
4
3
use eframe::egui;
5
4
6
5
use posprint::dsl::{self, parse};
7
6
use posprint::editor_assist::{
8
at_directive_prefix, barcode_insert_options, directive_completions, image_insert_options,
9
insert_at_cursor, qr_insert_options,
7
apply_directive_completion, at_directive_prefix, barcode_insert_options,
8
complete_directive, date_time_insert_options, directive_ghost_suffix, image_insert_options,
9
insert_at_cursor, parameter_insert_options, qr_insert_options,
10
10
};
11
use posprint::pipeline;
12
use posprint::io::{PosFile, PosMetadata, PreviewMode};
13
use posprint::params::collect_parameter_names;
14
use posprint::preview::{render_preview, PreviewLine, TextStyle};
15
use posprint::print::{list_usb_serial_printers, print_bytes, SerialTransport, PrinterDevice};
11
use posprint::help_view;
12
use posprint::io::{PosFile, PosMetadata};
13
use posprint::preview::{
14
preview_content_width_px, preview_zoom_scale, render_preview, PreviewLine, TextStyle,
15
};
16
use posprint::undo::TextUndo;
16
17
use posprint::HELP_MARKDOWN;
17
18
19
use crate::print_dialog::{PrintDialog, PrintDialogAction, PrintExecuteResult};
20
18
21
#[derive(Clone, Copy, PartialEq, Eq)]
19
enum Tab {
20
Editor,
21
Preview,
22
enum ViewMode {
23
Design,
22
24
Help,
23
25
}
24
26
25
27
pub struct PosPrintApp {
26
tab: Tab,
28
view_mode: ViewMode,
27
29
body: String,
28
30
metadata: PosMetadata,
29
31
file_path: Option<PathBuf>,
30
32
dirty: bool,
31
33
parse_error: Option<String>,
32
status_message: Option<String>,
33
last_params: HashMap<String, String>,
34
action_error: Option<String>,
34
35
show_print_dialog: bool,
35
print_param_inputs: HashMap<String, String>,
36
print_param_names: Vec<String>,
37
printers: Vec<PrinterDevice>,
38
selected_printer: Option<usize>,
39
print_error: Option<String>,
36
print_dialog: PrintDialog,
40
37
editor_cursor: usize,
41
autocomplete: Vec<&'static str>,
38
undo: TextUndo,
39
preview_zoom: f32,
42
40
}
43
41
44
42
impl Default for PosPrintApp {
45
43
fn default() -> Self {
46
44
Self {
47
tab: Tab::Editor,
45
view_mode: ViewMode::Design,
48
46
body: default_template(),
49
47
metadata: PosMetadata::default(),
50
48
file_path: None,
51
49
dirty: false,
52
50
parse_error: None,
53
status_message: None,
54
last_params: HashMap::new(),
51
action_error: None,
55
52
show_print_dialog: false,
56
print_param_inputs: HashMap::new(),
57
print_param_names: Vec::new(),
58
printers: Vec::new(),
59
selected_printer: None,
60
print_error: None,
53
print_dialog: PrintDialog::default(),
61
54
editor_cursor: 0,
62
autocomplete: Vec::new(),
55
undo: TextUndo::default(),
56
preview_zoom: 1.0,
63
57
}
64
58
}
65
59
}
66
60
67
61
impl PosPrintApp {
68
pub fn new() -> Self {
69
Self::default()
62
pub fn new_with_file(path: Option<PathBuf>) -> Self {
63
let mut app = Self::default();
64
if let Some(path) = path {
65
match PosFile::load_from_path(&path) {
66
Ok(file) => app.load_pos_file(path, file),
67
Err(e) => app.action_error = Some(format!("Open failed: {e:?}")),
68
}
69
}
70
app
70
71
}
71
72
72
73
fn title(&self) -> String {
@@ -78,7 +79,7 @@ impl PosPrintApp {
78
79
.or_else(|| self.metadata.title.clone())
79
80
.unwrap_or_else(|| "Untitled".into());
80
81
if self.dirty {
81
format!("{name} * — posprint")
82
format!("* {name} — posprint")
82
83
} else {
83
84
format!("{name} — posprint")
84
85
}
@@ -98,93 +99,139 @@ impl PosPrintApp {
98
99
self.file_path = Some(path);
99
100
self.dirty = false;
100
101
self.parse_error = None;
101
self.status_message = Some("File loaded".into());
102
self.action_error = None;
103
self.undo = TextUndo::default();
102
104
}
103
105
104
fn validate_parse(&mut self) {
105
self.parse_error = match parse(&self.body) {
106
Ok(_) => None,
107
Err(e) => Some(e.to_string()),
108
};
106
fn new_document(&mut self) {
107
*self = Self::default();
109
108
}
110
109
111
fn open_print_dialog(&mut self) {
112
self.print_error = None;
113
match parse(&self.body) {
114
Ok(doc) => {
115
self.print_param_names = collect_parameter_names(&doc);
116
self.print_param_inputs.clear();
117
for name in &self.print_param_names {
118
let value = self
119
.last_params
120
.get(name)
121
.cloned()
122
.unwrap_or_default();
123
self.print_param_inputs.insert(name.clone(), value);
124
}
125
self.show_print_dialog = true;
126
self.refresh_printers();
110
fn open_file_dialog(&mut self) {
111
if let Some(path) = rfd::FileDialog::new()
112
.add_filter("POS template", &["pos"])
113
.pick_file()
114
{
115
match PosFile::load_from_path(&path) {
116
Ok(file) => self.load_pos_file(path, file),
117
Err(e) => self.action_error = Some(format!("Open failed: {e:?}")),
127
118
}
128
Err(e) => self.parse_error = Some(e.to_string()),
129
119
}
130
120
}
131
121
132
fn refresh_printers(&mut self) {
133
match list_usb_serial_printers() {
134
Ok(list) => {
135
self.printers = list;
136
if self.selected_printer.is_none() && !self.printers.is_empty() {
137
self.selected_printer = Some(0);
138
}
139
}
140
Err(e) => self.print_error = Some(e.to_string()),
122
fn save(&mut self) {
123
if let Some(path) = self.file_path.clone() {
124
self.save_to_path(path);
125
} else {
126
self.save_as();
141
127
}
142
128
}
143
129
144
fn execute_print(&mut self) {
145
self.print_error = None;
146
if parse(&self.body).is_err() {
147
self.print_error = Some("Template has parse errors".into());
148
return;
130
fn save_as(&mut self) {
131
if let Some(path) = rfd::FileDialog::new()
132
.add_filter("POS template", &["pos"])
133
.set_file_name("document.pos")
134
.save_file()
135
{
136
self.save_to_path(path);
149
137
}
138
}
150
139
151
for name in &self.print_param_names {
152
if !self.print_param_inputs.contains_key(name) {
153
self.print_error = Some(format!("Missing value for parameter {name}"));
154
return;
155
}
140
fn save_to_path(&mut self, path: PathBuf) {
141
if let Err(e) = self.pos_file().save_to_path(&path) {
142
self.action_error = Some(format!("Save failed: {e:?}"));
143
} else {
144
self.file_path = Some(path);
145
self.dirty = false;
146
self.action_error = None;
156
147
}
148
}
157
149
158
self.last_params = self.print_param_inputs.clone();
150
fn validate_parse(&mut self) {
151
self.parse_error = match parse(&self.body) {
152
Ok(_) => None,
153
Err(e) => Some(e.to_string()),
154
};
155
}
159
156
160
let base_dir = self.file_path.as_ref().and_then(|p| p.parent());
161
let file = self.pos_file();
162
let bytes = match pipeline::encode_pos_file(&file, base_dir, &self.last_params) {
163
Ok(b) => b,
164
Err(e) => {
165
self.print_error = Some(e.to_string());
166
return;
157
fn handle_shortcuts(&mut self, ctx: &egui::Context) {
158
let mut new_doc = false;
159
let mut open = false;
160
let mut save = false;
161
let mut undo = false;
162
let mut redo = false;
163
164
ctx.input(|i| {
165
if i.modifiers.command {
166
if i.key_pressed(egui::Key::S) {
167
save = true;
168
}
169
if i.key_pressed(egui::Key::N) {
170
new_doc = true;
171
}
172
if i.key_pressed(egui::Key::O) {
173
open = true;
174
}
175
if i.key_pressed(egui::Key::Z) {
176
if i.modifiers.shift {
177
redo = true;
178
} else {
179
undo = true;
180
}
181
}
182
if i.modifiers.shift && i.key_pressed(egui::Key::Y) {
183
redo = true;
184
}
167
185
}
168
};
186
});
169
187
170
let idx = match self.selected_printer {
171
Some(i) if i < self.printers.len() => i,
172
_ => {
173
self.print_error = Some("Select a printer".into());
174
return;
188
if new_doc {
189
self.new_document();
190
}
191
if open {
192
self.open_file_dialog();
193
}
194
if save {
195
self.save();
196
}
197
if undo {
198
if let Some(prev) = self.undo.undo(&self.body) {
199
self.body = prev;
200
self.dirty = true;
175
201
}
176
};
202
}
203
if redo {
204
if let Some(next) = self.undo.redo(&self.body) {
205
self.body = next;
206
self.dirty = true;
207
}
208
}
209
}
177
210
178
let port = self.printers[idx].port_name.clone();
179
match SerialTransport::open(&port) {
180
Ok(mut transport) => match print_bytes(&mut transport, &bytes) {
181
Ok(()) => {
182
self.status_message = Some(format!("Printed to {port}"));
183
self.show_print_dialog = false;
184
}
185
Err(e) => self.print_error = Some(format!("{e:?}")),
186
},
187
Err(e) => self.print_error = Some(format!("{e:?}")),
211
fn apply_print_dialog_params_to_preview(&mut self) {
212
self.print_dialog.apply_inputs_to_last_params();
213
}
214
215
fn close_print_dialog(&mut self) {
216
self.apply_print_dialog_params_to_preview();
217
self.show_print_dialog = false;
218
}
219
220
fn open_print_dialog(&mut self) {
221
match self.print_dialog.prepare(&self.body) {
222
Ok(()) => self.show_print_dialog = true,
223
Err(e) => self.parse_error = Some(e),
224
}
225
}
226
227
fn execute_print(&mut self) {
228
if self.print_dialog.execute_print(
229
&self.body,
230
&self.metadata,
231
self.file_path.as_ref(),
232
) == PrintExecuteResult::Printed
233
{
234
self.show_print_dialog = false;
188
235
}
189
236
}
190
237
}
@@ -192,49 +239,22 @@ impl PosPrintApp {
192
239
impl eframe::App for PosPrintApp {
193
240
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
194
241
self.validate_parse();
242
self.handle_shortcuts(ctx);
243
self.print_dialog.poll_printer_discovery(ctx);
195
244
196
245
egui::TopBottomPanel::top("menu").show(ctx, |ui| {
197
246
ui.horizontal_wrapped(|ui| {
198
247
if ui.button("New").clicked() {
199
*self = Self::default();
248
self.new_document();
200
249
}
201
250
if ui.button("Open").clicked() {
202
if let Some(path) = rfd::FileDialog::new()
203
.add_filter("POS template", &["pos"])
204
.pick_file()
205
{
206
match PosFile::load_from_path(&path) {
207
Ok(file) => self.load_pos_file(path, file),
208
Err(e) => self.status_message = Some(format!("Open failed: {e:?}")),
209
}
210
}
251
self.open_file_dialog();
211
252
}
212
253
if ui.button("Save").clicked() {
213
if let Some(path) = self.file_path.clone() {
214
if let Err(e) = self.pos_file().save_to_path(&path) {
215
self.status_message = Some(format!("Save failed: {e:?}"));
216
} else {
217
self.dirty = false;
218
self.status_message = Some("Saved".into());
219
}
220
} else if ui.button("Save As").clicked() {
221
// handled below when no path
222
}
254
self.save();
223
255
}
224
256
if ui.button("Save As").clicked() {
225
if let Some(path) = rfd::FileDialog::new()
226
.add_filter("POS template", &["pos"])
227
.set_file_name("document.pos")
228
.save_file()
229
{
230
if let Err(e) = self.pos_file().save_to_path(&path) {
231
self.status_message = Some(format!("Save failed: {e:?}"));
232
} else {
233
self.file_path = Some(path);
234
self.dirty = false;
235
self.status_message = Some("Saved".into());
236
}
237
}
257
self.save_as();
238
258
}
239
259
if ui.button("Print").clicked() {
240
260
self.open_print_dialog();
@@ -264,6 +284,22 @@ impl eframe::App for PosPrintApp {
264
284
}
265
285
}
266
286
});
287
ui.menu_button("Date / time", |ui| {
288
for opt in date_time_insert_options() {
289
if ui.button(&opt.label).clicked() {
290
self.insert_snippet(&opt.snippet);
291
ui.close_menu();
292
}
293
}
294
});
295
ui.menu_button("Parameters", |ui| {
296
for opt in parameter_insert_options(&self.body) {
297
if ui.button(&opt.label).clicked() {
298
self.insert_snippet(&opt.snippet);
299
ui.close_menu();
300
}
301
}
302
});
267
303
ui.separator();
268
304
if ui.button("@feed").clicked() {
269
305
self.insert_snippet("@feed 3\n");
@@ -287,63 +323,80 @@ impl eframe::App for PosPrintApp {
287
323
self.metadata.page_width_mm = width;
288
324
self.dirty = true;
289
325
}
290
ui.label("Preview:");
291
egui::ComboBox::from_id_salt("preview_mode")
292
.selected_text(match self.metadata.preview_mode {
293
PreviewMode::Autoscale => "Auto-scale",
294
PreviewMode::Fixed => "Fixed width",
295
})
296
.show_ui(ui, |ui| {
297
if ui
298
.selectable_value(
299
&mut self.metadata.preview_mode,
300
PreviewMode::Autoscale,
301
"Auto-scale",
302
)
303
.changed()
304
{
305
self.dirty = true;
306
}
307
if ui
308
.selectable_value(
309
&mut self.metadata.preview_mode,
310
PreviewMode::Fixed,
311
"Fixed width",
312
)
313
.changed()
314
{
315
self.dirty = true;
316
}
317
});
318
326
});
319
327
320
328
if let Some(err) = &self.parse_error {
321
329
ui.colored_label(egui::Color32::RED, err);
322
330
}
323
if let Some(msg) = &self.status_message {
324
ui.label(msg);
331
if let Some(err) = &self.action_error {
332
ui.colored_label(egui::Color32::RED, err);
325
333
}
326
334
});
327
335
328
336
egui::TopBottomPanel::bottom("tabs").show(ctx, |ui| {
329
337
ui.horizontal(|ui| {
330
ui.selectable_value(&mut self.tab, Tab::Editor, "Editor");
331
ui.selectable_value(&mut self.tab, Tab::Preview, "Preview");
332
ui.selectable_value(&mut self.tab, Tab::Help, "Help");
338
ui.selectable_value(&mut self.view_mode, ViewMode::Design, "Design");
339
ui.selectable_value(&mut self.view_mode, ViewMode::Help, "Help");
333
340
});
334
341
});
335
342
336
egui::CentralPanel::default().show(ctx, |ui| match self.tab {
337
Tab::Editor => self.show_editor(ui),
338
Tab::Preview => self.show_preview(ui),
339
Tab::Help => self.show_help(ui),
340
});
343
match self.view_mode {
344
ViewMode::Design => {
345
egui::SidePanel::right("preview_panel")
346
.resizable(true)
347
.min_width(260.0)
348
.default_width(380.0)
349
.show(ctx, |ui| {
350
ui.heading("Preview");
351
ui.horizontal(|ui| {
352
ui.label(format!(
353
"Page width: {:.0} mm",
354
self.metadata.page_width_mm
355
));
356
ui.separator();
357
ui.label("Zoom:");
358
ui.add(
359
egui::Slider::new(&mut self.preview_zoom, 0.25..=4.0)
360
.logarithmic(true)
361
.show_value(true),
362
);
363
if ui.button("100%").clicked() {
364
self.preview_zoom = 1.0;
365
}
366
});
367
ui.separator();
368
self.show_preview(ui, ctx);
369
});
370
371
egui::CentralPanel::default().show(ctx, |ui| {
372
ui.heading("Editor");
373
self.show_editor(ui);
374
});
375
}
376
ViewMode::Help => {
377
egui::CentralPanel::default().show(ctx, |ui| {
378
help_view::show_help(ui, HELP_MARKDOWN);
379
});
380
}
381
}
341
382
342
383
if self.show_print_dialog {
384
let mut open = true;
343
385
egui::Window::new("Print")
344
386
.collapsible(false)
345
387
.resizable(true)
346
.show(ctx, |ui| self.show_print_dialog_ui(ui));
388
.open(&mut open)
389
.show(ctx, |ui| {
390
match self.print_dialog.show_ui(ui, "Cancel") {
391
PrintDialogAction::Cancel => self.close_print_dialog(),
392
PrintDialogAction::Print => self.execute_print(),
393
PrintDialogAction::None => {}
394
}
395
});
396
if !open {
397
self.apply_print_dialog_params_to_preview();
398
}
399
self.show_print_dialog = open;
347
400
}
348
401
349
402
ctx.send_viewport_cmd(egui::ViewportCommand::Title(self.title()));
@@ -352,251 +405,254 @@ impl eframe::App for PosPrintApp {
352
405
353
406
impl PosPrintApp {
354
407
fn insert_snippet(&mut self, snippet: &str) {
408
let before = self.body.clone();
355
409
let (body, cursor) = insert_at_cursor(&self.body, self.editor_cursor, snippet);
356
410
self.body = body;
357
411
self.editor_cursor = cursor;
412
self.undo.record(before);
358
413
self.dirty = true;
359
self.tab = Tab::Editor;
414
self.view_mode = ViewMode::Design;
360
415
}
361
416
362
417
fn show_editor(&mut self, ui: &mut egui::Ui) {
418
let before = self.body.clone();
419
let cursor_before = self.editor_cursor;
420
421
let directive_ctx = at_directive_prefix(&self.body, cursor_before);
422
let autocomplete_active = directive_ctx.as_ref().is_some_and(|(_, prefix)| {
423
complete_directive(prefix).is_some() || directive_ghost_suffix(prefix).is_some()
424
});
425
426
let mut tab_completion: Option<(usize, String)> = None;
427
if autocomplete_active {
428
if let Some((at_index, prefix)) = directive_ctx.clone() {
429
ui.input_mut(|input| {
430
if input.key_pressed(egui::Key::Tab) && !input.modifiers.any() {
431
tab_completion = Some((at_index, prefix));
432
input.consume_key(egui::Modifiers::NONE, egui::Key::Tab);
433
}
434
});
435
}
436
}
437
363
438
let output = egui::TextEdit::multiline(&mut self.body)
364
439
.id_salt("main_editor")
365
440
.desired_width(f32::INFINITY)
366
441
.desired_rows(30)
367
442
.font(egui::TextStyle::Monospace)
443
.lock_focus(true)
368
444
.show(ui);
369
445
446
if autocomplete_active {
447
output.response.request_focus();
448
}
449
370
450
self.editor_cursor = output
371
.state
372
.cursor
373
.char_range()
374
.map(|r| r.primary.index)
451
.cursor_range
452
.as_ref()
453
.map(|r| r.primary.ccursor.index)
454
.or_else(|| {
455
output
456
.state
457
.cursor
458
.char_range()
459
.map(|r| r.primary.index)
460
})
375
461
.unwrap_or(self.body.len());
376
462
377
if output.response.changed() {
463
if let Some((at_index, prefix)) = tab_completion {
464
if let Some(completed) = complete_directive(&prefix) {
465
let undo_before = self.body.clone();
466
self.editor_cursor =
467
apply_directive_completion(&mut self.body, at_index, self.editor_cursor, completed);
468
self.undo.record(undo_before);
469
self.dirty = true;
470
}
471
} else if output.response.changed() {
472
self.undo.record(before);
378
473
self.dirty = true;
379
474
}
380
475
381
if let Some((_start, prefix)) = at_directive_prefix(&self.body, self.editor_cursor) {
382
self.autocomplete = directive_completions(&prefix);
383
if !self.autocomplete.is_empty() {
384
egui::Area::new(egui::Id::new("directive_ac"))
385
.order(egui::Order::Foreground)
386
.show(ui.ctx(), |ui| {
387
ui.set_min_width(120.0);
388
ui.label("Directive autocomplete:");
389
for dir in &self.autocomplete {
390
if ui.button(format!("@{dir}")).clicked() {
391
let line_start = self.body[..self.editor_cursor]
392
.rfind('\n')
393
.map(|i| i + 1)
394
.unwrap_or(0);
395
let line_end = self.body[self.editor_cursor..]
396
.find('\n')
397
.map(|i| self.editor_cursor + i)
398
.unwrap_or(self.body.len());
399
let mut line = self.body[line_start..line_end].to_string();
400
if let Some(at) = line.find('@') {
401
line.replace_range(at + 1.., dir);
402
self.body.replace_range(line_start..line_end, &line);
403
self.editor_cursor = line_start + at + 1 + dir.len();
404
self.dirty = true;
405
}
406
}
407
}
408
});
476
if let Some((_at_index, prefix)) = at_directive_prefix(&self.body, self.editor_cursor) {
477
if let Some(suffix) = directive_ghost_suffix(&prefix) {
478
if let Some(cursor_range) = &output.cursor_range {
479
let font_id = egui::TextStyle::Monospace.resolve(ui.style());
480
let pos = output.galley.pos_from_cursor(&cursor_range.primary);
481
let ghost_pos = output.galley_pos + pos.min.to_vec2();
482
let ghost_color = ui.visuals().weak_text_color();
483
ui.painter().text(
484
ghost_pos,
485
egui::Align2::LEFT_TOP,
486
suffix,
487
font_id,
488
ghost_color,
489
);
490
}
409
491
}
410
} else {
411
self.autocomplete.clear();
412
492
}
413
493
}
414
494
415
fn show_preview(&mut self, ui: &mut egui::Ui) {
495
fn show_preview(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) {
416
496
let Ok(doc) = parse(&self.body) else {
417
497
ui.label("Fix parse errors to preview.");
418
498
return;
419
499
};
420
let model = render_preview(&doc, &self.metadata);
421
let chars = model.width_chars as f32;
422
let scale = match self.metadata.preview_mode {
423
PreviewMode::Autoscale => {
424
let avail = ui.available_width().max(200.0);
425
(avail / (chars * 8.0)).clamp(0.8, 3.0)
426
}
427
PreviewMode::Fixed => model.width_mm / 80.0,
428
};
429
500
430
egui::Frame::canvas(ui.style()).show(ui, |ui| {
431
let width = chars * 8.0 * scale;
432
let (_id, rect) = ui.allocate_space(egui::vec2(width, ui.available_height()));
433
let painter = ui.painter_at(rect);
434
painter.rect_filled(rect, 4.0, egui::Color32::WHITE);
435
painter.rect_stroke(
436
rect,
437
4.0,
438
egui::Stroke::new(1.0_f32, egui::Color32::GRAY),
439
egui::StrokeKind::Inside,
440
);
441
442
let mut y = rect.min.y + 8.0;
443
let line_height = 18.0 * scale;
444
for line in &model.lines {
445
match line {
446
PreviewLine::Text {
447
content,
448
align,
449
style,
450
} => {
451
let font_id = match style {
452
TextStyle::Heading1 => egui::FontId::proportional(22.0 * scale),
453
TextStyle::Heading2 => egui::FontId::proportional(18.0 * scale),
454
TextStyle::Bold => egui::FontId::proportional(16.0 * scale),
455
TextStyle::Italic => egui::FontId::proportional(15.0 * scale),
456
TextStyle::Code => egui::FontId::monospace(14.0 * scale),
457
TextStyle::Normal => egui::FontId::monospace(14.0 * scale),
458
};
459
let galley = painter.layout(
460
content.clone(),
461
font_id,
462
egui::Color32::BLACK,
463
width,
464
);
465
let x = match align {
466
dsl::Align::Left => rect.min.x + 8.0,
467
dsl::Align::Center => {
468
rect.min.x + (width - galley.size().x) / 2.0
469
}
470
dsl::Align::Right => rect.max.x - galley.size().x - 8.0,
471
};
472
painter.galley(egui::pos2(x, y), galley, egui::Color32::BLACK);
473
y += line_height;
474
}
475
PreviewLine::Rule => {
476
painter.line_segment(
477
[
478
egui::pos2(rect.min.x + 8.0, y),
479
egui::pos2(rect.max.x - 8.0, y),
480
],
481
egui::Stroke::new(1.0_f32, egui::Color32::DARK_GRAY),
482
);
483
y += line_height;
484
}
485
PreviewLine::Barcode { symbology, data, .. } => {
486
let text = format!("[barcode {symbology}: {data}]");
487
let galley = painter.layout(
488
text,
489
egui::FontId::monospace(14.0 * scale),
490
egui::Color32::BLACK,
491
width,
492
);
493
painter.galley(egui::pos2(rect.min.x + 8.0, y), galley, egui::Color32::BLACK);
494
y += line_height * 1.5;
495
}
496
PreviewLine::Qr { data, .. } => {
497
let text = format!("[qr: {data}]");
498
let galley = painter.layout(
499
text,
500
egui::FontId::monospace(14.0 * scale),
501
egui::Color32::BLACK,
502
width,
503
);
504
painter.galley(egui::pos2(rect.min.x + 8.0, y), galley, egui::Color32::BLACK);
505
y += line_height * 1.5;
506
}
507
PreviewLine::Image { label, .. } => {
508
let galley = painter.layout(
509
label.clone(),
510
egui::FontId::monospace(14.0 * scale),
511
egui::Color32::DARK_BLUE,
512
width,
513
);
514
painter.galley(egui::pos2(rect.min.x + 8.0, y), galley, egui::Color32::BLACK);
515
y += line_height * 1.5;
501
let base_dir = self.file_path.as_ref().and_then(|p| p.parent());
502
let model = render_preview(
503
&doc,
504
&self.metadata,
505
base_dir,
506
&self.print_dialog.last_params,
507
);
508
let visual_scale = preview_zoom_scale(self.preview_zoom);
509
let content_width = preview_content_width_px(&self.metadata) * visual_scale;
510
let padding = 8.0 * visual_scale;
511
512
egui::ScrollArea::both()
513
.auto_shrink([false; 2])
514
.show(ui, |ui| {
515
egui::Frame::canvas(ui.style()).show(ui, |ui| {
516
let mut total_height = padding * 2.0;
517
for line in &model.lines {
518
total_height += line_height(line, visual_scale) + 2.0;
516
519
}
517
PreviewLine::Spacer(n) => {
518
y += line_height * (*n as f32);
520
total_height = total_height.max(100.0);
521
522
let (_id, rect) = ui.allocate_space(egui::vec2(content_width, total_height));
523
let painter = ui.painter_at(rect);
524
painter.rect_filled(rect, 4.0, egui::Color32::WHITE);
525
painter.rect_stroke(
526
rect,
527
4.0,
528
egui::Stroke::new(1.0_f32, egui::Color32::GRAY),
529
egui::StrokeKind::Inside,
530
);
531
532
let mut y = rect.min.y + padding;
533
let inner_width = content_width - padding * 2.0;
534
535
for (idx, line) in model.lines.iter().enumerate() {
536
match line {
537
PreviewLine::Text {
538
content,
539
align,
540
style,
541
} => {
542
let font_id = text_font(*style, visual_scale);
543
let galley = painter.layout_no_wrap(
544
content.clone(),
545
font_id,
546
egui::Color32::BLACK,
547
);
548
let x = align_x(*align, rect.min.x + padding, inner_width, galley.size().x);
549
let line_h = galley.size().y;
550
painter.galley(egui::pos2(x, y), galley, egui::Color32::BLACK);
551
y += line_h + 4.0 * visual_scale;
552
}
553
PreviewLine::Rule => {
554
painter.line_segment(
555
[
556
egui::pos2(rect.min.x + padding, y),
557
egui::pos2(rect.max.x - padding, y),
558
],
559
egui::Stroke::new(1.0_f32, egui::Color32::DARK_GRAY),
560
);
561
y += 12.0 * visual_scale;
562
}
563
PreviewLine::Graphic { image, align } => {
564
let tex = gray_to_texture(
565
ctx,
566
&format!("preview_graphic_{idx}"),
567
image,
568
);
569
let size = egui::vec2(
570
tex.size()[0] as f32 * visual_scale,
571
tex.size()[1] as f32 * visual_scale,
572
);
573
let x = align_x(*align, rect.min.x + padding, inner_width, size.x);
574
painter.image(
575
tex.id(),
576
egui::Rect::from_min_size(egui::pos2(x, y), size),
577
egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)),
578
egui::Color32::WHITE,
579
);
580
y += size.y + 4.0 * visual_scale;
581
}
582
PreviewLine::Error { message, align } => {
583
let galley = painter.layout(
584
message.clone(),
585
egui::FontId::proportional(12.0 * visual_scale),
586
egui::Color32::RED,
587
inner_width,
588
);
589
let x = align_x(*align, rect.min.x + padding, inner_width, galley.size().x);
590
let line_h = galley.size().y;
591
painter.galley(egui::pos2(x, y), galley, egui::Color32::RED);
592
y += line_h + 4.0 * visual_scale;
593
}
594
PreviewLine::Spacer(n) => {
595
y += 18.0 * visual_scale * (*n as f32);
596
}
597
}
519
598
}
520
}
521
}
522
});
599
});
600
});
523
601
}
602
}
524
603
525
fn show_help(&mut self, ui: &mut egui::Ui) {
526
egui::ScrollArea::vertical().show(ui, |ui| {
527
ui.add(
528
egui::Label::new(HELP_MARKDOWN)
529
.wrap()
530
.selectable(true),
531
);
532
});
604
fn text_font(style: TextStyle, scale: f32) -> egui::FontId {
605
match style {
606
TextStyle::Heading1 => egui::FontId::proportional(22.0 * scale),
607
TextStyle::Heading2 => egui::FontId::proportional(18.0 * scale),
608
TextStyle::Bold => egui::FontId::proportional(16.0 * scale),
609
TextStyle::Italic => egui::FontId::proportional(15.0 * scale),
610
TextStyle::Code => egui::FontId::monospace(14.0 * scale),
611
TextStyle::Normal => egui::FontId::monospace(14.0 * scale),
533
612
}
613
}
534
614
535
fn show_print_dialog_ui(&mut self, ui: &mut egui::Ui) {
536
ui.heading("Parameters");
537
if self.print_param_names.is_empty() {
538
ui.label("No parameters in this template.");
539
} else {
540
for name in self.print_param_names.clone() {
541
ui.horizontal(|ui| {
542
ui.label(format!("{name}:"));
543
let entry = self
544
.print_param_inputs
545
.entry(name)
546
.or_insert_with(String::new);
547
ui.text_edit_singleline(entry);
548
});
549
}
550
}
551
552
ui.separator();
553
ui.heading("USB printer");
554
if ui.button("Refresh").clicked() {
555
self.refresh_printers();
556
}
557
if self.printers.is_empty() {
558
ui.label("No serial ports found. Connect a USB printer and refresh.");
559
} else {
560
for (i, printer) in self.printers.iter().enumerate() {
561
ui.selectable_value(&mut self.selected_printer, Some(i), &printer.display_name);
562
}
563
}
564
565
if let Some(err) = &self.print_error {
566
ui.colored_label(egui::Color32::RED, err);
567
}
568
569
ui.horizontal(|ui| {
570
if ui.button("Cancel").clicked() {
571
self.show_print_dialog = false;
572
}
573
if ui.button("Print").clicked() {
574
self.execute_print();
575
}
576
});
615
fn align_x(align: dsl::Align, left: f32, inner_width: f32, item_width: f32) -> f32 {
616
match align {
617
dsl::Align::Left => left,
618
dsl::Align::Center => left + (inner_width - item_width) / 2.0,
619
dsl::Align::Right => left + inner_width - item_width,
577
620
}
578
621
}
579
622
580
fn default_template() -> String {
581
r#"# ${StoreName}
582
:center:
583
584
Receipt: ${DocumentNumber}
585
Date: ${Date}
586
587
---
588
:right:
589
**TOTAL: ${GrandTotal}**
623
fn line_height(line: &PreviewLine, scale: f32) -> f32 {
624
match line {
625
PreviewLine::Text { style, .. } => match style {
626
TextStyle::Heading1 => 28.0 * scale,
627
TextStyle::Heading2 => 24.0 * scale,
628
_ => 18.0 * scale,
629
},
630
PreviewLine::Rule => 12.0 * scale,
631
PreviewLine::Graphic { image, .. } => image.height() as f32 * scale + 4.0,
632
PreviewLine::Error { .. } => 18.0 * scale,
633
PreviewLine::Spacer(n) => 18.0 * scale * (*n as f32),
634
}
635
}
590
636
591
@barcode CODE128 ${DocumentNumber}
592
@feed 2
593
@qr https://example.com/r/${DocumentNumber}
637
fn gray_to_texture(
638
ctx: &egui::Context,
639
id: &str,
640
image: &image::GrayImage,
641
) -> egui::TextureHandle {
642
let (w, h) = image.dimensions();
643
let pixels: Vec<egui::Color32> = image
644
.pixels()
645
.map(|p| egui::Color32::from_gray(p.0[0]))
646
.collect();
647
let color_image = egui::ColorImage {
648
size: [w as usize, h as usize],
649
pixels,
650
};
651
ctx.load_texture(id, color_image, egui::TextureOptions::NEAREST)
652
}
594
653
595
Thank you!
596
@feed 4
597
@cut
598
"#
599
.to_string()
654
fn default_template() -> String {
655
String::new()
600
656
}
601
657
602
658
#[cfg(test)]
@@ -604,17 +660,16 @@ mod tests {
604
660
use super::*;
605
661
606
662
#[test]
607
fn default_template_parses() {
663
fn default_template_is_empty() {
608
664
let app = PosPrintApp::default();
665
assert!(app.body.is_empty());
609
666
assert!(parse(&app.body).is_ok());
610
667
}
611
668
612
669
#[test]
613
fn collect_params_from_default_template() {
614
let app = PosPrintApp::default();
615
let doc = parse(&app.body).unwrap();
616
let names = collect_parameter_names(&doc);
617
assert!(names.contains(&"StoreName".to_string()));
618
assert!(names.contains(&"DocumentNumber".to_string()));
670
fn title_shows_asterisk_before_name_when_dirty() {
671
let mut app = PosPrintApp::default();
672
app.dirty = true;
673
assert!(app.title().starts_with("* "));
619
674
}
620
675
}
@@ -1,72 +1,73 @@1
use std::collections::HashMap;
2
use std::path::PathBuf;
1
use std::path::PathBuf;
3
2
4
use eframe::egui;
3
use eframe::egui;
5
4
6
use posprint::dsl::{self, parse};
5
use posprint::dsl::{self, parse};
7
use posprint::editor_assist::{
6
use posprint::editor_assist::{
8
at_directive_prefix, barcode_insert_options, directive_completions, image_insert_options,
7
apply_directive_completion, at_directive_prefix, barcode_insert_options,
9
insert_at_cursor, qr_insert_options,
8
complete_directive, date_time_insert_options, directive_ghost_suffix, image_insert_options,
9
insert_at_cursor, parameter_insert_options, qr_insert_options,
10
};
10
};
11
use posprint::pipeline;
11
use posprint::help_view;
12
use posprint::io::{PosFile, PosMetadata, PreviewMode};
12
use posprint::io::{PosFile, PosMetadata};
13
use posprint::params::collect_parameter_names;
13
use posprint::preview::{
14
use posprint::preview::{render_preview, PreviewLine, TextStyle};
14
preview_content_width_px, preview_zoom_scale, render_preview, PreviewLine, TextStyle,
15
use posprint::print::{list_usb_serial_printers, print_bytes, SerialTransport, PrinterDevice};
15
};
16
use posprint::undo::TextUndo;
16
use posprint::HELP_MARKDOWN;
17
use posprint::HELP_MARKDOWN;
17
18
19
use crate::print_dialog::{PrintDialog, PrintDialogAction, PrintExecuteResult};
20
18
#[derive(Clone, Copy, PartialEq, Eq)]
21
#[derive(Clone, Copy, PartialEq, Eq)]
19
enum Tab {
22
enum ViewMode {
20
Editor,
23
Design,
21
Preview,
22
Help,
24
Help,
23
}
25
}
24
26
25
pub struct PosPrintApp {
27
pub struct PosPrintApp {
26
tab: Tab,
28
view_mode: ViewMode,
27
body: String,
29
body: String,
28
metadata: PosMetadata,
30
metadata: PosMetadata,
29
file_path: Option<PathBuf>,
31
file_path: Option<PathBuf>,
30
dirty: bool,
32
dirty: bool,
31
parse_error: Option<String>,
33
parse_error: Option<String>,
32
status_message: Option<String>,
34
action_error: Option<String>,
33
last_params: HashMap<String, String>,
34
show_print_dialog: bool,
35
show_print_dialog: bool,
35
print_param_inputs: HashMap<String, String>,
36
print_dialog: PrintDialog,
36
print_param_names: Vec<String>,
37
printers: Vec<PrinterDevice>,
38
selected_printer: Option<usize>,
39
print_error: Option<String>,
40
editor_cursor: usize,
37
editor_cursor: usize,
41
autocomplete: Vec<&'static str>,
38
undo: TextUndo,
39
preview_zoom: f32,
42
}
40
}
43
41
44
impl Default for PosPrintApp {
42
impl Default for PosPrintApp {
45
fn default() -> Self {
43
fn default() -> Self {
46
Self {
44
Self {
47
tab: Tab::Editor,
45
view_mode: ViewMode::Design,
48
body: default_template(),
46
body: default_template(),
49
metadata: PosMetadata::default(),
47
metadata: PosMetadata::default(),
50
file_path: None,
48
file_path: None,
51
dirty: false,
49
dirty: false,
52
parse_error: None,
50
parse_error: None,
53
status_message: None,
51
action_error: None,
54
last_params: HashMap::new(),
55
show_print_dialog: false,
52
show_print_dialog: false,
56
print_param_inputs: HashMap::new(),
53
print_dialog: PrintDialog::default(),
57
print_param_names: Vec::new(),
58
printers: Vec::new(),
59
selected_printer: None,
60
print_error: None,
61
editor_cursor: 0,
54
editor_cursor: 0,
62
autocomplete: Vec::new(),
55
undo: TextUndo::default(),
56
preview_zoom: 1.0,
63
}
57
}
64
}
58
}
65
}
59
}
66
60
67
impl PosPrintApp {
61
impl PosPrintApp {
68
pub fn new() -> Self {
62
pub fn new_with_file(path: Option<PathBuf>) -> Self {
69
Self::default()
63
let mut app = Self::default();
64
if let Some(path) = path {
65
match PosFile::load_from_path(&path) {
66
Ok(file) => app.load_pos_file(path, file),
67
Err(e) => app.action_error = Some(format!("Open failed: {e:?}")),
68
}
69
}
70
app
70
}
71
}
71
72
72
fn title(&self) -> String {
73
fn title(&self) -> String {
@@ -78,7 +79,7 @@ impl PosPrintApp {78
.or_else(|| self.metadata.title.clone())
79
.or_else(|| self.metadata.title.clone())
79
.unwrap_or_else(|| "Untitled".into());
80
.unwrap_or_else(|| "Untitled".into());
80
if self.dirty {
81
if self.dirty {
81
format!("{name} * — posprint")
82
format!("* {name} — posprint")
82
} else {
83
} else {
83
format!("{name} — posprint")
84
format!("{name} — posprint")
84
}
85
}
@@ -98,93 +99,139 @@ impl PosPrintApp {98
self.file_path = Some(path);
99
self.file_path = Some(path);
99
self.dirty = false;
100
self.dirty = false;
100
self.parse_error = None;
101
self.parse_error = None;
101
self.status_message = Some("File loaded".into());
102
self.action_error = None;
103
self.undo = TextUndo::default();
102
}
104
}
103
105
104
fn validate_parse(&mut self) {
106
fn new_document(&mut self) {
105
self.parse_error = match parse(&self.body) {
107
*self = Self::default();
106
Ok(_) => None,
107
Err(e) => Some(e.to_string()),
108
};
109
}
108
}
110
109
111
fn open_print_dialog(&mut self) {
110
fn open_file_dialog(&mut self) {
112
self.print_error = None;
111
if let Some(path) = rfd::FileDialog::new()
113
match parse(&self.body) {
112
.add_filter("POS template", &["pos"])
114
Ok(doc) => {
113
.pick_file()
115
self.print_param_names = collect_parameter_names(&doc);
114
{
116
self.print_param_inputs.clear();
115
match PosFile::load_from_path(&path) {
117
for name in &self.print_param_names {
116
Ok(file) => self.load_pos_file(path, file),
118
let value = self
117
Err(e) => self.action_error = Some(format!("Open failed: {e:?}")),
119
.last_params
120
.get(name)
121
.cloned()
122
.unwrap_or_default();
123
self.print_param_inputs.insert(name.clone(), value);
124
}
125
self.show_print_dialog = true;
126
self.refresh_printers();
127
}
118
}
128
Err(e) => self.parse_error = Some(e.to_string()),
129
}
119
}
130
}
120
}
131
121
132
fn refresh_printers(&mut self) {
122
fn save(&mut self) {
133
match list_usb_serial_printers() {
123
if let Some(path) = self.file_path.clone() {
134
Ok(list) => {
124
self.save_to_path(path);
135
self.printers = list;
125
} else {
136
if self.selected_printer.is_none() && !self.printers.is_empty() {
126
self.save_as();
137
self.selected_printer = Some(0);
138
}
139
}
140
Err(e) => self.print_error = Some(e.to_string()),
141
}
127
}
142
}
128
}
143
129
144
fn execute_print(&mut self) {
130
fn save_as(&mut self) {
145
self.print_error = None;
131
if let Some(path) = rfd::FileDialog::new()
146
if parse(&self.body).is_err() {
132
.add_filter("POS template", &["pos"])
147
self.print_error = Some("Template has parse errors".into());
133
.set_file_name("document.pos")
148
return;
134
.save_file()
135
{
136
self.save_to_path(path);
149
}
137
}
138
}
150
139
151
for name in &self.print_param_names {
140
fn save_to_path(&mut self, path: PathBuf) {
152
if !self.print_param_inputs.contains_key(name) {
141
if let Err(e) = self.pos_file().save_to_path(&path) {
153
self.print_error = Some(format!("Missing value for parameter {name}"));
142
self.action_error = Some(format!("Save failed: {e:?}"));
154
return;
143
} else {
155
}
144
self.file_path = Some(path);
145
self.dirty = false;
146
self.action_error = None;
156
}
147
}
148
}
157
149
158
self.last_params = self.print_param_inputs.clone();
150
fn validate_parse(&mut self) {
151
self.parse_error = match parse(&self.body) {
152
Ok(_) => None,
153
Err(e) => Some(e.to_string()),
154
};
155
}
159
156
160
let base_dir = self.file_path.as_ref().and_then(|p| p.parent());
157
fn handle_shortcuts(&mut self, ctx: &egui::Context) {
161
let file = self.pos_file();
158
let mut new_doc = false;
162
let bytes = match pipeline::encode_pos_file(&file, base_dir, &self.last_params) {
159
let mut open = false;
163
Ok(b) => b,
160
let mut save = false;
164
Err(e) => {
161
let mut undo = false;
165
self.print_error = Some(e.to_string());
162
let mut redo = false;
166
return;
163
164
ctx.input(|i| {
165
if i.modifiers.command {
166
if i.key_pressed(egui::Key::S) {
167
save = true;
168
}
169
if i.key_pressed(egui::Key::N) {
170
new_doc = true;
171
}
172
if i.key_pressed(egui::Key::O) {
173
open = true;
174
}
175
if i.key_pressed(egui::Key::Z) {
176
if i.modifiers.shift {
177
redo = true;
178
} else {
179
undo = true;
180
}
181
}
182
if i.modifiers.shift && i.key_pressed(egui::Key::Y) {
183
redo = true;
184
}
167
}
185
}
168
};
186
});
169
187
170
let idx = match self.selected_printer {
188
if new_doc {
171
Some(i) if i < self.printers.len() => i,
189
self.new_document();
172
_ => {
190
}
173
self.print_error = Some("Select a printer".into());
191
if open {
174
return;
192
self.open_file_dialog();
193
}
194
if save {
195
self.save();
196
}
197
if undo {
198
if let Some(prev) = self.undo.undo(&self.body) {
199
self.body = prev;
200
self.dirty = true;
175
}
201
}
176
};
202
}
203
if redo {
204
if let Some(next) = self.undo.redo(&self.body) {
205
self.body = next;
206
self.dirty = true;
207
}
208
}
209
}
177
210
178
let port = self.printers[idx].port_name.clone();
211
fn apply_print_dialog_params_to_preview(&mut self) {
179
match SerialTransport::open(&port) {
212
self.print_dialog.apply_inputs_to_last_params();
180
Ok(mut transport) => match print_bytes(&mut transport, &bytes) {
213
}
181
Ok(()) => {
214
182
self.status_message = Some(format!("Printed to {port}"));
215
fn close_print_dialog(&mut self) {
183
self.show_print_dialog = false;
216
self.apply_print_dialog_params_to_preview();
184
}
217
self.show_print_dialog = false;
185
Err(e) => self.print_error = Some(format!("{e:?}")),
218
}
186
},
219
187
Err(e) => self.print_error = Some(format!("{e:?}")),
220
fn open_print_dialog(&mut self) {
221
match self.print_dialog.prepare(&self.body) {
222
Ok(()) => self.show_print_dialog = true,
223
Err(e) => self.parse_error = Some(e),
224
}
225
}
226
227
fn execute_print(&mut self) {
228
if self.print_dialog.execute_print(
229
&self.body,
230
&self.metadata,
231
self.file_path.as_ref(),
232
) == PrintExecuteResult::Printed
233
{
234
self.show_print_dialog = false;
188
}
235
}
189
}
236
}
190
}
237
}
@@ -192,49 +239,22 @@ impl PosPrintApp {192
impl eframe::App for PosPrintApp {
239
impl eframe::App for PosPrintApp {
193
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
240
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
194
self.validate_parse();
241
self.validate_parse();
242
self.handle_shortcuts(ctx);
243
self.print_dialog.poll_printer_discovery(ctx);
195
244
196
egui::TopBottomPanel::top("menu").show(ctx, |ui| {
245
egui::TopBottomPanel::top("menu").show(ctx, |ui| {
197
ui.horizontal_wrapped(|ui| {
246
ui.horizontal_wrapped(|ui| {
198
if ui.button("New").clicked() {
247
if ui.button("New").clicked() {
199
*self = Self::default();
248
self.new_document();
200
}
249
}
201
if ui.button("Open").clicked() {
250
if ui.button("Open").clicked() {
202
if let Some(path) = rfd::FileDialog::new()
251
self.open_file_dialog();
203
.add_filter("POS template", &["pos"])
204
.pick_file()
205
{
206
match PosFile::load_from_path(&path) {
207
Ok(file) => self.load_pos_file(path, file),
208
Err(e) => self.status_message = Some(format!("Open failed: {e:?}")),
209
}
210
}
211
}
252
}
212
if ui.button("Save").clicked() {
253
if ui.button("Save").clicked() {
213
if let Some(path) = self.file_path.clone() {
254
self.save();
214
if let Err(e) = self.pos_file().save_to_path(&path) {
215
self.status_message = Some(format!("Save failed: {e:?}"));
216
} else {
217
self.dirty = false;
218
self.status_message = Some("Saved".into());
219
}
220
} else if ui.button("Save As").clicked() {
221
// handled below when no path
222
}
223
}
255
}
224
if ui.button("Save As").clicked() {
256
if ui.button("Save As").clicked() {
225
if let Some(path) = rfd::FileDialog::new()
257
self.save_as();
226
.add_filter("POS template", &["pos"])
227
.set_file_name("document.pos")
228
.save_file()
229
{
230
if let Err(e) = self.pos_file().save_to_path(&path) {
231
self.status_message = Some(format!("Save failed: {e:?}"));
232
} else {
233
self.file_path = Some(path);
234
self.dirty = false;
235
self.status_message = Some("Saved".into());
236
}
237
}
238
}
258
}
239
if ui.button("Print").clicked() {
259
if ui.button("Print").clicked() {
240
self.open_print_dialog();
260
self.open_print_dialog();
@@ -264,6 +284,22 @@ impl eframe::App for PosPrintApp {264
}
284
}
265
}
285
}
266
});
286
});
287
ui.menu_button("Date / time", |ui| {
288
for opt in date_time_insert_options() {
289
if ui.button(&opt.label).clicked() {
290
self.insert_snippet(&opt.snippet);
291
ui.close_menu();
292
}
293
}
294
});
295
ui.menu_button("Parameters", |ui| {
296
for opt in parameter_insert_options(&self.body) {
297
if ui.button(&opt.label).clicked() {
298
self.insert_snippet(&opt.snippet);
299
ui.close_menu();
300
}
301
}
302
});
267
ui.separator();
303
ui.separator();
268
if ui.button("@feed").clicked() {
304
if ui.button("@feed").clicked() {
269
self.insert_snippet("@feed 3\n");
305
self.insert_snippet("@feed 3\n");
@@ -287,63 +323,80 @@ impl eframe::App for PosPrintApp {287
self.metadata.page_width_mm = width;
323
self.metadata.page_width_mm = width;
288
self.dirty = true;
324
self.dirty = true;
289
}
325
}
290
ui.label("Preview:");
291
egui::ComboBox::from_id_salt("preview_mode")
292
.selected_text(match self.metadata.preview_mode {
293
PreviewMode::Autoscale => "Auto-scale",
294
PreviewMode::Fixed => "Fixed width",
295
})
296
.show_ui(ui, |ui| {
297
if ui
298
.selectable_value(
299
&mut self.metadata.preview_mode,
300
PreviewMode::Autoscale,
301
"Auto-scale",
302
)
303
.changed()
304
{
305
self.dirty = true;
306
}
307
if ui
308
.selectable_value(
309
&mut self.metadata.preview_mode,
310
PreviewMode::Fixed,
311
"Fixed width",
312
)
313
.changed()
314
{
315
self.dirty = true;
316
}
317
});
318
});
326
});
319
327
320
if let Some(err) = &self.parse_error {
328
if let Some(err) = &self.parse_error {
321
ui.colored_label(egui::Color32::RED, err);
329
ui.colored_label(egui::Color32::RED, err);
322
}
330
}
323
if let Some(msg) = &self.status_message {
331
if let Some(err) = &self.action_error {
324
ui.label(msg);
332
ui.colored_label(egui::Color32::RED, err);
325
}
333
}
326
});
334
});
327
335
328
egui::TopBottomPanel::bottom("tabs").show(ctx, |ui| {
336
egui::TopBottomPanel::bottom("tabs").show(ctx, |ui| {
329
ui.horizontal(|ui| {
337
ui.horizontal(|ui| {
330
ui.selectable_value(&mut self.tab, Tab::Editor, "Editor");
338
ui.selectable_value(&mut self.view_mode, ViewMode::Design, "Design");
331
ui.selectable_value(&mut self.tab, Tab::Preview, "Preview");
339
ui.selectable_value(&mut self.view_mode, ViewMode::Help, "Help");
332
ui.selectable_value(&mut self.tab, Tab::Help, "Help");
333
});
340
});
334
});
341
});
335
342
336
egui::CentralPanel::default().show(ctx, |ui| match self.tab {
343
match self.view_mode {
337
Tab::Editor => self.show_editor(ui),
344
ViewMode::Design => {
338
Tab::Preview => self.show_preview(ui),
345
egui::SidePanel::right("preview_panel")
339
Tab::Help => self.show_help(ui),
346
.resizable(true)
340
});
347
.min_width(260.0)
348
.default_width(380.0)
349
.show(ctx, |ui| {
350
ui.heading("Preview");
351
ui.horizontal(|ui| {
352
ui.label(format!(
353
"Page width: {:.0} mm",
354
self.metadata.page_width_mm
355
));
356
ui.separator();
357
ui.label("Zoom:");
358
ui.add(
359
egui::Slider::new(&mut self.preview_zoom, 0.25..=4.0)
360
.logarithmic(true)
361
.show_value(true),
362
);
363
if ui.button("100%").clicked() {
364
self.preview_zoom = 1.0;
365
}
366
});
367
ui.separator();
368
self.show_preview(ui, ctx);
369
});
370
371
egui::CentralPanel::default().show(ctx, |ui| {
372
ui.heading("Editor");
373
self.show_editor(ui);
374
});
375
}
376
ViewMode::Help => {
377
egui::CentralPanel::default().show(ctx, |ui| {
378
help_view::show_help(ui, HELP_MARKDOWN);
379
});
380
}
381
}
341
382
342
if self.show_print_dialog {
383
if self.show_print_dialog {
384
let mut open = true;
343
egui::Window::new("Print")
385
egui::Window::new("Print")
344
.collapsible(false)
386
.collapsible(false)
345
.resizable(true)
387
.resizable(true)
346
.show(ctx, |ui| self.show_print_dialog_ui(ui));
388
.open(&mut open)
389
.show(ctx, |ui| {
390
match self.print_dialog.show_ui(ui, "Cancel") {
391
PrintDialogAction::Cancel => self.close_print_dialog(),
392
PrintDialogAction::Print => self.execute_print(),
393
PrintDialogAction::None => {}
394
}
395
});
396
if !open {
397
self.apply_print_dialog_params_to_preview();
398
}
399
self.show_print_dialog = open;
347
}
400
}
348
401
349
ctx.send_viewport_cmd(egui::ViewportCommand::Title(self.title()));
402
ctx.send_viewport_cmd(egui::ViewportCommand::Title(self.title()));
@@ -352,251 +405,254 @@ impl eframe::App for PosPrintApp {352
405
353
impl PosPrintApp {
406
impl PosPrintApp {
354
fn insert_snippet(&mut self, snippet: &str) {
407
fn insert_snippet(&mut self, snippet: &str) {
408
let before = self.body.clone();
355
let (body, cursor) = insert_at_cursor(&self.body, self.editor_cursor, snippet);
409
let (body, cursor) = insert_at_cursor(&self.body, self.editor_cursor, snippet);
356
self.body = body;
410
self.body = body;
357
self.editor_cursor = cursor;
411
self.editor_cursor = cursor;
412
self.undo.record(before);
358
self.dirty = true;
413
self.dirty = true;
359
self.tab = Tab::Editor;
414
self.view_mode = ViewMode::Design;
360
}
415
}
361
416
362
fn show_editor(&mut self, ui: &mut egui::Ui) {
417
fn show_editor(&mut self, ui: &mut egui::Ui) {
418
let before = self.body.clone();
419
let cursor_before = self.editor_cursor;
420
421
let directive_ctx = at_directive_prefix(&self.body, cursor_before);
422
let autocomplete_active = directive_ctx.as_ref().is_some_and(|(_, prefix)| {
423
complete_directive(prefix).is_some() || directive_ghost_suffix(prefix).is_some()
424
});
425
426
let mut tab_completion: Option<(usize, String)> = None;
427
if autocomplete_active {
428
if let Some((at_index, prefix)) = directive_ctx.clone() {
429
ui.input_mut(|input| {
430
if input.key_pressed(egui::Key::Tab) && !input.modifiers.any() {
431
tab_completion = Some((at_index, prefix));
432
input.consume_key(egui::Modifiers::NONE, egui::Key::Tab);
433
}
434
});
435
}
436
}
437
363
let output = egui::TextEdit::multiline(&mut self.body)
438
let output = egui::TextEdit::multiline(&mut self.body)
364
.id_salt("main_editor")
439
.id_salt("main_editor")
365
.desired_width(f32::INFINITY)
440
.desired_width(f32::INFINITY)
366
.desired_rows(30)
441
.desired_rows(30)
367
.font(egui::TextStyle::Monospace)
442
.font(egui::TextStyle::Monospace)
443
.lock_focus(true)
368
.show(ui);
444
.show(ui);
369
445
446
if autocomplete_active {
447
output.response.request_focus();
448
}
449
370
self.editor_cursor = output
450
self.editor_cursor = output
371
.state
451
.cursor_range
372
.cursor
452
.as_ref()
373
.char_range()
453
.map(|r| r.primary.ccursor.index)
374
.map(|r| r.primary.index)
454
.or_else(|| {
455
output
456
.state
457
.cursor
458
.char_range()
459
.map(|r| r.primary.index)
460
})
375
.unwrap_or(self.body.len());
461
.unwrap_or(self.body.len());
376
462
377
if output.response.changed() {
463
if let Some((at_index, prefix)) = tab_completion {
464
if let Some(completed) = complete_directive(&prefix) {
465
let undo_before = self.body.clone();
466
self.editor_cursor =
467
apply_directive_completion(&mut self.body, at_index, self.editor_cursor, completed);
468
self.undo.record(undo_before);
469
self.dirty = true;
470
}
471
} else if output.response.changed() {
472
self.undo.record(before);
378
self.dirty = true;
473
self.dirty = true;
379
}
474
}
380
475
381
if let Some((_start, prefix)) = at_directive_prefix(&self.body, self.editor_cursor) {
476
if let Some((_at_index, prefix)) = at_directive_prefix(&self.body, self.editor_cursor) {
382
self.autocomplete = directive_completions(&prefix);
477
if let Some(suffix) = directive_ghost_suffix(&prefix) {
383
if !self.autocomplete.is_empty() {
478
if let Some(cursor_range) = &output.cursor_range {
384
egui::Area::new(egui::Id::new("directive_ac"))
479
let font_id = egui::TextStyle::Monospace.resolve(ui.style());
385
.order(egui::Order::Foreground)
480
let pos = output.galley.pos_from_cursor(&cursor_range.primary);
386
.show(ui.ctx(), |ui| {
481
let ghost_pos = output.galley_pos + pos.min.to_vec2();
387
ui.set_min_width(120.0);
482
let ghost_color = ui.visuals().weak_text_color();
388
ui.label("Directive autocomplete:");
483
ui.painter().text(
389
for dir in &self.autocomplete {
484
ghost_pos,
390
if ui.button(format!("@{dir}")).clicked() {
485
egui::Align2::LEFT_TOP,
391
let line_start = self.body[..self.editor_cursor]
486
suffix,
392
.rfind('\n')
487
font_id,
393
.map(|i| i + 1)
488
ghost_color,
394
.unwrap_or(0);
489
);
395
let line_end = self.body[self.editor_cursor..]
490
}
396
.find('\n')
397
.map(|i| self.editor_cursor + i)
398
.unwrap_or(self.body.len());
399
let mut line = self.body[line_start..line_end].to_string();
400
if let Some(at) = line.find('@') {
401
line.replace_range(at + 1.., dir);
402
self.body.replace_range(line_start..line_end, &line);
403
self.editor_cursor = line_start + at + 1 + dir.len();
404
self.dirty = true;
405
}
406
}
407
}
408
});
409
}
491
}
410
} else {
411
self.autocomplete.clear();
412
}
492
}
413
}
493
}
414
494
415
fn show_preview(&mut self, ui: &mut egui::Ui) {
495
fn show_preview(&mut self, ui: &mut egui::Ui, ctx: &egui::Context) {
416
let Ok(doc) = parse(&self.body) else {
496
let Ok(doc) = parse(&self.body) else {
417
ui.label("Fix parse errors to preview.");
497
ui.label("Fix parse errors to preview.");
418
return;
498
return;
419
};
499
};
420
let model = render_preview(&doc, &self.metadata);
421
let chars = model.width_chars as f32;
422
let scale = match self.metadata.preview_mode {
423
PreviewMode::Autoscale => {
424
let avail = ui.available_width().max(200.0);
425
(avail / (chars * 8.0)).clamp(0.8, 3.0)
426
}
427
PreviewMode::Fixed => model.width_mm / 80.0,
428
};
429
500
430
egui::Frame::canvas(ui.style()).show(ui, |ui| {
501
let base_dir = self.file_path.as_ref().and_then(|p| p.parent());
431
let width = chars * 8.0 * scale;
502
let model = render_preview(
432
let (_id, rect) = ui.allocate_space(egui::vec2(width, ui.available_height()));
503
&doc,
433
let painter = ui.painter_at(rect);
504
&self.metadata,
434
painter.rect_filled(rect, 4.0, egui::Color32::WHITE);
505
base_dir,
435
painter.rect_stroke(
506
&self.print_dialog.last_params,
436
rect,
507
);
437
4.0,
508
let visual_scale = preview_zoom_scale(self.preview_zoom);
438
egui::Stroke::new(1.0_f32, egui::Color32::GRAY),
509
let content_width = preview_content_width_px(&self.metadata) * visual_scale;
439
egui::StrokeKind::Inside,
510
let padding = 8.0 * visual_scale;
440
);
511
441
512
egui::ScrollArea::both()
442
let mut y = rect.min.y + 8.0;
513
.auto_shrink([false; 2])
443
let line_height = 18.0 * scale;
514
.show(ui, |ui| {
444
for line in &model.lines {
515
egui::Frame::canvas(ui.style()).show(ui, |ui| {
445
match line {
516
let mut total_height = padding * 2.0;
446
PreviewLine::Text {
517
for line in &model.lines {
447
content,
518
total_height += line_height(line, visual_scale) + 2.0;
448
align,
449
style,
450
} => {
451
let font_id = match style {
452
TextStyle::Heading1 => egui::FontId::proportional(22.0 * scale),
453
TextStyle::Heading2 => egui::FontId::proportional(18.0 * scale),
454
TextStyle::Bold => egui::FontId::proportional(16.0 * scale),
455
TextStyle::Italic => egui::FontId::proportional(15.0 * scale),
456
TextStyle::Code => egui::FontId::monospace(14.0 * scale),
457
TextStyle::Normal => egui::FontId::monospace(14.0 * scale),
458
};
459
let galley = painter.layout(
460
content.clone(),
461
font_id,
462
egui::Color32::BLACK,
463
width,
464
);
465
let x = match align {
466
dsl::Align::Left => rect.min.x + 8.0,
467
dsl::Align::Center => {
468
rect.min.x + (width - galley.size().x) / 2.0
469
}
470
dsl::Align::Right => rect.max.x - galley.size().x - 8.0,
471
};
472
painter.galley(egui::pos2(x, y), galley, egui::Color32::BLACK);
473
y += line_height;
474
}
475
PreviewLine::Rule => {
476
painter.line_segment(
477
[
478
egui::pos2(rect.min.x + 8.0, y),
479
egui::pos2(rect.max.x - 8.0, y),
480
],
481
egui::Stroke::new(1.0_f32, egui::Color32::DARK_GRAY),
482
);
483
y += line_height;
484
}
485
PreviewLine::Barcode { symbology, data, .. } => {
486
let text = format!("[barcode {symbology}: {data}]");
487
let galley = painter.layout(
488
text,
489
egui::FontId::monospace(14.0 * scale),
490
egui::Color32::BLACK,
491
width,
492
);
493
painter.galley(egui::pos2(rect.min.x + 8.0, y), galley, egui::Color32::BLACK);
494
y += line_height * 1.5;
495
}
496
PreviewLine::Qr { data, .. } => {
497
let text = format!("[qr: {data}]");
498
let galley = painter.layout(
499
text,
500
egui::FontId::monospace(14.0 * scale),
501
egui::Color32::BLACK,
502
width,
503
);
504
painter.galley(egui::pos2(rect.min.x + 8.0, y), galley, egui::Color32::BLACK);
505
y += line_height * 1.5;
506
}
507
PreviewLine::Image { label, .. } => {
508
let galley = painter.layout(
509
label.clone(),
510
egui::FontId::monospace(14.0 * scale),
511
egui::Color32::DARK_BLUE,
512
width,
513
);
514
painter.galley(egui::pos2(rect.min.x + 8.0, y), galley, egui::Color32::BLACK);
515
y += line_height * 1.5;
516
}
519
}
517
PreviewLine::Spacer(n) => {
520
total_height = total_height.max(100.0);
518
y += line_height * (*n as f32);
521
522
let (_id, rect) = ui.allocate_space(egui::vec2(content_width, total_height));
523
let painter = ui.painter_at(rect);
524
painter.rect_filled(rect, 4.0, egui::Color32::WHITE);
525
painter.rect_stroke(
526
rect,
527
4.0,
528
egui::Stroke::new(1.0_f32, egui::Color32::GRAY),
529
egui::StrokeKind::Inside,
530
);
531
532
let mut y = rect.min.y + padding;
533
let inner_width = content_width - padding * 2.0;
534
535
for (idx, line) in model.lines.iter().enumerate() {
536
match line {
537
PreviewLine::Text {
538
content,
539
align,
540
style,
541
} => {
542
let font_id = text_font(*style, visual_scale);
543
let galley = painter.layout_no_wrap(
544
content.clone(),
545
font_id,
546
egui::Color32::BLACK,
547
);
548
let x = align_x(*align, rect.min.x + padding, inner_width, galley.size().x);
549
let line_h = galley.size().y;
550
painter.galley(egui::pos2(x, y), galley, egui::Color32::BLACK);
551
y += line_h + 4.0 * visual_scale;
552
}
553
PreviewLine::Rule => {
554
painter.line_segment(
555
[
556
egui::pos2(rect.min.x + padding, y),
557
egui::pos2(rect.max.x - padding, y),
558
],
559
egui::Stroke::new(1.0_f32, egui::Color32::DARK_GRAY),
560
);
561
y += 12.0 * visual_scale;
562
}
563
PreviewLine::Graphic { image, align } => {
564
let tex = gray_to_texture(
565
ctx,
566
&format!("preview_graphic_{idx}"),
567
image,
568
);
569
let size = egui::vec2(
570
tex.size()[0] as f32 * visual_scale,
571
tex.size()[1] as f32 * visual_scale,
572
);
573
let x = align_x(*align, rect.min.x + padding, inner_width, size.x);
574
painter.image(
575
tex.id(),
576
egui::Rect::from_min_size(egui::pos2(x, y), size),
577
egui::Rect::from_min_max(egui::pos2(0.0, 0.0), egui::pos2(1.0, 1.0)),
578
egui::Color32::WHITE,
579
);
580
y += size.y + 4.0 * visual_scale;
581
}
582
PreviewLine::Error { message, align } => {
583
let galley = painter.layout(
584
message.clone(),
585
egui::FontId::proportional(12.0 * visual_scale),
586
egui::Color32::RED,
587
inner_width,
588
);
589
let x = align_x(*align, rect.min.x + padding, inner_width, galley.size().x);
590
let line_h = galley.size().y;
591
painter.galley(egui::pos2(x, y), galley, egui::Color32::RED);
592
y += line_h + 4.0 * visual_scale;
593
}
594
PreviewLine::Spacer(n) => {
595
y += 18.0 * visual_scale * (*n as f32);
596
}
597
}
519
}
598
}
520
}
599
});
521
}
600
});
522
});
523
}
601
}
602
}
524
603
525
fn show_help(&mut self, ui: &mut egui::Ui) {
604
fn text_font(style: TextStyle, scale: f32) -> egui::FontId {
526
egui::ScrollArea::vertical().show(ui, |ui| {
605
match style {
527
ui.add(
606
TextStyle::Heading1 => egui::FontId::proportional(22.0 * scale),
528
egui::Label::new(HELP_MARKDOWN)
607
TextStyle::Heading2 => egui::FontId::proportional(18.0 * scale),
529
.wrap()
608
TextStyle::Bold => egui::FontId::proportional(16.0 * scale),
530
.selectable(true),
609
TextStyle::Italic => egui::FontId::proportional(15.0 * scale),
531
);
610
TextStyle::Code => egui::FontId::monospace(14.0 * scale),
532
});
611
TextStyle::Normal => egui::FontId::monospace(14.0 * scale),
533
}
612
}
613
}
534
614
535
fn show_print_dialog_ui(&mut self, ui: &mut egui::Ui) {
615
fn align_x(align: dsl::Align, left: f32, inner_width: f32, item_width: f32) -> f32 {
536
ui.heading("Parameters");
616
match align {
537
if self.print_param_names.is_empty() {
617
dsl::Align::Left => left,
538
ui.label("No parameters in this template.");
618
dsl::Align::Center => left + (inner_width - item_width) / 2.0,
539
} else {
619
dsl::Align::Right => left + inner_width - item_width,
540
for name in self.print_param_names.clone() {
541
ui.horizontal(|ui| {
542
ui.label(format!("{name}:"));
543
let entry = self
544
.print_param_inputs
545
.entry(name)
546
.or_insert_with(String::new);
547
ui.text_edit_singleline(entry);
548
});
549
}
550
}
551
552
ui.separator();
553
ui.heading("USB printer");
554
if ui.button("Refresh").clicked() {
555
self.refresh_printers();
556
}
557
if self.printers.is_empty() {
558
ui.label("No serial ports found. Connect a USB printer and refresh.");
559
} else {
560
for (i, printer) in self.printers.iter().enumerate() {
561
ui.selectable_value(&mut self.selected_printer, Some(i), &printer.display_name);
562
}
563
}
564
565
if let Some(err) = &self.print_error {
566
ui.colored_label(egui::Color32::RED, err);
567
}
568
569
ui.horizontal(|ui| {
570
if ui.button("Cancel").clicked() {
571
self.show_print_dialog = false;
572
}
573
if ui.button("Print").clicked() {
574
self.execute_print();
575
}
576
});
577
}
620
}
578
}
621
}
579
622
580
fn default_template() -> String {
623
fn line_height(line: &PreviewLine, scale: f32) -> f32 {
581
r#"# ${StoreName}
624
match line {
582
:center:
625
PreviewLine::Text { style, .. } => match style {
583
626
TextStyle::Heading1 => 28.0 * scale,
584
Receipt: ${DocumentNumber}
627
TextStyle::Heading2 => 24.0 * scale,
585
Date: ${Date}
628
_ => 18.0 * scale,
586
629
},
587
---
630
PreviewLine::Rule => 12.0 * scale,
588
:right:
631
PreviewLine::Graphic { image, .. } => image.height() as f32 * scale + 4.0,
589
**TOTAL: ${GrandTotal}**
632
PreviewLine::Error { .. } => 18.0 * scale,
633
PreviewLine::Spacer(n) => 18.0 * scale * (*n as f32),
634
}
635
}
590
636
591
@barcode CODE128 ${DocumentNumber}
637
fn gray_to_texture(
592
@feed 2
638
ctx: &egui::Context,
593
@qr https://example.com/r/${DocumentNumber}
639
id: &str,
640
image: &image::GrayImage,
641
) -> egui::TextureHandle {
642
let (w, h) = image.dimensions();
643
let pixels: Vec<egui::Color32> = image
644
.pixels()
645
.map(|p| egui::Color32::from_gray(p.0[0]))
646
.collect();
647
let color_image = egui::ColorImage {
648
size: [w as usize, h as usize],
649
pixels,
650
};
651
ctx.load_texture(id, color_image, egui::TextureOptions::NEAREST)
652
}
594
653
595
Thank you!
654
fn default_template() -> String {
596
@feed 4
655
String::new()
597
@cut
598
"#
599
.to_string()
600
}
656
}
601
657
602
#[cfg(test)]
658
#[cfg(test)]
@@ -604,17 +660,16 @@ mod tests {604
use super::*;
660
use super::*;
605
661
606
#[test]
662
#[test]
607
fn default_template_parses() {
663
fn default_template_is_empty() {
608
let app = PosPrintApp::default();
664
let app = PosPrintApp::default();
665
assert!(app.body.is_empty());
609
assert!(parse(&app.body).is_ok());
666
assert!(parse(&app.body).is_ok());
610
}
667
}
611
668
612
#[test]
669
#[test]
613
fn collect_params_from_default_template() {
670
fn title_shows_asterisk_before_name_when_dirty() {
614
let app = PosPrintApp::default();
671
let mut app = PosPrintApp::default();
615
let doc = parse(&app.body).unwrap();
672
app.dirty = true;
616
let names = collect_parameter_names(&doc);
673
assert!(app.title().starts_with("* "));
617
assert!(names.contains(&"StoreName".to_string()));
618
assert!(names.contains(&"DocumentNumber".to_string()));
619
}
674
}
620
}
675
}
@@ -14,6 +14,14 @@ use crate::pipeline;
14
14
pub struct Cli {
15
15
#[command(subcommand)]
16
16
pub command: Option<Commands>,
17
18
/// Open the print dialog only (no editor). Exits after printing or cancel.
19
#[arg(long)]
20
pub print: bool,
21
22
/// POS template file to open in the GUI editor
23
#[arg(value_name = "FILE")]
24
pub file: Option<PathBuf>,
17
25
}
18
26
19
27
#[derive(Subcommand, Debug)]
@@ -41,7 +49,9 @@ pub fn run(cli: Cli) -> i32 {
41
49
}
42
50
},
43
51
None => {
44
eprintln!("No subcommand specified. Run `posprint --help` or start without arguments for the GUI.");
52
eprintln!(
53
"No subcommand specified. Run `posprint --help` or start without arguments for the GUI."
54
);
45
55
1
46
56
}
47
57
}
@@ -81,4 +91,12 @@ mod tests {
81
91
fn rejects_invalid_pair() {
82
92
assert!(parse_params(&["nope".into()]).is_err());
83
93
}
94
95
#[test]
96
fn accepts_print_flag_with_file() {
97
use clap::Parser;
98
let cli = Cli::parse_from(["posprint", "--print", "doc.pos"]);
99
assert!(cli.print);
100
assert_eq!(cli.file.as_ref().unwrap().to_str().unwrap(), "doc.pos");
101
}
84
102
}
@@ -14,6 +14,14 @@ use crate::pipeline;14
pub struct Cli {
14
pub struct Cli {
15
#[command(subcommand)]
15
#[command(subcommand)]
16
pub command: Option<Commands>,
16
pub command: Option<Commands>,
17
18
/// Open the print dialog only (no editor). Exits after printing or cancel.
19
#[arg(long)]
20
pub print: bool,
21
22
/// POS template file to open in the GUI editor
23
#[arg(value_name = "FILE")]
24
pub file: Option<PathBuf>,
17
}
25
}
18
26
19
#[derive(Subcommand, Debug)]
27
#[derive(Subcommand, Debug)]
@@ -41,7 +49,9 @@ pub fn run(cli: Cli) -> i32 {41
}
49
}
42
},
50
},
43
None => {
51
None => {
44
eprintln!("No subcommand specified. Run `posprint --help` or start without arguments for the GUI.");
52
eprintln!(
53
"No subcommand specified. Run `posprint --help` or start without arguments for the GUI."
54
);
45
1
55
1
46
}
56
}
47
}
57
}
@@ -81,4 +91,12 @@ mod tests {81
fn rejects_invalid_pair() {
91
fn rejects_invalid_pair() {
82
assert!(parse_params(&["nope".into()]).is_err());
92
assert!(parse_params(&["nope".into()]).is_err());
83
}
93
}
94
95
#[test]
96
fn accepts_print_flag_with_file() {
97
use clap::Parser;
98
let cli = Cli::parse_from(["posprint", "--print", "doc.pos"]);
99
assert!(cli.print);
100
assert_eq!(cli.file.as_ref().unwrap().to_str().unwrap(), "doc.pos");
101
}
84
}
102
}
@@ -0,0 +1,168 @@
1
//! Locale-aware date/time formatting for `@date` and `@time` directives.
2
3
use std::os::raw::{c_char, c_int};
4
5
use chrono::{Datelike, Local, Timelike};
6
use libc::tm;
7
8
use crate::dsl::TimeFormatSpec;
9
10
#[cfg(unix)]
11
use libc::LC_TIME;
12
13
#[cfg(windows)]
14
const LC_TIME: c_int = 5;
15
16
extern "C" {
17
fn strftime(s: *mut c_char, max: usize, format: *const c_char, tm: *const tm) -> usize;
18
fn setlocale(category: c_int, locale: *const c_char) -> *mut c_char;
19
}
20
21
/// Format the current local date. `None` uses the system regional short date (`%x`).
22
pub fn format_date(format: Option<&str>) -> String {
23
format_date_at(format, Local::now())
24
}
25
26
/// Format the current local time.
27
pub fn format_time(spec: TimeFormatSpec) -> String {
28
format_time_at(spec, Local::now())
29
}
30
31
pub fn format_date_at(
32
format: Option<&str>,
33
at: chrono::DateTime<Local>,
34
) -> String {
35
let tm = datetime_to_tm(&at);
36
apply_locale();
37
match format {
38
None => strftime_tm("%x", &tm),
39
Some(pattern) => {
40
let strftime_fmt = date_pattern_to_strftime(pattern);
41
strftime_tm(&strftime_fmt, &tm)
42
}
43
}
44
}
45
46
pub fn format_time_at(spec: TimeFormatSpec, at: chrono::DateTime<Local>) -> String {
47
match spec {
48
TimeFormatSpec::Hours24 => format!("{:02}:{:02}", at.hour(), at.minute()),
49
TimeFormatSpec::Hours12 => {
50
let hour = at.hour();
51
let (hour12, ampm) = match hour {
52
0 => (12, "AM"),
53
1..=11 => (hour, "AM"),
54
12 => (12, "PM"),
55
_ => (hour - 12, "PM"),
56
};
57
format!("{:02}:{:02} {ampm}", hour12, at.minute())
58
}
59
}
60
}
61
62
fn datetime_to_tm(dt: &chrono::DateTime<Local>) -> tm {
63
tm {
64
tm_sec: dt.second() as i32,
65
tm_min: dt.minute() as i32,
66
tm_hour: dt.hour() as i32,
67
tm_mday: dt.day() as i32,
68
tm_mon: (dt.month() - 1) as i32,
69
tm_year: (dt.year() - 1900) as i32,
70
tm_wday: dt.weekday().num_days_from_sunday() as i32,
71
tm_yday: 0,
72
tm_isdst: -1,
73
}
74
}
75
76
fn apply_locale() {
77
unsafe {
78
setlocale(LC_TIME, b"\0".as_ptr().cast());
79
}
80
}
81
82
fn strftime_tm(fmt: &str, tm: &tm) -> String {
83
let mut buf = [0u8; 128];
84
let fmt = std::ffi::CString::new(fmt).unwrap_or_else(|_| std::ffi::CString::new("%x").unwrap());
85
let len = unsafe { strftime(buf.as_mut_ptr().cast(), buf.len(), fmt.as_ptr(), tm) };
86
if len == 0 {
87
return String::new();
88
}
89
String::from_utf8_lossy(&buf[..len]).into_owned()
90
}
91
92
/// Convert template tokens (`DD`, `YYYY`, `MMMM`, …) to `strftime` format.
93
pub fn date_pattern_to_strftime(pattern: &str) -> String {
94
const TOKENS: &[(&str, &str)] = &[
95
("MMMM", "%B"),
96
("YYYY", "%Y"),
97
("MMM", "%b"),
98
("DD", "%d"),
99
("MM", "%m"),
100
("YY", "%y"),
101
];
102
103
let mut out = String::with_capacity(pattern.len());
104
let mut i = 0;
105
while i < pattern.len() {
106
let mut matched = false;
107
for (token, replacement) in TOKENS {
108
if pattern[i..].starts_with(token) {
109
out.push_str(replacement);
110
i += token.len();
111
matched = true;
112
break;
113
}
114
}
115
if matched {
116
continue;
117
}
118
let ch = pattern[i..].chars().next().expect("byte index on char boundary");
119
if ch == '%' {
120
out.push_str("%%");
121
} else {
122
out.push(ch);
123
}
124
i += ch.len_utf8();
125
}
126
out
127
}
128
129
#[cfg(test)]
130
mod tests {
131
use super::*;
132
use chrono::TimeZone;
133
134
fn sample_dt() -> chrono::DateTime<Local> {
135
Local
136
.with_ymd_and_hms(2026, 7, 15, 16, 3, 0)
137
.single()
138
.expect("valid sample datetime")
139
}
140
141
#[test]
142
fn maps_custom_date_tokens() {
143
assert_eq!(date_pattern_to_strftime("DD-YYYY-MM"), "%d-%Y-%m");
144
assert_eq!(date_pattern_to_strftime("MMMM DD"), "%B %d");
145
}
146
147
#[test]
148
fn formats_custom_date_pattern() {
149
let dt = sample_dt();
150
assert_eq!(format_date_at(Some("DD-YYYY-MM"), dt), "15-2026-07");
151
let named = format_date_at(Some("MMMM DD"), dt);
152
assert!(named.contains("15"));
153
}
154
155
#[test]
156
fn formats_time_24h_and_12h() {
157
let dt = sample_dt();
158
assert_eq!(format_time_at(TimeFormatSpec::Hours24, dt), "16:03");
159
assert_eq!(format_time_at(TimeFormatSpec::Hours12, dt), "04:03 PM");
160
}
161
162
#[test]
163
fn regional_date_is_non_empty() {
164
let dt = sample_dt();
165
let formatted = format_date_at(None, dt);
166
assert!(!formatted.is_empty());
167
}
168
}
@@ -0,0 +1,168 @@1
//! Locale-aware date/time formatting for `@date` and `@time` directives.
2
3
use std::os::raw::{c_char, c_int};
4
5
use chrono::{Datelike, Local, Timelike};
6
use libc::tm;
7
8
use crate::dsl::TimeFormatSpec;
9
10
#[cfg(unix)]
11
use libc::LC_TIME;
12
13
#[cfg(windows)]
14
const LC_TIME: c_int = 5;
15
16
extern "C" {
17
fn strftime(s: *mut c_char, max: usize, format: *const c_char, tm: *const tm) -> usize;
18
fn setlocale(category: c_int, locale: *const c_char) -> *mut c_char;
19
}
20
21
/// Format the current local date. `None` uses the system regional short date (`%x`).
22
pub fn format_date(format: Option<&str>) -> String {
23
format_date_at(format, Local::now())
24
}
25
26
/// Format the current local time.
27
pub fn format_time(spec: TimeFormatSpec) -> String {
28
format_time_at(spec, Local::now())
29
}
30
31
pub fn format_date_at(
32
format: Option<&str>,
33
at: chrono::DateTime<Local>,
34
) -> String {
35
let tm = datetime_to_tm(&at);
36
apply_locale();
37
match format {
38
None => strftime_tm("%x", &tm),
39
Some(pattern) => {
40
let strftime_fmt = date_pattern_to_strftime(pattern);
41
strftime_tm(&strftime_fmt, &tm)
42
}
43
}
44
}
45
46
pub fn format_time_at(spec: TimeFormatSpec, at: chrono::DateTime<Local>) -> String {
47
match spec {
48
TimeFormatSpec::Hours24 => format!("{:02}:{:02}", at.hour(), at.minute()),
49
TimeFormatSpec::Hours12 => {
50
let hour = at.hour();
51
let (hour12, ampm) = match hour {
52
0 => (12, "AM"),
53
1..=11 => (hour, "AM"),
54
12 => (12, "PM"),
55
_ => (hour - 12, "PM"),
56
};
57
format!("{:02}:{:02} {ampm}", hour12, at.minute())
58
}
59
}
60
}
61
62
fn datetime_to_tm(dt: &chrono::DateTime<Local>) -> tm {
63
tm {
64
tm_sec: dt.second() as i32,
65
tm_min: dt.minute() as i32,
66
tm_hour: dt.hour() as i32,
67
tm_mday: dt.day() as i32,
68
tm_mon: (dt.month() - 1) as i32,
69
tm_year: (dt.year() - 1900) as i32,
70
tm_wday: dt.weekday().num_days_from_sunday() as i32,
71
tm_yday: 0,
72
tm_isdst: -1,
73
}
74
}
75
76
fn apply_locale() {
77
unsafe {
78
setlocale(LC_TIME, b"\0".as_ptr().cast());
79
}
80
}
81
82
fn strftime_tm(fmt: &str, tm: &tm) -> String {
83
let mut buf = [0u8; 128];
84
let fmt = std::ffi::CString::new(fmt).unwrap_or_else(|_| std::ffi::CString::new("%x").unwrap());
85
let len = unsafe { strftime(buf.as_mut_ptr().cast(), buf.len(), fmt.as_ptr(), tm) };
86
if len == 0 {
87
return String::new();
88
}
89
String::from_utf8_lossy(&buf[..len]).into_owned()
90
}
91
92
/// Convert template tokens (`DD`, `YYYY`, `MMMM`, …) to `strftime` format.
93
pub fn date_pattern_to_strftime(pattern: &str) -> String {
94
const TOKENS: &[(&str, &str)] = &[
95
("MMMM", "%B"),
96
("YYYY", "%Y"),
97
("MMM", "%b"),
98
("DD", "%d"),
99
("MM", "%m"),
100
("YY", "%y"),
101
];
102
103
let mut out = String::with_capacity(pattern.len());
104
let mut i = 0;
105
while i < pattern.len() {
106
let mut matched = false;
107
for (token, replacement) in TOKENS {
108
if pattern[i..].starts_with(token) {
109
out.push_str(replacement);
110
i += token.len();
111
matched = true;
112
break;
113
}
114
}
115
if matched {
116
continue;
117
}
118
let ch = pattern[i..].chars().next().expect("byte index on char boundary");
119
if ch == '%' {
120
out.push_str("%%");
121
} else {
122
out.push(ch);
123
}
124
i += ch.len_utf8();
125
}
126
out
127
}
128
129
#[cfg(test)]
130
mod tests {
131
use super::*;
132
use chrono::TimeZone;
133
134
fn sample_dt() -> chrono::DateTime<Local> {
135
Local
136
.with_ymd_and_hms(2026, 7, 15, 16, 3, 0)
137
.single()
138
.expect("valid sample datetime")
139
}
140
141
#[test]
142
fn maps_custom_date_tokens() {
143
assert_eq!(date_pattern_to_strftime("DD-YYYY-MM"), "%d-%Y-%m");
144
assert_eq!(date_pattern_to_strftime("MMMM DD"), "%B %d");
145
}
146
147
#[test]
148
fn formats_custom_date_pattern() {
149
let dt = sample_dt();
150
assert_eq!(format_date_at(Some("DD-YYYY-MM"), dt), "15-2026-07");
151
let named = format_date_at(Some("MMMM DD"), dt);
152
assert!(named.contains("15"));
153
}
154
155
#[test]
156
fn formats_time_24h_and_12h() {
157
let dt = sample_dt();
158
assert_eq!(format_time_at(TimeFormatSpec::Hours24, dt), "16:03");
159
assert_eq!(format_time_at(TimeFormatSpec::Hours12, dt), "04:03 PM");
160
}
161
162
#[test]
163
fn regional_date_is_non_empty() {
164
let dt = sample_dt();
165
let formatted = format_date_at(None, dt);
166
assert!(!formatted.is_empty());
167
}
168
}
@@ -32,6 +32,7 @@ pub enum Block {
32
32
},
33
33
Heading {
34
34
level: u8,
35
align: Align,
35
36
inlines: Vec<Inline>,
36
37
},
37
38
Rule,
@@ -58,6 +59,21 @@ pub enum Block {
58
59
version: Option<u8>,
59
60
align: Align,
60
61
},
62
Date {
63
format: Option<String>,
64
align: Align,
65
},
66
Time {
67
format: TimeFormatSpec,
68
align: Align,
69
},
70
}
71
72
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
73
pub enum TimeFormatSpec {
74
#[default]
75
Hours24,
76
Hours12,
61
77
}
62
78
63
79
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
@@ -32,6 +32,7 @@ pub enum Block {32
},
32
},
33
Heading {
33
Heading {
34
level: u8,
34
level: u8,
35
align: Align,
35
inlines: Vec<Inline>,
36
inlines: Vec<Inline>,
36
},
37
},
37
Rule,
38
Rule,
@@ -58,6 +59,21 @@ pub enum Block {58
version: Option<u8>,
59
version: Option<u8>,
59
align: Align,
60
align: Align,
60
},
61
},
62
Date {
63
format: Option<String>,
64
align: Align,
65
},
66
Time {
67
format: TimeFormatSpec,
68
align: Align,
69
},
70
}
71
72
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
73
pub enum TimeFormatSpec {
74
#[default]
75
Hours24,
76
Hours12,
61
}
77
}
62
78
63
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
79
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
@@ -8,49 +8,85 @@ pub fn parse(source: &str) -> Result<Document, ParseError> {
8
8
let mut blocks = Vec::new();
9
9
let mut lines = source.lines().peekable();
10
10
let mut line_no = 0usize;
11
let mut current_align = Align::Left;
11
12
12
13
while let Some(raw_line) = lines.next() {
13
14
line_no += 1;
14
15
let line = raw_line.trim_end();
15
if line.trim().is_empty() {
16
continue;
17
}
18
16
19
if line.starts_with('#') {
20
blocks.push(parse_heading(line, line_no)?);
21
continue;
22
}
17
let (content, align_for_block) = match parse_align_line(line) {
18
Some((align, None)) => {
19
current_align = align;
20
continue;
21
}
22
Some((align, Some(rest))) => {
23
current_align = align;
24
(rest, current_align)
25
}
26
None => (line, current_align),
27
};
23
28
24
if line.trim() == "---" {
25
blocks.push(Block::Rule);
29
if is_blank_feed_line(content) {
30
blocks.push(Block::Feed(1));
26
31
continue;
27
32
}
28
33
29
if line.trim_start().starts_with('@') {
30
blocks.push(parse_directive(line.trim(), line_no)?);
34
let segments = split_aligned_segments(content, align_for_block);
35
if segments.is_empty() {
31
36
continue;
32
37
}
33
38
34
let (align, first) = parse_align_prefix(line);
35
let mut paragraph_lines = vec![first];
36
while let Some(&next) = lines.peek() {
37
if next.trim().is_empty()
38
|| next.starts_with('#')
39
|| next.trim() == "---"
40
|| next.trim_start().starts_with('@')
41
|| starts_with_align_prefix(next)
42
{
43
break;
39
for (idx, (seg_align, seg_text)) in segments.iter().enumerate() {
40
current_align = *seg_align;
41
let allow_multiline_paragraph = segments.len() == 1 && idx == segments.len() - 1;
42
43
if is_blank_feed_line(seg_text) {
44
blocks.push(Block::Feed(1));
45
continue;
46
}
47
48
if seg_text.starts_with('#') {
49
blocks.push(parse_heading(seg_text, line_no, *seg_align)?);
50
continue;
51
}
52
53
if seg_text.trim() == "---" {
54
blocks.push(Block::Rule);
55
continue;
56
}
57
58
if seg_text.trim_start().starts_with('@') {
59
blocks.push(parse_directive(seg_text.trim(), line_no, *seg_align)?);
60
continue;
61
}
62
63
if allow_multiline_paragraph {
64
let mut paragraph_lines = vec![seg_text.clone()];
65
while let Some(&next) = lines.peek() {
66
if is_blank_feed_line(next)
67
|| next.starts_with('#')
68
|| next.trim() == "---"
69
|| next.trim_start().starts_with('@')
70
|| parse_align_line(next).is_some()
71
{
72
break;
73
}
74
line_no += 1;
75
lines.next();
76
paragraph_lines.push(next.trim_end().to_string());
77
}
78
let text = paragraph_lines.join("\n");
79
blocks.push(Block::Paragraph {
80
align: *seg_align,
81
inlines: parse_inlines(&text, line_no, 1)?,
82
});
83
} else {
84
blocks.push(Block::Paragraph {
85
align: *seg_align,
86
inlines: parse_inlines(seg_text, line_no, 1)?,
87
});
44
88
}
45
line_no += 1;
46
lines.next();
47
paragraph_lines.push(next.trim_end().to_string());
48
89
}
49
let text = paragraph_lines.join("\n");
50
blocks.push(Block::Paragraph {
51
align,
52
inlines: parse_inlines(&text, line_no, 1)?,
53
});
54
90
}
55
91
56
92
Ok(Document { blocks })
@@ -89,28 +125,89 @@ fn strip_comments(source: &str) -> String {
89
125
out
90
126
}
91
127
92
fn starts_with_align_prefix(line: &str) -> bool {
93
let t = line.trim_start();
94
t.starts_with(":left:")
95
|| t.starts_with(":center:")
96
|| t.starts_with(":right:")
97
}
98
99
fn parse_align_prefix(line: &str) -> (Align, String) {
128
/// Parse `:left:`, `:center:`, `:centre:`, or `:right:` at line start.
129
/// Returns the alignment and optional remaining content on the same line.
130
fn parse_align_line(line: &str) -> Option<(Align, Option<&str>)> {
100
131
let trimmed = line.trim_start();
101
132
if let Some(rest) = trimmed.strip_prefix(":left:") {
102
return (Align::Left, rest.trim_start().to_string());
133
let rest = rest.trim_start();
134
return Some((
135
Align::Left,
136
if rest.is_empty() { None } else { Some(rest) },
137
));
103
138
}
104
139
if let Some(rest) = trimmed.strip_prefix(":center:") {
105
return (Align::Center, rest.trim_start().to_string());
140
let rest = rest.trim_start();
141
return Some((
142
Align::Center,
143
if rest.is_empty() { None } else { Some(rest) },
144
));
145
}
146
if let Some(rest) = trimmed.strip_prefix(":centre:") {
147
let rest = rest.trim_start();
148
return Some((
149
Align::Center,
150
if rest.is_empty() { None } else { Some(rest) },
151
));
106
152
}
107
153
if let Some(rest) = trimmed.strip_prefix(":right:") {
108
return (Align::Right, rest.trim_start().to_string());
154
let rest = rest.trim_start();
155
return Some((
156
Align::Right,
157
if rest.is_empty() { None } else { Some(rest) },
158
));
159
}
160
None
161
}
162
163
/// Split line content on embedded `:left:`, `:center:`, `:centre:`, or `:right:` markers.
164
fn split_aligned_segments(content: &str, start_align: Align) -> Vec<(Align, String)> {
165
let mut segments = Vec::new();
166
let mut align = start_align;
167
let mut rest = content;
168
169
while let Some((pos, new_align, marker_len)) = find_next_align_marker(rest) {
170
let before = rest[..pos].trim();
171
if !before.is_empty() {
172
segments.push((align, before.to_string()));
173
}
174
align = new_align;
175
rest = rest[pos + marker_len..].trim_start();
176
}
177
178
let tail = rest.trim();
179
if !tail.is_empty() {
180
segments.push((align, tail.to_string()));
181
}
182
segments
183
}
184
185
fn find_next_align_marker(s: &str) -> Option<(usize, Align, usize)> {
186
const MARKERS: &[(&str, Align)] = &[
187
(":left:", Align::Left),
188
(":center:", Align::Center),
189
(":centre:", Align::Center),
190
(":right:", Align::Right),
191
];
192
193
let mut best: Option<(usize, Align, usize)> = None;
194
for (pat, marker_align) in MARKERS {
195
if let Some(pos) = s.find(pat) {
196
if best.is_none() || pos < best.unwrap().0 {
197
best = Some((pos, *marker_align, pat.len()));
198
}
199
}
109
200
}
110
(Align::Left, line.to_string())
201
best
111
202
}
112
203
113
fn parse_heading(line: &str, line_no: usize) -> Result<Block, ParseError> {
204
/// True only when a line has no visible content (empty or whitespace-only).
205
/// Lines with DSL markers (`:right:`, `@feed`, `#`, etc.) are never feed lines.
206
fn is_blank_feed_line(line: &str) -> bool {
207
line.chars().all(|c| c.is_whitespace())
208
}
209
210
fn parse_heading(line: &str, line_no: usize, align: Align) -> Result<Block, ParseError> {
114
211
let mut level = 0u8;
115
212
for ch in line.chars() {
116
213
if ch == '#' {
@@ -128,11 +225,12 @@ fn parse_heading(line: &str, line_no: usize) -> Result<Block, ParseError> {
128
225
}
129
226
Ok(Block::Heading {
130
227
level,
228
align,
131
229
inlines: parse_inlines(text, line_no, level as usize + 1)?,
132
230
})
133
231
}
134
232
135
fn parse_directive(line: &str, line_no: usize) -> Result<Block, ParseError> {
233
fn parse_directive(line: &str, line_no: usize, default_align: Align) -> Result<Block, ParseError> {
136
234
let body = line
137
235
.trim_start()
138
236
.strip_prefix('@')
@@ -150,20 +248,26 @@ fn parse_directive(line: &str, line_no: usize) -> Result<Block, ParseError> {
150
248
Ok(Block::Feed(lines))
151
249
}
152
250
"cut" => Ok(Block::Cut),
153
"image" => parse_image_directive(parts.collect(), line_no),
154
"barcode" => parse_barcode_directive(parts.collect(), line_no),
155
"qr" => parse_qr_directive(parts.collect(), line_no),
251
"image" => parse_image_directive(parts.collect(), line_no, default_align),
252
"barcode" => parse_barcode_directive(parts.collect(), line_no, default_align),
253
"qr" => parse_qr_directive(parts.collect(), line_no, default_align),
254
"date" => parse_date_directive(parts.collect(), line_no, default_align),
255
"time" => parse_time_directive(parts.collect(), line_no, default_align),
156
256
_ => Err(err(line_no, 1, format!("unknown directive @{name}"))),
157
257
}
158
258
}
159
259
160
fn parse_image_directive(parts: Vec<&str>, line_no: usize) -> Result<Block, ParseError> {
260
fn parse_image_directive(
261
parts: Vec<&str>,
262
line_no: usize,
263
default_align: Align,
264
) -> Result<Block, ParseError> {
161
265
if parts.is_empty() {
162
266
return Err(err(line_no, 1, "@image requires a path"));
163
267
}
164
268
let path = parts[0].to_string();
165
269
let mut width = ImageWidth::Default;
166
let mut align = Align::Left;
270
let mut align = default_align;
167
271
for attr in &parts[1..] {
168
272
if let Some((k, v)) = attr.split_once('=') {
169
273
match k.to_ascii_lowercase().as_str() {
@@ -188,7 +292,11 @@ fn parse_image_directive(parts: Vec<&str>, line_no: usize) -> Result<Block, Pars
188
292
Ok(Block::Image { path, width, align })
189
293
}
190
294
191
fn parse_barcode_directive(parts: Vec<&str>, line_no: usize) -> Result<Block, ParseError> {
295
fn parse_barcode_directive(
296
parts: Vec<&str>,
297
line_no: usize,
298
default_align: Align,
299
) -> Result<Block, ParseError> {
192
300
if parts.len() < 2 {
193
301
return Err(err(
194
302
line_no,
@@ -228,7 +336,7 @@ fn parse_barcode_directive(parts: Vec<&str>, line_no: usize) -> Result<Block, Pa
228
336
let data = parts[data_idx].to_string();
229
337
let attr_start = data_idx + 1;
230
338
let mut height = 64u8;
231
let mut align = Align::Left;
339
let mut align = default_align;
232
340
let mut show_text = true;
233
341
for attr in &parts[attr_start..] {
234
342
if let Some((k, v)) = attr.split_once('=') {
@@ -254,7 +362,59 @@ fn parse_barcode_directive(parts: Vec<&str>, line_no: usize) -> Result<Block, Pa
254
362
})
255
363
}
256
364
257
fn parse_qr_directive(parts: Vec<&str>, line_no: usize) -> Result<Block, ParseError> {
365
fn parse_date_directive(
366
parts: Vec<&str>,
367
_line_no: usize,
368
default_align: Align,
369
) -> Result<Block, ParseError> {
370
let pattern = parts.join(" ");
371
let format = if pattern.is_empty() {
372
None
373
} else {
374
Some(pattern)
375
};
376
Ok(Block::Date {
377
format,
378
align: default_align,
379
})
380
}
381
382
fn parse_time_directive(
383
parts: Vec<&str>,
384
line_no: usize,
385
default_align: Align,
386
) -> Result<Block, ParseError> {
387
use super::TimeFormatSpec;
388
let spec = match parts.first().map(|s| s.to_ascii_lowercase()).as_deref() {
389
None => TimeFormatSpec::Hours24,
390
Some("12h") => TimeFormatSpec::Hours12,
391
Some("24h") => TimeFormatSpec::Hours24,
392
Some(other) => {
393
return Err(err(
394
line_no,
395
1,
396
format!("unknown @time format '{other}' (use 12h or 24h)"),
397
));
398
}
399
};
400
if parts.len() > 1 {
401
return Err(err(
402
line_no,
403
1,
404
"@time accepts at most one format argument (12h or 24h)",
405
));
406
}
407
Ok(Block::Time {
408
format: spec,
409
align: default_align,
410
})
411
}
412
413
fn parse_qr_directive(
414
parts: Vec<&str>,
415
line_no: usize,
416
default_align: Align,
417
) -> Result<Block, ParseError> {
258
418
if parts.is_empty() {
259
419
return Err(err(line_no, 1, "@qr requires data"));
260
420
}
@@ -272,7 +432,7 @@ fn parse_qr_directive(parts: Vec<&str>, line_no: usize) -> Result<Block, ParseEr
272
432
let attr_start = data_idx + 1;
273
433
let mut size = 4u8;
274
434
let mut ecc = QrEcc::M;
275
let mut align = Align::Left;
435
let mut align = default_align;
276
436
let mut version = None;
277
437
for attr in &parts[attr_start..] {
278
438
if let Some((k, v)) = attr.split_once('=') {
@@ -435,7 +595,18 @@ fn err(line: usize, column: usize, message: impl Into<String>) -> ParseError {
435
595
#[cfg(test)]
436
596
mod tests {
437
597
use super::*;
438
use crate::dsl::{BarcodeMode, BarcodeSymbology, Inline};
598
use crate::dsl::{BarcodeMode, BarcodeSymbology, Inline, TimeFormatSpec};
599
600
fn inlines_to_text(inlines: &[Inline]) -> String {
601
let mut out = String::new();
602
for inline in inlines {
603
match inline {
604
Inline::Text(t) | Inline::Code(t) | Inline::Param(t) => out.push_str(t),
605
Inline::Bold(inner) | Inline::Italic(inner) => out.push_str(&inlines_to_text(inner)),
606
}
607
}
608
out
609
}
439
610
440
611
#[test]
441
612
fn parses_heading_and_paragraph() {
@@ -468,8 +639,10 @@ mod tests {
468
639
469
640
#[test]
470
641
fn strips_comments() {
471
let doc = parse("<!-- hidden -->\nVisible").unwrap();
642
let doc = parse("<!-- hidden -->Visible").unwrap();
472
643
assert_eq!(doc.blocks.len(), 1);
644
let doc = parse("<!-- hidden -->\nVisible").unwrap();
645
assert!(matches!(doc.blocks[0], Block::Feed(1)));
473
646
}
474
647
475
648
#[test]
@@ -486,6 +659,168 @@ mod tests {
486
659
assert_eq!(*align, Align::Center);
487
660
}
488
661
662
#[test]
663
fn persistent_center_applies_to_heading_and_directives() {
664
let doc = parse(
665
":center:\n# Hello\n@qr ${Data}\n@barcode RASTER CODE128 ${Data}\n:left:\nLeft\n",
666
)
667
.unwrap();
668
assert_eq!(doc.blocks.len(), 4);
669
assert!(matches!(
670
doc.blocks[0],
671
Block::Heading {
672
align: Align::Center,
673
..
674
}
675
));
676
assert!(matches!(
677
doc.blocks[1],
678
Block::Qr {
679
align: Align::Center,
680
..
681
}
682
));
683
assert!(matches!(
684
doc.blocks[2],
685
Block::Barcode {
686
align: Align::Center,
687
..
688
}
689
));
690
assert!(matches!(
691
doc.blocks[3],
692
Block::Paragraph {
693
align: Align::Left,
694
..
695
}
696
));
697
}
698
699
#[test]
700
fn persistent_center_groups_following_paragraph_lines() {
701
let doc = parse(":center:\nLine one\nLine two").unwrap();
702
assert_eq!(doc.blocks.len(), 1);
703
let Block::Paragraph { align, inlines } = &doc.blocks[0] else {
704
panic!();
705
};
706
assert_eq!(*align, Align::Center);
707
assert_eq!(inlines_to_text(inlines), "Line one\nLine two");
708
}
709
710
#[test]
711
fn align_prefix_on_same_line_sets_persistent_state() {
712
let doc = parse(":center: Inline\nNext").unwrap();
713
assert_eq!(doc.blocks.len(), 1);
714
let Block::Paragraph { align, inlines } = &doc.blocks[0] else {
715
panic!();
716
};
717
assert_eq!(*align, Align::Center);
718
assert_eq!(inlines_to_text(inlines), "Inline\nNext");
719
}
720
721
#[test]
722
fn multiple_align_prefixes_on_one_line() {
723
let doc = parse(":left:left :right:right").unwrap();
724
assert_eq!(doc.blocks.len(), 2);
725
assert!(matches!(
726
doc.blocks[0],
727
Block::Paragraph {
728
align: Align::Left,
729
..
730
}
731
));
732
assert!(matches!(
733
doc.blocks[1],
734
Block::Paragraph {
735
align: Align::Right,
736
..
737
}
738
));
739
let Block::Paragraph { inlines: left, .. } = &doc.blocks[0] else {
740
panic!();
741
};
742
let Block::Paragraph { inlines: right, .. } = &doc.blocks[1] else {
743
panic!();
744
};
745
assert_eq!(inlines_to_text(left), "left");
746
assert_eq!(inlines_to_text(right), "right");
747
}
748
749
#[test]
750
fn align_only_line_does_not_emit_block() {
751
let doc = parse(":center:\n:center:").unwrap();
752
assert!(doc.blocks.is_empty());
753
}
754
755
#[test]
756
fn parses_date_and_time_directives() {
757
let doc = parse("@date\n@date DD-YYYY-MM\n@time\n@time 12h").unwrap();
758
assert!(matches!(
759
doc.blocks[0],
760
Block::Date {
761
format: None,
762
..
763
}
764
));
765
assert!(matches!(
766
doc.blocks[1],
767
Block::Date {
768
format: Some(ref f),
769
..
770
} if f == "DD-YYYY-MM"
771
));
772
assert!(matches!(
773
doc.blocks[2],
774
Block::Time {
775
format: TimeFormatSpec::Hours24,
776
..
777
}
778
));
779
assert!(matches!(
780
doc.blocks[3],
781
Block::Time {
782
format: TimeFormatSpec::Hours12,
783
..
784
}
785
));
786
}
787
788
#[test]
789
fn rejects_unknown_time_format() {
790
assert!(parse("@time 24").is_err());
791
}
792
793
#[test]
794
fn blank_line_inserts_feed() {
795
let doc = parse("A\n\nB").unwrap();
796
assert!(matches!(doc.blocks[1], Block::Feed(1)));
797
}
798
799
#[test]
800
fn whitespace_only_line_inserts_feed() {
801
let doc = parse("A\n \nB").unwrap();
802
assert!(matches!(doc.blocks[1], Block::Feed(1)));
803
}
804
805
#[test]
806
fn dsl_marker_lines_are_not_feed() {
807
for src in [
808
":left:\nNext",
809
":center:\nNext",
810
":right:\nNext",
811
":centre:\nNext",
812
"# Title\n",
813
"---\n",
814
"@cut\n",
815
] {
816
let doc = parse(src).unwrap();
817
assert!(
818
!doc.blocks.iter().any(|b| matches!(b, Block::Feed(1))),
819
"unexpected feed for {src:?}"
820
);
821
}
822
}
823
489
824
#[test]
490
825
fn parses_raster_barcode() {
491
826
let doc = parse("@barcode RASTER CODE128 ABC").unwrap();
@@ -8,49 +8,85 @@ pub fn parse(source: &str) -> Result<Document, ParseError> {8
let mut blocks = Vec::new();
8
let mut blocks = Vec::new();
9
let mut lines = source.lines().peekable();
9
let mut lines = source.lines().peekable();
10
let mut line_no = 0usize;
10
let mut line_no = 0usize;
11
let mut current_align = Align::Left;
11
12
12
while let Some(raw_line) = lines.next() {
13
while let Some(raw_line) = lines.next() {
13
line_no += 1;
14
line_no += 1;
14
let line = raw_line.trim_end();
15
let line = raw_line.trim_end();
15
if line.trim().is_empty() {
16
continue;
17
}
18
16
19
if line.starts_with('#') {
17
let (content, align_for_block) = match parse_align_line(line) {
20
blocks.push(parse_heading(line, line_no)?);
18
Some((align, None)) => {
21
continue;
19
current_align = align;
22
}
20
continue;
21
}
22
Some((align, Some(rest))) => {
23
current_align = align;
24
(rest, current_align)
25
}
26
None => (line, current_align),
27
};
23
28
24
if line.trim() == "---" {
29
if is_blank_feed_line(content) {
25
blocks.push(Block::Rule);
30
blocks.push(Block::Feed(1));
26
continue;
31
continue;
27
}
32
}
28
33
29
if line.trim_start().starts_with('@') {
34
let segments = split_aligned_segments(content, align_for_block);
30
blocks.push(parse_directive(line.trim(), line_no)?);
35
if segments.is_empty() {
31
continue;
36
continue;
32
}
37
}
33
38
34
let (align, first) = parse_align_prefix(line);
39
for (idx, (seg_align, seg_text)) in segments.iter().enumerate() {
35
let mut paragraph_lines = vec![first];
40
current_align = *seg_align;
36
while let Some(&next) = lines.peek() {
41
let allow_multiline_paragraph = segments.len() == 1 && idx == segments.len() - 1;
37
if next.trim().is_empty()
42
38
|| next.starts_with('#')
43
if is_blank_feed_line(seg_text) {
39
|| next.trim() == "---"
44
blocks.push(Block::Feed(1));
40
|| next.trim_start().starts_with('@')
45
continue;
41
|| starts_with_align_prefix(next)
46
}
42
{
47
43
break;
48
if seg_text.starts_with('#') {
49
blocks.push(parse_heading(seg_text, line_no, *seg_align)?);
50
continue;
51
}
52
53
if seg_text.trim() == "---" {
54
blocks.push(Block::Rule);
55
continue;
56
}
57
58
if seg_text.trim_start().starts_with('@') {
59
blocks.push(parse_directive(seg_text.trim(), line_no, *seg_align)?);
60
continue;
61
}
62
63
if allow_multiline_paragraph {
64
let mut paragraph_lines = vec![seg_text.clone()];
65
while let Some(&next) = lines.peek() {
66
if is_blank_feed_line(next)
67
|| next.starts_with('#')
68
|| next.trim() == "---"
69
|| next.trim_start().starts_with('@')
70
|| parse_align_line(next).is_some()
71
{
72
break;
73
}
74
line_no += 1;
75
lines.next();
76
paragraph_lines.push(next.trim_end().to_string());
77
}
78
let text = paragraph_lines.join("\n");
79
blocks.push(Block::Paragraph {
80
align: *seg_align,
81
inlines: parse_inlines(&text, line_no, 1)?,
82
});
83
} else {
84
blocks.push(Block::Paragraph {
85
align: *seg_align,
86
inlines: parse_inlines(seg_text, line_no, 1)?,
87
});
44
}
88
}
45
line_no += 1;
46
lines.next();
47
paragraph_lines.push(next.trim_end().to_string());
48
}
89
}
49
let text = paragraph_lines.join("\n");
50
blocks.push(Block::Paragraph {
51
align,
52
inlines: parse_inlines(&text, line_no, 1)?,
53
});
54
}
90
}
55
91
56
Ok(Document { blocks })
92
Ok(Document { blocks })
@@ -89,28 +125,89 @@ fn strip_comments(source: &str) -> String {89
out
125
out
90
}
126
}
91
127
92
fn starts_with_align_prefix(line: &str) -> bool {
128
/// Parse `:left:`, `:center:`, `:centre:`, or `:right:` at line start.
93
let t = line.trim_start();
129
/// Returns the alignment and optional remaining content on the same line.
94
t.starts_with(":left:")
130
fn parse_align_line(line: &str) -> Option<(Align, Option<&str>)> {
95
|| t.starts_with(":center:")
96
|| t.starts_with(":right:")
97
}
98
99
fn parse_align_prefix(line: &str) -> (Align, String) {
100
let trimmed = line.trim_start();
131
let trimmed = line.trim_start();
101
if let Some(rest) = trimmed.strip_prefix(":left:") {
132
if let Some(rest) = trimmed.strip_prefix(":left:") {
102
return (Align::Left, rest.trim_start().to_string());
133
let rest = rest.trim_start();
134
return Some((
135
Align::Left,
136
if rest.is_empty() { None } else { Some(rest) },
137
));
103
}
138
}
104
if let Some(rest) = trimmed.strip_prefix(":center:") {
139
if let Some(rest) = trimmed.strip_prefix(":center:") {
105
return (Align::Center, rest.trim_start().to_string());
140
let rest = rest.trim_start();
141
return Some((
142
Align::Center,
143
if rest.is_empty() { None } else { Some(rest) },
144
));
145
}
146
if let Some(rest) = trimmed.strip_prefix(":centre:") {
147
let rest = rest.trim_start();
148
return Some((
149
Align::Center,
150
if rest.is_empty() { None } else { Some(rest) },
151
));
106
}
152
}
107
if let Some(rest) = trimmed.strip_prefix(":right:") {
153
if let Some(rest) = trimmed.strip_prefix(":right:") {
108
return (Align::Right, rest.trim_start().to_string());
154
let rest = rest.trim_start();
155
return Some((
156
Align::Right,
157
if rest.is_empty() { None } else { Some(rest) },
158
));
159
}
160
None
161
}
162
163
/// Split line content on embedded `:left:`, `:center:`, `:centre:`, or `:right:` markers.
164
fn split_aligned_segments(content: &str, start_align: Align) -> Vec<(Align, String)> {
165
let mut segments = Vec::new();
166
let mut align = start_align;
167
let mut rest = content;
168
169
while let Some((pos, new_align, marker_len)) = find_next_align_marker(rest) {
170
let before = rest[..pos].trim();
171
if !before.is_empty() {
172
segments.push((align, before.to_string()));
173
}
174
align = new_align;
175
rest = rest[pos + marker_len..].trim_start();
176
}
177
178
let tail = rest.trim();
179
if !tail.is_empty() {
180
segments.push((align, tail.to_string()));
181
}
182
segments
183
}
184
185
fn find_next_align_marker(s: &str) -> Option<(usize, Align, usize)> {
186
const MARKERS: &[(&str, Align)] = &[
187
(":left:", Align::Left),
188
(":center:", Align::Center),
189
(":centre:", Align::Center),
190
(":right:", Align::Right),
191
];
192
193
let mut best: Option<(usize, Align, usize)> = None;
194
for (pat, marker_align) in MARKERS {
195
if let Some(pos) = s.find(pat) {
196
if best.is_none() || pos < best.unwrap().0 {
197
best = Some((pos, *marker_align, pat.len()));
198
}
199
}
109
}
200
}
110
(Align::Left, line.to_string())
201
best
111
}
202
}
112
203
113
fn parse_heading(line: &str, line_no: usize) -> Result<Block, ParseError> {
204
/// True only when a line has no visible content (empty or whitespace-only).
205
/// Lines with DSL markers (`:right:`, `@feed`, `#`, etc.) are never feed lines.
206
fn is_blank_feed_line(line: &str) -> bool {
207
line.chars().all(|c| c.is_whitespace())
208
}
209
210
fn parse_heading(line: &str, line_no: usize, align: Align) -> Result<Block, ParseError> {
114
let mut level = 0u8;
211
let mut level = 0u8;
115
for ch in line.chars() {
212
for ch in line.chars() {
116
if ch == '#' {
213
if ch == '#' {
@@ -128,11 +225,12 @@ fn parse_heading(line: &str, line_no: usize) -> Result<Block, ParseError> {128
}
225
}
129
Ok(Block::Heading {
226
Ok(Block::Heading {
130
level,
227
level,
228
align,
131
inlines: parse_inlines(text, line_no, level as usize + 1)?,
229
inlines: parse_inlines(text, line_no, level as usize + 1)?,
132
})
230
})
133
}
231
}
134
232
135
fn parse_directive(line: &str, line_no: usize) -> Result<Block, ParseError> {
233
fn parse_directive(line: &str, line_no: usize, default_align: Align) -> Result<Block, ParseError> {
136
let body = line
234
let body = line
137
.trim_start()
235
.trim_start()
138
.strip_prefix('@')
236
.strip_prefix('@')
@@ -150,20 +248,26 @@ fn parse_directive(line: &str, line_no: usize) -> Result<Block, ParseError> {150
Ok(Block::Feed(lines))
248
Ok(Block::Feed(lines))
151
}
249
}
152
"cut" => Ok(Block::Cut),
250
"cut" => Ok(Block::Cut),
153
"image" => parse_image_directive(parts.collect(), line_no),
251
"image" => parse_image_directive(parts.collect(), line_no, default_align),
154
"barcode" => parse_barcode_directive(parts.collect(), line_no),
252
"barcode" => parse_barcode_directive(parts.collect(), line_no, default_align),
155
"qr" => parse_qr_directive(parts.collect(), line_no),
253
"qr" => parse_qr_directive(parts.collect(), line_no, default_align),
254
"date" => parse_date_directive(parts.collect(), line_no, default_align),
255
"time" => parse_time_directive(parts.collect(), line_no, default_align),
156
_ => Err(err(line_no, 1, format!("unknown directive @{name}"))),
256
_ => Err(err(line_no, 1, format!("unknown directive @{name}"))),
157
}
257
}
158
}
258
}
159
259
160
fn parse_image_directive(parts: Vec<&str>, line_no: usize) -> Result<Block, ParseError> {
260
fn parse_image_directive(
261
parts: Vec<&str>,
262
line_no: usize,
263
default_align: Align,
264
) -> Result<Block, ParseError> {
161
if parts.is_empty() {
265
if parts.is_empty() {
162
return Err(err(line_no, 1, "@image requires a path"));
266
return Err(err(line_no, 1, "@image requires a path"));
163
}
267
}
164
let path = parts[0].to_string();
268
let path = parts[0].to_string();
165
let mut width = ImageWidth::Default;
269
let mut width = ImageWidth::Default;
166
let mut align = Align::Left;
270
let mut align = default_align;
167
for attr in &parts[1..] {
271
for attr in &parts[1..] {
168
if let Some((k, v)) = attr.split_once('=') {
272
if let Some((k, v)) = attr.split_once('=') {
169
match k.to_ascii_lowercase().as_str() {
273
match k.to_ascii_lowercase().as_str() {
@@ -188,7 +292,11 @@ fn parse_image_directive(parts: Vec<&str>, line_no: usize) -> Result<Block, Pars188
Ok(Block::Image { path, width, align })
292
Ok(Block::Image { path, width, align })
189
}
293
}
190
294
191
fn parse_barcode_directive(parts: Vec<&str>, line_no: usize) -> Result<Block, ParseError> {
295
fn parse_barcode_directive(
296
parts: Vec<&str>,
297
line_no: usize,
298
default_align: Align,
299
) -> Result<Block, ParseError> {
192
if parts.len() < 2 {
300
if parts.len() < 2 {
193
return Err(err(
301
return Err(err(
194
line_no,
302
line_no,
@@ -228,7 +336,7 @@ fn parse_barcode_directive(parts: Vec<&str>, line_no: usize) -> Result<Block, Pa228
let data = parts[data_idx].to_string();
336
let data = parts[data_idx].to_string();
229
let attr_start = data_idx + 1;
337
let attr_start = data_idx + 1;
230
let mut height = 64u8;
338
let mut height = 64u8;
231
let mut align = Align::Left;
339
let mut align = default_align;
232
let mut show_text = true;
340
let mut show_text = true;
233
for attr in &parts[attr_start..] {
341
for attr in &parts[attr_start..] {
234
if let Some((k, v)) = attr.split_once('=') {
342
if let Some((k, v)) = attr.split_once('=') {
@@ -254,7 +362,59 @@ fn parse_barcode_directive(parts: Vec<&str>, line_no: usize) -> Result<Block, Pa254
})
362
})
255
}
363
}
256
364
257
fn parse_qr_directive(parts: Vec<&str>, line_no: usize) -> Result<Block, ParseError> {
365
fn parse_date_directive(
366
parts: Vec<&str>,
367
_line_no: usize,
368
default_align: Align,
369
) -> Result<Block, ParseError> {
370
let pattern = parts.join(" ");
371
let format = if pattern.is_empty() {
372
None
373
} else {
374
Some(pattern)
375
};
376
Ok(Block::Date {
377
format,
378
align: default_align,
379
})
380
}
381
382
fn parse_time_directive(
383
parts: Vec<&str>,
384
line_no: usize,
385
default_align: Align,
386
) -> Result<Block, ParseError> {
387
use super::TimeFormatSpec;
388
let spec = match parts.first().map(|s| s.to_ascii_lowercase()).as_deref() {
389
None => TimeFormatSpec::Hours24,
390
Some("12h") => TimeFormatSpec::Hours12,
391
Some("24h") => TimeFormatSpec::Hours24,
392
Some(other) => {
393
return Err(err(
394
line_no,
395
1,
396
format!("unknown @time format '{other}' (use 12h or 24h)"),
397
));
398
}
399
};
400
if parts.len() > 1 {
401
return Err(err(
402
line_no,
403
1,
404
"@time accepts at most one format argument (12h or 24h)",
405
));
406
}
407
Ok(Block::Time {
408
format: spec,
409
align: default_align,
410
})
411
}
412
413
fn parse_qr_directive(
414
parts: Vec<&str>,
415
line_no: usize,
416
default_align: Align,
417
) -> Result<Block, ParseError> {
258
if parts.is_empty() {
418
if parts.is_empty() {
259
return Err(err(line_no, 1, "@qr requires data"));
419
return Err(err(line_no, 1, "@qr requires data"));
260
}
420
}
@@ -272,7 +432,7 @@ fn parse_qr_directive(parts: Vec<&str>, line_no: usize) -> Result<Block, ParseEr272
let attr_start = data_idx + 1;
432
let attr_start = data_idx + 1;
273
let mut size = 4u8;
433
let mut size = 4u8;
274
let mut ecc = QrEcc::M;
434
let mut ecc = QrEcc::M;
275
let mut align = Align::Left;
435
let mut align = default_align;
276
let mut version = None;
436
let mut version = None;
277
for attr in &parts[attr_start..] {
437
for attr in &parts[attr_start..] {
278
if let Some((k, v)) = attr.split_once('=') {
438
if let Some((k, v)) = attr.split_once('=') {
@@ -435,7 +595,18 @@ fn err(line: usize, column: usize, message: impl Into<String>) -> ParseError {435
#[cfg(test)]
595
#[cfg(test)]
436
mod tests {
596
mod tests {
437
use super::*;
597
use super::*;
438
use crate::dsl::{BarcodeMode, BarcodeSymbology, Inline};
598
use crate::dsl::{BarcodeMode, BarcodeSymbology, Inline, TimeFormatSpec};
599
600
fn inlines_to_text(inlines: &[Inline]) -> String {
601
let mut out = String::new();
602
for inline in inlines {
603
match inline {
604
Inline::Text(t) | Inline::Code(t) | Inline::Param(t) => out.push_str(t),
605
Inline::Bold(inner) | Inline::Italic(inner) => out.push_str(&inlines_to_text(inner)),
606
}
607
}
608
out
609
}
439
610
440
#[test]
611
#[test]
441
fn parses_heading_and_paragraph() {
612
fn parses_heading_and_paragraph() {
@@ -468,8 +639,10 @@ mod tests {468
639
469
#[test]
640
#[test]
470
fn strips_comments() {
641
fn strips_comments() {
471
let doc = parse("<!-- hidden -->\nVisible").unwrap();
642
let doc = parse("<!-- hidden -->Visible").unwrap();
472
assert_eq!(doc.blocks.len(), 1);
643
assert_eq!(doc.blocks.len(), 1);
644
let doc = parse("<!-- hidden -->\nVisible").unwrap();
645
assert!(matches!(doc.blocks[0], Block::Feed(1)));
473
}
646
}
474
647
475
#[test]
648
#[test]
@@ -486,6 +659,168 @@ mod tests {486
assert_eq!(*align, Align::Center);
659
assert_eq!(*align, Align::Center);
487
}
660
}
488
661
662
#[test]
663
fn persistent_center_applies_to_heading_and_directives() {
664
let doc = parse(
665
":center:\n# Hello\n@qr ${Data}\n@barcode RASTER CODE128 ${Data}\n:left:\nLeft\n",
666
)
667
.unwrap();
668
assert_eq!(doc.blocks.len(), 4);
669
assert!(matches!(
670
doc.blocks[0],
671
Block::Heading {
672
align: Align::Center,
673
..
674
}
675
));
676
assert!(matches!(
677
doc.blocks[1],
678
Block::Qr {
679
align: Align::Center,
680
..
681
}
682
));
683
assert!(matches!(
684
doc.blocks[2],
685
Block::Barcode {
686
align: Align::Center,
687
..
688
}
689
));
690
assert!(matches!(
691
doc.blocks[3],
692
Block::Paragraph {
693
align: Align::Left,
694
..
695
}
696
));
697
}
698
699
#[test]
700
fn persistent_center_groups_following_paragraph_lines() {
701
let doc = parse(":center:\nLine one\nLine two").unwrap();
702
assert_eq!(doc.blocks.len(), 1);
703
let Block::Paragraph { align, inlines } = &doc.blocks[0] else {
704
panic!();
705
};
706
assert_eq!(*align, Align::Center);
707
assert_eq!(inlines_to_text(inlines), "Line one\nLine two");
708
}
709
710
#[test]
711
fn align_prefix_on_same_line_sets_persistent_state() {
712
let doc = parse(":center: Inline\nNext").unwrap();
713
assert_eq!(doc.blocks.len(), 1);
714
let Block::Paragraph { align, inlines } = &doc.blocks[0] else {
715
panic!();
716
};
717
assert_eq!(*align, Align::Center);
718
assert_eq!(inlines_to_text(inlines), "Inline\nNext");
719
}
720
721
#[test]
722
fn multiple_align_prefixes_on_one_line() {
723
let doc = parse(":left:left :right:right").unwrap();
724
assert_eq!(doc.blocks.len(), 2);
725
assert!(matches!(
726
doc.blocks[0],
727
Block::Paragraph {
728
align: Align::Left,
729
..
730
}
731
));
732
assert!(matches!(
733
doc.blocks[1],
734
Block::Paragraph {
735
align: Align::Right,
736
..
737
}
738
));
739
let Block::Paragraph { inlines: left, .. } = &doc.blocks[0] else {
740
panic!();
741
};
742
let Block::Paragraph { inlines: right, .. } = &doc.blocks[1] else {
743
panic!();
744
};
745
assert_eq!(inlines_to_text(left), "left");
746
assert_eq!(inlines_to_text(right), "right");
747
}
748
749
#[test]
750
fn align_only_line_does_not_emit_block() {
751
let doc = parse(":center:\n:center:").unwrap();
752
assert!(doc.blocks.is_empty());
753
}
754
755
#[test]
756
fn parses_date_and_time_directives() {
757
let doc = parse("@date\n@date DD-YYYY-MM\n@time\n@time 12h").unwrap();
758
assert!(matches!(
759
doc.blocks[0],
760
Block::Date {
761
format: None,
762
..
763
}
764
));
765
assert!(matches!(
766
doc.blocks[1],
767
Block::Date {
768
format: Some(ref f),
769
..
770
} if f == "DD-YYYY-MM"
771
));
772
assert!(matches!(
773
doc.blocks[2],
774
Block::Time {
775
format: TimeFormatSpec::Hours24,
776
..
777
}
778
));
779
assert!(matches!(
780
doc.blocks[3],
781
Block::Time {
782
format: TimeFormatSpec::Hours12,
783
..
784
}
785
));
786
}
787
788
#[test]
789
fn rejects_unknown_time_format() {
790
assert!(parse("@time 24").is_err());
791
}
792
793
#[test]
794
fn blank_line_inserts_feed() {
795
let doc = parse("A\n\nB").unwrap();
796
assert!(matches!(doc.blocks[1], Block::Feed(1)));
797
}
798
799
#[test]
800
fn whitespace_only_line_inserts_feed() {
801
let doc = parse("A\n \nB").unwrap();
802
assert!(matches!(doc.blocks[1], Block::Feed(1)));
803
}
804
805
#[test]
806
fn dsl_marker_lines_are_not_feed() {
807
for src in [
808
":left:\nNext",
809
":center:\nNext",
810
":right:\nNext",
811
":centre:\nNext",
812
"# Title\n",
813
"---\n",
814
"@cut\n",
815
] {
816
let doc = parse(src).unwrap();
817
assert!(
818
!doc.blocks.iter().any(|b| matches!(b, Block::Feed(1))),
819
"unexpected feed for {src:?}"
820
);
821
}
822
}
823
489
#[test]
824
#[test]
490
fn parses_raster_barcode() {
825
fn parses_raster_barcode() {
491
let doc = parse("@barcode RASTER CODE128 ABC").unwrap();
826
let doc = parse("@barcode RASTER CODE128 ABC").unwrap();
@@ -1,6 +1,6 @@
1
1
//! Editor snippets, directive autocomplete, and insert helpers.
2
2
3
pub const DIRECTIVES: &[&str] = &["feed", "cut", "image", "barcode", "qr"];
3
pub const DIRECTIVES: &[&str] = &["feed", "cut", "image", "barcode", "qr", "date", "time"];
4
4
5
5
pub fn directive_completions(prefix: &str) -> Vec<&'static str> {
6
6
let p = prefix.to_ascii_lowercase();
@@ -11,6 +11,73 @@ pub fn directive_completions(prefix: &str) -> Vec<&'static str> {
11
11
.collect()
12
12
}
13
13
14
/// Transparent continuation shown after the typed `@` prefix (e.g. `ba` → `rcode`).
15
pub fn directive_ghost_suffix(prefix: &str) -> Option<String> {
16
let matches = directive_completions(prefix);
17
let full = match matches.len() {
18
0 => return None,
19
1 => matches[0],
20
_ => longest_common_prefix(&matches)?,
21
};
22
if full.len() > prefix.len() {
23
Some(full[prefix.len()..].to_string())
24
} else {
25
None
26
}
27
}
28
29
/// Full directive name to insert when the user presses Tab.
30
pub fn complete_directive(prefix: &str) -> Option<&'static str> {
31
let matches = directive_completions(prefix);
32
match matches.len() {
33
0 => None,
34
1 => Some(matches[0]),
35
_ => {
36
let common = longest_common_prefix(&matches)?;
37
if common.len() > prefix.len() {
38
Some(common)
39
} else {
40
Some(matches[0])
41
}
42
}
43
}
44
}
45
46
fn longest_common_prefix(matches: &[&'static str]) -> Option<&'static str> {
47
if matches.is_empty() {
48
return None;
49
}
50
let mut common = matches[0];
51
for candidate in &matches[1..] {
52
let mut len = 0;
53
while len < common.len()
54
&& len < candidate.len()
55
&& common.as_bytes()[len] == candidate.as_bytes()[len]
56
{
57
len += 1;
58
}
59
common = &common[..len];
60
if common.is_empty() {
61
return None;
62
}
63
}
64
Some(common)
65
}
66
67
/// Replace the partial directive after `@` with `completed`; returns new cursor index.
68
pub fn apply_directive_completion(
69
body: &mut String,
70
at_index: usize,
71
cursor: usize,
72
completed: &str,
73
) -> usize {
74
let replace_start = at_index + 1;
75
let cursor = cursor.min(body.len());
76
let replace_start = replace_start.min(cursor);
77
body.replace_range(replace_start..cursor, completed);
78
at_index + 1 + completed.len()
79
}
80
14
81
pub struct InsertOption {
15
82
pub label: String,
16
83
pub snippet: String,
@@ -59,6 +126,66 @@ pub fn qr_insert_options() -> Vec<InsertOption> {
59
126
]
60
127
}
61
128
129
pub fn date_time_insert_options() -> Vec<InsertOption> {
130
vec![
131
InsertOption {
132
label: "@date (regional)".into(),
133
snippet: "@date\n".into(),
134
},
135
InsertOption {
136
label: "@date DD-YYYY-MM".into(),
137
snippet: "@date DD-YYYY-MM\n".into(),
138
},
139
InsertOption {
140
label: "@date MMMM DD".into(),
141
snippet: "@date MMMM DD\n".into(),
142
},
143
InsertOption {
144
label: "@time (24h)".into(),
145
snippet: "@time\n".into(),
146
},
147
InsertOption {
148
label: "@time 12h".into(),
149
snippet: "@time 12h\n".into(),
150
},
151
InsertOption {
152
label: "@time 24h".into(),
153
snippet: "@time 24h\n".into(),
154
},
155
]
156
}
157
158
pub fn parameter_insert_options(source: &str) -> Vec<InsertOption> {
159
use std::collections::BTreeSet;
160
161
let mut names = BTreeSet::new();
162
if let Ok(doc) = crate::dsl::parse(source) {
163
for name in crate::params::collect_parameter_names(&doc) {
164
names.insert(name);
165
}
166
}
167
for preset in [
168
"DocumentNumber",
169
"Data",
170
"Name",
171
"StoreName",
172
"Total",
173
"OrderId",
174
"Date",
175
"Time",
176
] {
177
names.insert(preset.to_string());
178
}
179
180
names
181
.into_iter()
182
.map(|name| InsertOption {
183
label: format!("${{{name}}}"),
184
snippet: format!("${{{name}}}"),
185
})
186
.collect()
187
}
188
62
189
/// If the cursor is after `@` on the current line, return (start_index, typed_prefix).
63
190
pub fn at_directive_prefix(body: &str, cursor: usize) -> Option<(usize, String)> {
64
191
let cursor = cursor.min(body.len());
@@ -90,6 +217,30 @@ pub fn insert_at_cursor(body: &str, cursor: usize, text: &str) -> (String, usize
90
217
mod tests {
91
218
use super::*;
92
219
220
#[test]
221
fn ghost_suffix_for_partial_directive() {
222
assert_eq!(directive_ghost_suffix("ba"), Some("rcode".into()));
223
}
224
225
#[test]
226
fn ghost_suffix_none_when_ambiguous() {
227
assert!(directive_ghost_suffix("").is_none());
228
}
229
230
#[test]
231
fn completes_directive_on_tab() {
232
assert_eq!(complete_directive("ba"), Some("barcode"));
233
}
234
235
#[test]
236
fn applies_directive_completion() {
237
let mut body = "hello\n@ba".to_string();
238
let end = body.len();
239
let cursor = apply_directive_completion(&mut body, 6, end, "barcode");
240
assert_eq!(body, "hello\n@barcode");
241
assert_eq!(cursor, 6 + 1 + "barcode".len());
242
}
243
93
244
#[test]
94
245
fn completes_directives() {
95
246
let hits = directive_completions("ba");
@@ -1,6 +1,6 @@1
//! Editor snippets, directive autocomplete, and insert helpers.
1
//! Editor snippets, directive autocomplete, and insert helpers.
2
2
3
pub const DIRECTIVES: &[&str] = &["feed", "cut", "image", "barcode", "qr"];
3
pub const DIRECTIVES: &[&str] = &["feed", "cut", "image", "barcode", "qr", "date", "time"];
4
4
5
pub fn directive_completions(prefix: &str) -> Vec<&'static str> {
5
pub fn directive_completions(prefix: &str) -> Vec<&'static str> {
6
let p = prefix.to_ascii_lowercase();
6
let p = prefix.to_ascii_lowercase();
@@ -11,6 +11,73 @@ pub fn directive_completions(prefix: &str) -> Vec<&'static str> {11
.collect()
11
.collect()
12
}
12
}
13
13
14
/// Transparent continuation shown after the typed `@` prefix (e.g. `ba` → `rcode`).
15
pub fn directive_ghost_suffix(prefix: &str) -> Option<String> {
16
let matches = directive_completions(prefix);
17
let full = match matches.len() {
18
0 => return None,
19
1 => matches[0],
20
_ => longest_common_prefix(&matches)?,
21
};
22
if full.len() > prefix.len() {
23
Some(full[prefix.len()..].to_string())
24
} else {
25
None
26
}
27
}
28
29
/// Full directive name to insert when the user presses Tab.
30
pub fn complete_directive(prefix: &str) -> Option<&'static str> {
31
let matches = directive_completions(prefix);
32
match matches.len() {
33
0 => None,
34
1 => Some(matches[0]),
35
_ => {
36
let common = longest_common_prefix(&matches)?;
37
if common.len() > prefix.len() {
38
Some(common)
39
} else {
40
Some(matches[0])
41
}
42
}
43
}
44
}
45
46
fn longest_common_prefix(matches: &[&'static str]) -> Option<&'static str> {
47
if matches.is_empty() {
48
return None;
49
}
50
let mut common = matches[0];
51
for candidate in &matches[1..] {
52
let mut len = 0;
53
while len < common.len()
54
&& len < candidate.len()
55
&& common.as_bytes()[len] == candidate.as_bytes()[len]
56
{
57
len += 1;
58
}
59
common = &common[..len];
60
if common.is_empty() {
61
return None;
62
}
63
}
64
Some(common)
65
}
66
67
/// Replace the partial directive after `@` with `completed`; returns new cursor index.
68
pub fn apply_directive_completion(
69
body: &mut String,
70
at_index: usize,
71
cursor: usize,
72
completed: &str,
73
) -> usize {
74
let replace_start = at_index + 1;
75
let cursor = cursor.min(body.len());
76
let replace_start = replace_start.min(cursor);
77
body.replace_range(replace_start..cursor, completed);
78
at_index + 1 + completed.len()
79
}
80
14
pub struct InsertOption {
81
pub struct InsertOption {
15
pub label: String,
82
pub label: String,
16
pub snippet: String,
83
pub snippet: String,
@@ -59,6 +126,66 @@ pub fn qr_insert_options() -> Vec<InsertOption> {59
]
126
]
60
}
127
}
61
128
129
pub fn date_time_insert_options() -> Vec<InsertOption> {
130
vec![
131
InsertOption {
132
label: "@date (regional)".into(),
133
snippet: "@date\n".into(),
134
},
135
InsertOption {
136
label: "@date DD-YYYY-MM".into(),
137
snippet: "@date DD-YYYY-MM\n".into(),
138
},
139
InsertOption {
140
label: "@date MMMM DD".into(),
141
snippet: "@date MMMM DD\n".into(),
142
},
143
InsertOption {
144
label: "@time (24h)".into(),
145
snippet: "@time\n".into(),
146
},
147
InsertOption {
148
label: "@time 12h".into(),
149
snippet: "@time 12h\n".into(),
150
},
151
InsertOption {
152
label: "@time 24h".into(),
153
snippet: "@time 24h\n".into(),
154
},
155
]
156
}
157
158
pub fn parameter_insert_options(source: &str) -> Vec<InsertOption> {
159
use std::collections::BTreeSet;
160
161
let mut names = BTreeSet::new();
162
if let Ok(doc) = crate::dsl::parse(source) {
163
for name in crate::params::collect_parameter_names(&doc) {
164
names.insert(name);
165
}
166
}
167
for preset in [
168
"DocumentNumber",
169
"Data",
170
"Name",
171
"StoreName",
172
"Total",
173
"OrderId",
174
"Date",
175
"Time",
176
] {
177
names.insert(preset.to_string());
178
}
179
180
names
181
.into_iter()
182
.map(|name| InsertOption {
183
label: format!("${{{name}}}"),
184
snippet: format!("${{{name}}}"),
185
})
186
.collect()
187
}
188
62
/// If the cursor is after `@` on the current line, return (start_index, typed_prefix).
189
/// If the cursor is after `@` on the current line, return (start_index, typed_prefix).
63
pub fn at_directive_prefix(body: &str, cursor: usize) -> Option<(usize, String)> {
190
pub fn at_directive_prefix(body: &str, cursor: usize) -> Option<(usize, String)> {
64
let cursor = cursor.min(body.len());
191
let cursor = cursor.min(body.len());
@@ -90,6 +217,30 @@ pub fn insert_at_cursor(body: &str, cursor: usize, text: &str) -> (String, usize90
mod tests {
217
mod tests {
91
use super::*;
218
use super::*;
92
219
220
#[test]
221
fn ghost_suffix_for_partial_directive() {
222
assert_eq!(directive_ghost_suffix("ba"), Some("rcode".into()));
223
}
224
225
#[test]
226
fn ghost_suffix_none_when_ambiguous() {
227
assert!(directive_ghost_suffix("").is_none());
228
}
229
230
#[test]
231
fn completes_directive_on_tab() {
232
assert_eq!(complete_directive("ba"), Some("barcode"));
233
}
234
235
#[test]
236
fn applies_directive_completion() {
237
let mut body = "hello\n@ba".to_string();
238
let end = body.len();
239
let cursor = apply_directive_completion(&mut body, 6, end, "barcode");
240
assert_eq!(body, "hello\n@barcode");
241
assert_eq!(cursor, 6 + 1 + "barcode".len());
242
}
243
93
#[test]
244
#[test]
94
fn completes_directives() {
245
fn completes_directives() {
95
let hits = directive_completions("ba");
246
let hits = directive_completions("ba");
@@ -7,6 +7,7 @@ use crate::dsl::{
7
7
};
8
8
use crate::io::PosMetadata;
9
9
use crate::raster::{self, RasterError};
10
use crate::text_wrap::{self, TextWrapStyle};
10
11
11
12
#[derive(Debug)]
12
13
pub enum EscPosError {
@@ -63,18 +64,28 @@ impl EscPosEncoder {
63
64
Block::Paragraph { align, inlines } => {
64
65
self.set_align(*align);
65
66
let line = inlines_to_plain(inlines);
66
for part in line.split('\n') {
67
self.writeln(part);
67
let cols = text_wrap::wrap_cols(&self.metadata, TextWrapStyle::Normal);
68
for part in text_wrap::wrap_text(&line, cols) {
69
self.writeln(&part);
68
70
}
69
71
}
70
Block::Heading { level, inlines } => {
71
self.set_align(Align::Left);
72
Block::Heading { level, align, inlines } => {
73
self.set_align(*align);
74
let wrap_style = if *level == 1 {
75
TextWrapStyle::Heading1
76
} else {
77
TextWrapStyle::Heading2
78
};
79
let cols = text_wrap::wrap_cols(&self.metadata, wrap_style);
80
let wrapped = text_wrap::wrap_text(&inlines_to_plain(inlines), cols);
72
81
if *level == 1 {
73
82
self.buffer.extend_from_slice(&[0x1D, b'!', 0x11]);
74
83
} else {
75
84
self.buffer.extend_from_slice(&[0x1B, b'E', 1]);
76
85
}
77
self.writeln(&inlines_to_plain(inlines));
86
for part in &wrapped {
87
self.writeln(part);
88
}
78
89
if *level == 1 {
79
90
self.buffer.extend_from_slice(&[0x1D, b'!', 0x00]);
80
91
} else {
@@ -129,6 +140,22 @@ impl EscPosEncoder {
129
140
}
130
141
}
131
142
}
143
Block::Date { format, align } => {
144
self.set_align(*align);
145
let text = crate::datetime::format_date(format.as_deref());
146
let cols = text_wrap::wrap_cols(&self.metadata, TextWrapStyle::Normal);
147
for part in text_wrap::wrap_text(&text, cols) {
148
self.writeln(&part);
149
}
150
}
151
Block::Time { format, align } => {
152
self.set_align(*align);
153
let text = crate::datetime::format_time(*format);
154
let cols = text_wrap::wrap_cols(&self.metadata, TextWrapStyle::Normal);
155
for part in text_wrap::wrap_text(&text, cols) {
156
self.writeln(&part);
157
}
158
}
132
159
}
133
160
Ok(())
134
161
}
@@ -320,6 +347,25 @@ mod tests {
320
347
use super::*;
321
348
use crate::dsl::parse;
322
349
350
#[test]
351
fn heading_wraps_like_preview_on_narrow_paper() {
352
let doc = parse("# Proof of Transfer").unwrap();
353
let mut enc = EscPosEncoder::new(PosMetadata {
354
page_width_mm: 53.0,
355
..Default::default()
356
});
357
let bytes = enc.encode_document(&doc).unwrap();
358
let text = String::from_utf8_lossy(bytes);
359
assert!(
360
text.contains("Proof of\n"),
361
"expected word wrap before Transfer, got: {text}"
362
);
363
assert!(
364
text.contains("Transfer\n"),
365
"expected wrapped second line, got: {text}"
366
);
367
}
368
323
369
#[test]
324
370
fn encodes_init_and_text() {
325
371
let doc = parse("Hello").unwrap();
@@ -337,6 +383,24 @@ mod tests {
337
383
assert!(bytes.windows(4).any(|w| w == [0x1D, b'v', 0, 0]));
338
384
}
339
385
386
#[test]
387
fn encodes_centered_heading() {
388
let doc = parse(":center:\n# Hello").unwrap();
389
let mut enc = EscPosEncoder::new(PosMetadata::default());
390
let bytes = enc.encode_document(&doc).unwrap();
391
assert!(bytes.windows(3).any(|w| w == [0x1B, b'a', 1]));
392
assert!(bytes.windows(5).any(|w| w == b"Hello"));
393
}
394
395
#[test]
396
fn encodes_date_directive() {
397
let doc = parse("@date DD-YYYY-MM").unwrap();
398
let mut enc = EscPosEncoder::new(PosMetadata::default());
399
let bytes = enc.encode_document(&doc).unwrap();
400
let text = String::from_utf8_lossy(bytes);
401
assert!(text.contains('-'));
402
}
403
340
404
#[test]
341
405
fn encodes_cut_directive() {
342
406
let doc = parse("@cut").unwrap();
@@ -7,6 +7,7 @@ use crate::dsl::{7
};
7
};
8
use crate::io::PosMetadata;
8
use crate::io::PosMetadata;
9
use crate::raster::{self, RasterError};
9
use crate::raster::{self, RasterError};
10
use crate::text_wrap::{self, TextWrapStyle};
10
11
11
#[derive(Debug)]
12
#[derive(Debug)]
12
pub enum EscPosError {
13
pub enum EscPosError {
@@ -63,18 +64,28 @@ impl EscPosEncoder {63
Block::Paragraph { align, inlines } => {
64
Block::Paragraph { align, inlines } => {
64
self.set_align(*align);
65
self.set_align(*align);
65
let line = inlines_to_plain(inlines);
66
let line = inlines_to_plain(inlines);
66
for part in line.split('\n') {
67
let cols = text_wrap::wrap_cols(&self.metadata, TextWrapStyle::Normal);
67
self.writeln(part);
68
for part in text_wrap::wrap_text(&line, cols) {
69
self.writeln(&part);
68
}
70
}
69
}
71
}
70
Block::Heading { level, inlines } => {
72
Block::Heading { level, align, inlines } => {
71
self.set_align(Align::Left);
73
self.set_align(*align);
74
let wrap_style = if *level == 1 {
75
TextWrapStyle::Heading1
76
} else {
77
TextWrapStyle::Heading2
78
};
79
let cols = text_wrap::wrap_cols(&self.metadata, wrap_style);
80
let wrapped = text_wrap::wrap_text(&inlines_to_plain(inlines), cols);
72
if *level == 1 {
81
if *level == 1 {
73
self.buffer.extend_from_slice(&[0x1D, b'!', 0x11]);
82
self.buffer.extend_from_slice(&[0x1D, b'!', 0x11]);
74
} else {
83
} else {
75
self.buffer.extend_from_slice(&[0x1B, b'E', 1]);
84
self.buffer.extend_from_slice(&[0x1B, b'E', 1]);
76
}
85
}
77
self.writeln(&inlines_to_plain(inlines));
86
for part in &wrapped {
87
self.writeln(part);
88
}
78
if *level == 1 {
89
if *level == 1 {
79
self.buffer.extend_from_slice(&[0x1D, b'!', 0x00]);
90
self.buffer.extend_from_slice(&[0x1D, b'!', 0x00]);
80
} else {
91
} else {
@@ -129,6 +140,22 @@ impl EscPosEncoder {129
}
140
}
130
}
141
}
131
}
142
}
143
Block::Date { format, align } => {
144
self.set_align(*align);
145
let text = crate::datetime::format_date(format.as_deref());
146
let cols = text_wrap::wrap_cols(&self.metadata, TextWrapStyle::Normal);
147
for part in text_wrap::wrap_text(&text, cols) {
148
self.writeln(&part);
149
}
150
}
151
Block::Time { format, align } => {
152
self.set_align(*align);
153
let text = crate::datetime::format_time(*format);
154
let cols = text_wrap::wrap_cols(&self.metadata, TextWrapStyle::Normal);
155
for part in text_wrap::wrap_text(&text, cols) {
156
self.writeln(&part);
157
}
158
}
132
}
159
}
133
Ok(())
160
Ok(())
134
}
161
}
@@ -320,6 +347,25 @@ mod tests {320
use super::*;
347
use super::*;
321
use crate::dsl::parse;
348
use crate::dsl::parse;
322
349
350
#[test]
351
fn heading_wraps_like_preview_on_narrow_paper() {
352
let doc = parse("# Proof of Transfer").unwrap();
353
let mut enc = EscPosEncoder::new(PosMetadata {
354
page_width_mm: 53.0,
355
..Default::default()
356
});
357
let bytes = enc.encode_document(&doc).unwrap();
358
let text = String::from_utf8_lossy(bytes);
359
assert!(
360
text.contains("Proof of\n"),
361
"expected word wrap before Transfer, got: {text}"
362
);
363
assert!(
364
text.contains("Transfer\n"),
365
"expected wrapped second line, got: {text}"
366
);
367
}
368
323
#[test]
369
#[test]
324
fn encodes_init_and_text() {
370
fn encodes_init_and_text() {
325
let doc = parse("Hello").unwrap();
371
let doc = parse("Hello").unwrap();
@@ -337,6 +383,24 @@ mod tests {337
assert!(bytes.windows(4).any(|w| w == [0x1D, b'v', 0, 0]));
383
assert!(bytes.windows(4).any(|w| w == [0x1D, b'v', 0, 0]));
338
}
384
}
339
385
386
#[test]
387
fn encodes_centered_heading() {
388
let doc = parse(":center:\n# Hello").unwrap();
389
let mut enc = EscPosEncoder::new(PosMetadata::default());
390
let bytes = enc.encode_document(&doc).unwrap();
391
assert!(bytes.windows(3).any(|w| w == [0x1B, b'a', 1]));
392
assert!(bytes.windows(5).any(|w| w == b"Hello"));
393
}
394
395
#[test]
396
fn encodes_date_directive() {
397
let doc = parse("@date DD-YYYY-MM").unwrap();
398
let mut enc = EscPosEncoder::new(PosMetadata::default());
399
let bytes = enc.encode_document(&doc).unwrap();
400
let text = String::from_utf8_lossy(bytes);
401
assert!(text.contains('-'));
402
}
403
340
#[test]
404
#[test]
341
fn encodes_cut_directive() {
405
fn encodes_cut_directive() {
342
let doc = parse("@cut").unwrap();
406
let doc = parse("@cut").unwrap();
@@ -0,0 +1,216 @@
1
//! Render HELP.md as formatted egui widgets.
2
3
use eframe::egui;
4
use pulldown_cmark::{Event, HeadingLevel, Options, Parser, Tag, TagEnd};
5
6
pub fn show_help(ui: &mut egui::Ui, markdown: &str) {
7
egui::ScrollArea::vertical().show(ui, |ui| {
8
render_markdown(ui, markdown);
9
});
10
}
11
12
fn render_markdown(ui: &mut egui::Ui, markdown: &str) {
13
let mut opts = Options::empty();
14
opts.insert(Options::ENABLE_TABLES);
15
opts.insert(Options::ENABLE_STRIKETHROUGH);
16
17
let parser = Parser::new_ext(markdown, opts);
18
19
let mut in_code_block = false;
20
let mut code_buf = String::new();
21
let mut para_buf = String::new();
22
let mut heading_buf = String::new();
23
let mut heading_level = HeadingLevel::H1;
24
let mut in_heading = false;
25
let mut list_depth = 0usize;
26
let mut list_item_buf = String::new();
27
let mut in_list_item = false;
28
29
let flush_para = |ui: &mut egui::Ui, buf: &mut String| {
30
let text = buf.trim();
31
if text.is_empty() {
32
buf.clear();
33
return;
34
}
35
ui.add(egui::Label::new(text).wrap().selectable(true));
36
ui.add_space(4.0);
37
buf.clear();
38
};
39
40
let flush_code = |ui: &mut egui::Ui, buf: &mut String| {
41
if buf.is_empty() {
42
return;
43
}
44
egui::Frame::new()
45
.fill(ui.visuals().extreme_bg_color)
46
.inner_margin(8.0)
47
.show(ui, |ui| {
48
ui.add(
49
egui::Label::new(egui::RichText::new(buf.trim_end()).monospace())
50
.wrap()
51
.selectable(true),
52
);
53
});
54
ui.add_space(6.0);
55
buf.clear();
56
};
57
58
let flush_list_item = |ui: &mut egui::Ui, buf: &mut String, depth: usize| {
59
let text = buf.trim();
60
if text.is_empty() {
61
buf.clear();
62
return;
63
}
64
ui.horizontal(|ui| {
65
ui.add_space((depth.saturating_sub(1)) as f32 * 12.0);
66
ui.label("•");
67
ui.add(egui::Label::new(text).wrap().selectable(true));
68
});
69
ui.add_space(2.0);
70
buf.clear();
71
};
72
73
for event in parser {
74
match event {
75
Event::Start(Tag::Heading { level, .. }) => {
76
flush_para(ui, &mut para_buf);
77
in_heading = true;
78
heading_level = level;
79
heading_buf.clear();
80
}
81
Event::End(TagEnd::Heading(_)) => {
82
let size = match heading_level {
83
HeadingLevel::H1 => 22.0,
84
HeadingLevel::H2 => 18.0,
85
HeadingLevel::H3 => 16.0,
86
HeadingLevel::H4 => 15.0,
87
HeadingLevel::H5 => 14.0,
88
HeadingLevel::H6 => 13.0,
89
};
90
ui.add_space(8.0);
91
ui.label(
92
egui::RichText::new(heading_buf.trim())
93
.size(size)
94
.strong(),
95
);
96
heading_buf.clear();
97
in_heading = false;
98
ui.add_space(6.0);
99
}
100
Event::Start(Tag::Paragraph) => {}
101
Event::End(TagEnd::Paragraph) => {
102
if in_list_item {
103
flush_list_item(ui, &mut list_item_buf, list_depth);
104
} else {
105
flush_para(ui, &mut para_buf);
106
}
107
}
108
Event::Start(Tag::List(_)) => {
109
flush_para(ui, &mut para_buf);
110
list_depth += 1;
111
}
112
Event::End(TagEnd::List(_)) => {
113
if in_list_item {
114
flush_list_item(ui, &mut list_item_buf, list_depth);
115
in_list_item = false;
116
}
117
list_depth = list_depth.saturating_sub(1);
118
}
119
Event::Start(Tag::Item) => {
120
in_list_item = true;
121
list_item_buf.clear();
122
}
123
Event::End(TagEnd::Item) => {
124
flush_list_item(ui, &mut list_item_buf, list_depth);
125
in_list_item = false;
126
}
127
Event::Start(Tag::CodeBlock(_)) => {
128
flush_para(ui, &mut para_buf);
129
in_code_block = true;
130
code_buf.clear();
131
}
132
Event::End(TagEnd::CodeBlock) => {
133
flush_code(ui, &mut code_buf);
134
in_code_block = false;
135
}
136
Event::Start(Tag::Link { dest_url, .. }) => {
137
if !in_code_block && !in_heading {
138
para_buf.push('[');
139
}
140
let _ = dest_url;
141
}
142
Event::End(TagEnd::Link) => {
143
if !in_code_block && !in_heading {
144
para_buf.push(']');
145
}
146
}
147
Event::Code(text) => {
148
if in_code_block {
149
code_buf.push_str(&text);
150
} else if in_heading {
151
heading_buf.push_str(&text);
152
} else if in_list_item {
153
list_item_buf.push('`');
154
list_item_buf.push_str(&text);
155
list_item_buf.push('`');
156
} else {
157
para_buf.push('`');
158
para_buf.push_str(&text);
159
para_buf.push('`');
160
}
161
}
162
Event::Text(text) => {
163
if in_code_block {
164
code_buf.push_str(&text);
165
} else if in_heading {
166
heading_buf.push_str(&text);
167
} else if in_list_item {
168
list_item_buf.push_str(&text);
169
} else {
170
para_buf.push_str(&text);
171
}
172
}
173
Event::SoftBreak | Event::HardBreak => {
174
if in_code_block {
175
code_buf.push('\n');
176
} else if in_list_item {
177
list_item_buf.push(' ');
178
} else {
179
para_buf.push('\n');
180
}
181
}
182
Event::Rule => {
183
flush_para(ui, &mut para_buf);
184
ui.separator();
185
ui.add_space(4.0);
186
}
187
Event::Start(Tag::Strong) => {
188
if !in_code_block {
189
para_buf.push_str("**");
190
}
191
}
192
Event::End(TagEnd::Strong) => {
193
if !in_code_block {
194
para_buf.push_str("**");
195
}
196
}
197
Event::Start(Tag::Emphasis) => {
198
if !in_code_block {
199
para_buf.push('*');
200
}
201
}
202
Event::End(TagEnd::Emphasis) => {
203
if !in_code_block {
204
para_buf.push('*');
205
}
206
}
207
_ => {}
208
}
209
}
210
211
if in_list_item {
212
flush_list_item(ui, &mut list_item_buf, list_depth);
213
}
214
flush_code(ui, &mut code_buf);
215
flush_para(ui, &mut para_buf);
216
}
@@ -0,0 +1,216 @@1
//! Render HELP.md as formatted egui widgets.
2
3
use eframe::egui;
4
use pulldown_cmark::{Event, HeadingLevel, Options, Parser, Tag, TagEnd};
5
6
pub fn show_help(ui: &mut egui::Ui, markdown: &str) {
7
egui::ScrollArea::vertical().show(ui, |ui| {
8
render_markdown(ui, markdown);
9
});
10
}
11
12
fn render_markdown(ui: &mut egui::Ui, markdown: &str) {
13
let mut opts = Options::empty();
14
opts.insert(Options::ENABLE_TABLES);
15
opts.insert(Options::ENABLE_STRIKETHROUGH);
16
17
let parser = Parser::new_ext(markdown, opts);
18
19
let mut in_code_block = false;
20
let mut code_buf = String::new();
21
let mut para_buf = String::new();
22
let mut heading_buf = String::new();
23
let mut heading_level = HeadingLevel::H1;
24
let mut in_heading = false;
25
let mut list_depth = 0usize;
26
let mut list_item_buf = String::new();
27
let mut in_list_item = false;
28
29
let flush_para = |ui: &mut egui::Ui, buf: &mut String| {
30
let text = buf.trim();
31
if text.is_empty() {
32
buf.clear();
33
return;
34
}
35
ui.add(egui::Label::new(text).wrap().selectable(true));
36
ui.add_space(4.0);
37
buf.clear();
38
};
39
40
let flush_code = |ui: &mut egui::Ui, buf: &mut String| {
41
if buf.is_empty() {
42
return;
43
}
44
egui::Frame::new()
45
.fill(ui.visuals().extreme_bg_color)
46
.inner_margin(8.0)
47
.show(ui, |ui| {
48
ui.add(
49
egui::Label::new(egui::RichText::new(buf.trim_end()).monospace())
50
.wrap()
51
.selectable(true),
52
);
53
});
54
ui.add_space(6.0);
55
buf.clear();
56
};
57
58
let flush_list_item = |ui: &mut egui::Ui, buf: &mut String, depth: usize| {
59
let text = buf.trim();
60
if text.is_empty() {
61
buf.clear();
62
return;
63
}
64
ui.horizontal(|ui| {
65
ui.add_space((depth.saturating_sub(1)) as f32 * 12.0);
66
ui.label("•");
67
ui.add(egui::Label::new(text).wrap().selectable(true));
68
});
69
ui.add_space(2.0);
70
buf.clear();
71
};
72
73
for event in parser {
74
match event {
75
Event::Start(Tag::Heading { level, .. }) => {
76
flush_para(ui, &mut para_buf);
77
in_heading = true;
78
heading_level = level;
79
heading_buf.clear();
80
}
81
Event::End(TagEnd::Heading(_)) => {
82
let size = match heading_level {
83
HeadingLevel::H1 => 22.0,
84
HeadingLevel::H2 => 18.0,
85
HeadingLevel::H3 => 16.0,
86
HeadingLevel::H4 => 15.0,
87
HeadingLevel::H5 => 14.0,
88
HeadingLevel::H6 => 13.0,
89
};
90
ui.add_space(8.0);
91
ui.label(
92
egui::RichText::new(heading_buf.trim())
93
.size(size)
94
.strong(),
95
);
96
heading_buf.clear();
97
in_heading = false;
98
ui.add_space(6.0);
99
}
100
Event::Start(Tag::Paragraph) => {}
101
Event::End(TagEnd::Paragraph) => {
102
if in_list_item {
103
flush_list_item(ui, &mut list_item_buf, list_depth);
104
} else {
105
flush_para(ui, &mut para_buf);
106
}
107
}
108
Event::Start(Tag::List(_)) => {
109
flush_para(ui, &mut para_buf);
110
list_depth += 1;
111
}
112
Event::End(TagEnd::List(_)) => {
113
if in_list_item {
114
flush_list_item(ui, &mut list_item_buf, list_depth);
115
in_list_item = false;
116
}
117
list_depth = list_depth.saturating_sub(1);
118
}
119
Event::Start(Tag::Item) => {
120
in_list_item = true;
121
list_item_buf.clear();
122
}
123
Event::End(TagEnd::Item) => {
124
flush_list_item(ui, &mut list_item_buf, list_depth);
125
in_list_item = false;
126
}
127
Event::Start(Tag::CodeBlock(_)) => {
128
flush_para(ui, &mut para_buf);
129
in_code_block = true;
130
code_buf.clear();
131
}
132
Event::End(TagEnd::CodeBlock) => {
133
flush_code(ui, &mut code_buf);
134
in_code_block = false;
135
}
136
Event::Start(Tag::Link { dest_url, .. }) => {
137
if !in_code_block && !in_heading {
138
para_buf.push('[');
139
}
140
let _ = dest_url;
141
}
142
Event::End(TagEnd::Link) => {
143
if !in_code_block && !in_heading {
144
para_buf.push(']');
145
}
146
}
147
Event::Code(text) => {
148
if in_code_block {
149
code_buf.push_str(&text);
150
} else if in_heading {
151
heading_buf.push_str(&text);
152
} else if in_list_item {
153
list_item_buf.push('`');
154
list_item_buf.push_str(&text);
155
list_item_buf.push('`');
156
} else {
157
para_buf.push('`');
158
para_buf.push_str(&text);
159
para_buf.push('`');
160
}
161
}
162
Event::Text(text) => {
163
if in_code_block {
164
code_buf.push_str(&text);
165
} else if in_heading {
166
heading_buf.push_str(&text);
167
} else if in_list_item {
168
list_item_buf.push_str(&text);
169
} else {
170
para_buf.push_str(&text);
171
}
172
}
173
Event::SoftBreak | Event::HardBreak => {
174
if in_code_block {
175
code_buf.push('\n');
176
} else if in_list_item {
177
list_item_buf.push(' ');
178
} else {
179
para_buf.push('\n');
180
}
181
}
182
Event::Rule => {
183
flush_para(ui, &mut para_buf);
184
ui.separator();
185
ui.add_space(4.0);
186
}
187
Event::Start(Tag::Strong) => {
188
if !in_code_block {
189
para_buf.push_str("**");
190
}
191
}
192
Event::End(TagEnd::Strong) => {
193
if !in_code_block {
194
para_buf.push_str("**");
195
}
196
}
197
Event::Start(Tag::Emphasis) => {
198
if !in_code_block {
199
para_buf.push('*');
200
}
201
}
202
Event::End(TagEnd::Emphasis) => {
203
if !in_code_block {
204
para_buf.push('*');
205
}
206
}
207
_ => {}
208
}
209
}
210
211
if in_list_item {
212
flush_list_item(ui, &mut list_item_buf, list_depth);
213
}
214
flush_code(ui, &mut code_buf);
215
flush_para(ui, &mut para_buf);
216
}
@@ -12,7 +12,6 @@ pub struct PosMetadata {
12
12
#[serde(skip_serializing_if = "Option::is_none")]
13
13
pub title: Option<String>,
14
14
pub page_width_mm: f32,
15
pub preview_mode: PreviewMode,
16
15
#[serde(skip_serializing_if = "Option::is_none")]
17
16
pub chars_per_line: Option<u32>,
18
17
#[serde(skip_serializing_if = "Option::is_none")]
@@ -23,13 +22,6 @@ pub struct PosMetadata {
23
22
pub default_feed_before_cut: u8,
24
23
}
25
24
26
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
27
#[serde(rename_all = "lowercase")]
28
pub enum PreviewMode {
29
Autoscale,
30
Fixed,
31
}
32
33
25
fn default_cut_after_print() -> bool {
34
26
true
35
27
}
@@ -43,7 +35,6 @@ impl Default for PosMetadata {
43
35
Self {
44
36
title: None,
45
37
page_width_mm: 80.0,
46
preview_mode: PreviewMode::Autoscale,
47
38
chars_per_line: None,
48
39
codepage: Some("CP437".into()),
49
40
cut_after_print: true,
@@ -156,6 +147,23 @@ mod tests {
156
147
assert_eq!(wide.chars_per_line(), 48);
157
148
}
158
149
150
#[test]
151
fn ignores_legacy_preview_mode_field() {
152
let json = r#"{
153
"version": 1,
154
"metadata": {
155
"page_width_mm": 80.0,
156
"preview_mode": "autoscale",
157
"cut_after_print": true,
158
"default_feed_before_cut": 4
159
},
160
"body": "hello"
161
}"#;
162
let loaded = PosFile::from_json(json).unwrap();
163
assert_eq!(loaded.body, "hello");
164
assert!(!loaded.to_json_pretty().unwrap().contains("preview_mode"));
165
}
166
159
167
#[test]
160
168
fn save_and_load_file() {
161
169
let dir = tempfile::tempdir().unwrap();
@@ -12,7 +12,6 @@ pub struct PosMetadata {12
#[serde(skip_serializing_if = "Option::is_none")]
12
#[serde(skip_serializing_if = "Option::is_none")]
13
pub title: Option<String>,
13
pub title: Option<String>,
14
pub page_width_mm: f32,
14
pub page_width_mm: f32,
15
pub preview_mode: PreviewMode,
16
#[serde(skip_serializing_if = "Option::is_none")]
15
#[serde(skip_serializing_if = "Option::is_none")]
17
pub chars_per_line: Option<u32>,
16
pub chars_per_line: Option<u32>,
18
#[serde(skip_serializing_if = "Option::is_none")]
17
#[serde(skip_serializing_if = "Option::is_none")]
@@ -23,13 +22,6 @@ pub struct PosMetadata {23
pub default_feed_before_cut: u8,
22
pub default_feed_before_cut: u8,
24
}
23
}
25
24
26
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
27
#[serde(rename_all = "lowercase")]
28
pub enum PreviewMode {
29
Autoscale,
30
Fixed,
31
}
32
33
fn default_cut_after_print() -> bool {
25
fn default_cut_after_print() -> bool {
34
true
26
true
35
}
27
}
@@ -43,7 +35,6 @@ impl Default for PosMetadata {43
Self {
35
Self {
44
title: None,
36
title: None,
45
page_width_mm: 80.0,
37
page_width_mm: 80.0,
46
preview_mode: PreviewMode::Autoscale,
47
chars_per_line: None,
38
chars_per_line: None,
48
codepage: Some("CP437".into()),
39
codepage: Some("CP437".into()),
49
cut_after_print: true,
40
cut_after_print: true,
@@ -156,6 +147,23 @@ mod tests {156
assert_eq!(wide.chars_per_line(), 48);
147
assert_eq!(wide.chars_per_line(), 48);
157
}
148
}
158
149
150
#[test]
151
fn ignores_legacy_preview_mode_field() {
152
let json = r#"{
153
"version": 1,
154
"metadata": {
155
"page_width_mm": 80.0,
156
"preview_mode": "autoscale",
157
"cut_after_print": true,
158
"default_feed_before_cut": 4
159
},
160
"body": "hello"
161
}"#;
162
let loaded = PosFile::from_json(json).unwrap();
163
assert_eq!(loaded.body, "hello");
164
assert!(!loaded.to_json_pretty().unwrap().contains("preview_mode"));
165
}
166
159
#[test]
167
#[test]
160
fn save_and_load_file() {
168
fn save_and_load_file() {
161
let dir = tempfile::tempdir().unwrap();
169
let dir = tempfile::tempdir().unwrap();
@@ -1,13 +1,17 @@
1
1
pub mod cli;
2
pub mod datetime;
2
3
pub mod dsl;
3
4
pub mod editor_assist;
4
5
pub mod escpos;
6
pub mod help_view;
5
7
pub mod io;
6
8
pub mod params;
7
9
pub mod pipeline;
8
10
pub mod preview;
9
11
pub mod print;
10
12
pub mod raster;
13
pub mod text_wrap;
14
pub mod undo;
11
15
12
16
#[cfg(windows)]
13
17
pub const HELP_MARKDOWN: &str = concat!(
@@ -1,13 +1,17 @@1
pub mod cli;
1
pub mod cli;
2
pub mod datetime;
2
pub mod dsl;
3
pub mod dsl;
3
pub mod editor_assist;
4
pub mod editor_assist;
4
pub mod escpos;
5
pub mod escpos;
6
pub mod help_view;
5
pub mod io;
7
pub mod io;
6
pub mod params;
8
pub mod params;
7
pub mod pipeline;
9
pub mod pipeline;
8
pub mod preview;
10
pub mod preview;
9
pub mod print;
11
pub mod print;
10
pub mod raster;
12
pub mod raster;
13
pub mod text_wrap;
14
pub mod undo;
11
15
12
#[cfg(windows)]
16
#[cfg(windows)]
13
pub const HELP_MARKDOWN: &str = concat!(
17
pub const HELP_MARKDOWN: &str = concat!(
@@ -1,20 +1,73 @@
1
mod app;
2
3
use clap::Parser;
4
5
fn main() -> eframe::Result<()> {
6
let cli = posprint::cli::Cli::parse();
7
if cli.command.is_some() {
8
std::process::exit(posprint::cli::run(cli));
9
}
10
11
let options = eframe::NativeOptions {
12
viewport: eframe::egui::ViewportBuilder::default().with_inner_size([1100.0, 750.0]),
13
..Default::default()
14
};
15
eframe::run_native(
16
"posprint",
17
options,
18
Box::new(|_cc| Ok(Box::new(app::PosPrintApp::new()))),
19
)
20
}
1
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
2
3
mod app;
4
mod print_dialog;
5
mod print_only_app;
6
mod shell_integration;
7
8
use std::sync::Arc;
9
10
use clap::Parser;
11
12
fn load_viewport_icon() -> Option<Arc<eframe::egui::IconData>> {
13
eframe::icon_data::from_png_bytes(include_bytes!("../pos-logo.png"))
14
.ok()
15
.map(Arc::new)
16
}
17
18
fn main() -> eframe::Result<()> {
19
shell_integration::ensure_print_context_menu();
20
21
let cli = posprint::cli::Cli::parse();
22
if cli.command.is_some() {
23
std::process::exit(posprint::cli::run(cli));
24
}
25
26
if cli.print {
27
let Some(path) = cli.file else {
28
eprintln!("--print requires a .pos file path");
29
std::process::exit(1);
30
};
31
return run_print_only(path);
32
}
33
34
let open_file = cli.file;
35
36
let mut viewport = eframe::egui::ViewportBuilder::default().with_inner_size([1200.0, 750.0]);
37
if let Some(icon) = load_viewport_icon() {
38
viewport = viewport.with_icon(icon);
39
}
40
41
let options = eframe::NativeOptions {
42
viewport,
43
..Default::default()
44
};
45
eframe::run_native(
46
"posprint",
47
options,
48
Box::new(move |_cc| {
49
Ok(Box::new(app::PosPrintApp::new_with_file(open_file)) as Box<dyn eframe::App>)
50
}),
51
)
52
}
53
54
fn run_print_only(path: std::path::PathBuf) -> eframe::Result<()> {
55
let mut viewport = eframe::egui::ViewportBuilder::default()
56
.with_inner_size([440.0, 420.0])
57
.with_min_inner_size([380.0, 320.0]);
58
if let Some(icon) = load_viewport_icon() {
59
viewport = viewport.with_icon(icon);
60
}
61
62
let options = eframe::NativeOptions {
63
viewport,
64
..Default::default()
65
};
66
eframe::run_native(
67
"posprint",
68
options,
69
Box::new(move |_cc| {
70
Ok(Box::new(print_only_app::PrintOnlyApp::new(path)) as Box<dyn eframe::App>)
71
}),
72
)
73
}
@@ -1,20 +1,73 @@1
mod app;
1
#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]
2
2
3
use clap::Parser;
3
mod app;
4
4
mod print_dialog;
5
fn main() -> eframe::Result<()> {
5
mod print_only_app;
6
let cli = posprint::cli::Cli::parse();
6
mod shell_integration;
7
if cli.command.is_some() {
7
8
std::process::exit(posprint::cli::run(cli));
8
use std::sync::Arc;
9
}
9
10
10
use clap::Parser;
11
let options = eframe::NativeOptions {
11
12
viewport: eframe::egui::ViewportBuilder::default().with_inner_size([1100.0, 750.0]),
12
fn load_viewport_icon() -> Option<Arc<eframe::egui::IconData>> {
13
..Default::default()
13
eframe::icon_data::from_png_bytes(include_bytes!("../pos-logo.png"))
14
};
14
.ok()
15
eframe::run_native(
15
.map(Arc::new)
16
"posprint",
16
}
17
options,
17
18
Box::new(|_cc| Ok(Box::new(app::PosPrintApp::new()))),
18
fn main() -> eframe::Result<()> {
19
)
19
shell_integration::ensure_print_context_menu();
20
}
20
21
let cli = posprint::cli::Cli::parse();
22
if cli.command.is_some() {
23
std::process::exit(posprint::cli::run(cli));
24
}
25
26
if cli.print {
27
let Some(path) = cli.file else {
28
eprintln!("--print requires a .pos file path");
29
std::process::exit(1);
30
};
31
return run_print_only(path);
32
}
33
34
let open_file = cli.file;
35
36
let mut viewport = eframe::egui::ViewportBuilder::default().with_inner_size([1200.0, 750.0]);
37
if let Some(icon) = load_viewport_icon() {
38
viewport = viewport.with_icon(icon);
39
}
40
41
let options = eframe::NativeOptions {
42
viewport,
43
..Default::default()
44
};
45
eframe::run_native(
46
"posprint",
47
options,
48
Box::new(move |_cc| {
49
Ok(Box::new(app::PosPrintApp::new_with_file(open_file)) as Box<dyn eframe::App>)
50
}),
51
)
52
}
53
54
fn run_print_only(path: std::path::PathBuf) -> eframe::Result<()> {
55
let mut viewport = eframe::egui::ViewportBuilder::default()
56
.with_inner_size([440.0, 420.0])
57
.with_min_inner_size([380.0, 320.0]);
58
if let Some(icon) = load_viewport_icon() {
59
viewport = viewport.with_icon(icon);
60
}
61
62
let options = eframe::NativeOptions {
63
viewport,
64
..Default::default()
65
};
66
eframe::run_native(
67
"posprint",
68
options,
69
Box::new(move |_cc| {
70
Ok(Box::new(print_only_app::PrintOnlyApp::new(path)) as Box<dyn eframe::App>)
71
}),
72
)
73
}
@@ -29,6 +29,22 @@ pub fn substitute_inlines(inlines: &[Inline], values: &std::collections::HashMap
29
29
}
30
30
31
31
pub fn substitute_string(input: &str, values: &std::collections::HashMap<String, String>) -> String {
32
substitute_params(input, values, |_| String::new())
33
}
34
35
/// Substitute `${Name}` using provided values, with sample data for unresolved parameters.
36
pub fn substitute_for_preview(
37
input: &str,
38
values: &std::collections::HashMap<String, String>,
39
) -> String {
40
substitute_params(input, values, preview_placeholder)
41
}
42
43
fn substitute_params(
44
input: &str,
45
values: &std::collections::HashMap<String, String>,
46
fallback: impl Fn(&str) -> String,
47
) -> String {
32
48
let mut out = String::new();
33
49
let chars: Vec<char> = input.chars().collect();
34
50
let mut i = 0;
@@ -41,7 +57,12 @@ pub fn substitute_string(input: &str, values: &std::collections::HashMap<String,
41
57
}
42
58
if j < chars.len() {
43
59
let name: String = chars[start..j].iter().collect();
44
out.push_str(values.get(&name).map(String::as_str).unwrap_or(""));
60
let value = values
61
.get(&name)
62
.filter(|v| !v.trim().is_empty())
63
.cloned()
64
.unwrap_or_else(|| fallback(&name));
65
out.push_str(&value);
45
66
i = j + 1;
46
67
continue;
47
68
}
@@ -52,6 +73,39 @@ pub fn substitute_string(input: &str, values: &std::collections::HashMap<String,
52
73
out
53
74
}
54
75
76
fn preview_placeholder(name: &str) -> String {
77
let lower = name.to_ascii_lowercase();
78
if lower.contains("date") {
79
return "20260115".into();
80
}
81
if lower.contains("total") || lower.contains("amount") || lower.contains("price") {
82
return "99.99".into();
83
}
84
if lower.contains("ean") || lower.contains("upc") || lower.contains("barcode") {
85
return "4006381333931".into();
86
}
87
if lower.contains("url") || lower.contains("link") || lower.contains("qr") {
88
return "https://example.com/sample".into();
89
}
90
if lower.contains("name") || lower.contains("store") {
91
return "Sample Store".into();
92
}
93
"1234567890".into()
94
}
95
96
/// Sample payload that encodes successfully for preview when user data is not valid.
97
pub fn preview_barcode_sample(symbology: crate::dsl::BarcodeSymbology) -> &'static str {
98
use crate::dsl::BarcodeSymbology;
99
match symbology {
100
BarcodeSymbology::Ean13 => "4006381333931",
101
BarcodeSymbology::Ean8 => "96385074",
102
BarcodeSymbology::UpcA => "036000291452",
103
BarcodeSymbology::Itf => "123456",
104
BarcodeSymbology::Codabar => "A40156A",
105
_ => "TEST12345",
106
}
107
}
108
55
109
pub fn substitute_document(
56
110
document: &Document,
57
111
values: &std::collections::HashMap<String, String>,
@@ -66,8 +120,9 @@ pub fn substitute_document(
66
120
align: *align,
67
121
inlines: substitute_inlines(inlines, values),
68
122
},
69
Block::Heading { level, inlines } => Block::Heading {
123
Block::Heading { level, align, inlines } => Block::Heading {
70
124
level: *level,
125
align: *align,
71
126
inlines: substitute_inlines(inlines, values),
72
127
},
73
128
Block::Rule => Block::Rule,
@@ -108,6 +163,14 @@ pub fn substitute_document(
108
163
version: *version,
109
164
align: *align,
110
165
},
166
Block::Date { format, align } => Block::Date {
167
format: format.clone(),
168
align: *align,
169
},
170
Block::Time { format, align } => Block::Time {
171
format: *format,
172
align: *align,
173
},
111
174
})
112
175
.collect();
113
176
Document { blocks }
@@ -122,7 +185,7 @@ fn collect_from_block(block: &crate::dsl::Block, names: &mut BTreeSet<String>) {
122
185
}
123
186
Block::Image { path, .. } => collect_from_raw(path, names),
124
187
Block::Barcode { data, .. } | Block::Qr { data, .. } => collect_from_raw(data, names),
125
Block::Rule | Block::Feed(_) | Block::Cut => {}
188
Block::Rule | Block::Feed(_) | Block::Cut | Block::Date { .. } | Block::Time { .. } => {}
126
189
}
127
190
}
128
191
@@ -159,6 +222,25 @@ fn collect_from_raw(text: &str, names: &mut BTreeSet<String>) {
159
222
}
160
223
}
161
224
225
pub fn substitute_inlines_for_preview(
226
inlines: &[Inline],
227
values: &std::collections::HashMap<String, String>,
228
) -> String {
229
let mut out = String::new();
230
for inline in inlines {
231
match inline {
232
Inline::Text(t) => out.push_str(t),
233
Inline::Code(t) => out.push_str(t),
234
Inline::Param(name) => {
235
out.push_str(&substitute_for_preview(&format!("${{{name}}}"), values));
236
}
237
Inline::Bold(inner) => out.push_str(&substitute_inlines_for_preview(inner, values)),
238
Inline::Italic(inner) => out.push_str(&substitute_inlines_for_preview(inner, values)),
239
}
240
}
241
out
242
}
243
162
244
#[cfg(test)]
163
245
mod tests {
164
246
use super::*;
@@ -170,6 +252,26 @@ mod tests {
170
252
assert_eq!(collect_parameter_names(&doc), vec!["A", "B"]);
171
253
}
172
254
255
#[test]
256
fn preview_substitutes_inlines() {
257
let doc = crate::dsl::parse("Hello ${Name}").unwrap();
258
let crate::dsl::Block::Paragraph { inlines, .. } = &doc.blocks[0] else {
259
panic!();
260
};
261
let mut values = HashMap::new();
262
values.insert("Name".into(), "Ada".into());
263
assert_eq!(
264
substitute_inlines_for_preview(inlines, &values),
265
"Hello Ada"
266
);
267
}
268
269
#[test]
270
fn preview_substitutes_placeholders_for_barcodes() {
271
let text = substitute_for_preview("${DocumentNumber}", &HashMap::new());
272
assert_eq!(text, "1234567890");
273
}
274
173
275
#[test]
174
276
fn substitutes_all_occurrences() {
175
277
let doc = crate::dsl::parse("Hi ${Name} and ${Name}").unwrap();
@@ -29,6 +29,22 @@ pub fn substitute_inlines(inlines: &[Inline], values: &std::collections::HashMap29
}
29
}
30
30
31
pub fn substitute_string(input: &str, values: &std::collections::HashMap<String, String>) -> String {
31
pub fn substitute_string(input: &str, values: &std::collections::HashMap<String, String>) -> String {
32
substitute_params(input, values, |_| String::new())
33
}
34
35
/// Substitute `${Name}` using provided values, with sample data for unresolved parameters.
36
pub fn substitute_for_preview(
37
input: &str,
38
values: &std::collections::HashMap<String, String>,
39
) -> String {
40
substitute_params(input, values, preview_placeholder)
41
}
42
43
fn substitute_params(
44
input: &str,
45
values: &std::collections::HashMap<String, String>,
46
fallback: impl Fn(&str) -> String,
47
) -> String {
32
let mut out = String::new();
48
let mut out = String::new();
33
let chars: Vec<char> = input.chars().collect();
49
let chars: Vec<char> = input.chars().collect();
34
let mut i = 0;
50
let mut i = 0;
@@ -41,7 +57,12 @@ pub fn substitute_string(input: &str, values: &std::collections::HashMap<String,41
}
57
}
42
if j < chars.len() {
58
if j < chars.len() {
43
let name: String = chars[start..j].iter().collect();
59
let name: String = chars[start..j].iter().collect();
44
out.push_str(values.get(&name).map(String::as_str).unwrap_or(""));
60
let value = values
61
.get(&name)
62
.filter(|v| !v.trim().is_empty())
63
.cloned()
64
.unwrap_or_else(|| fallback(&name));
65
out.push_str(&value);
45
i = j + 1;
66
i = j + 1;
46
continue;
67
continue;
47
}
68
}
@@ -52,6 +73,39 @@ pub fn substitute_string(input: &str, values: &std::collections::HashMap<String,52
out
73
out
53
}
74
}
54
75
76
fn preview_placeholder(name: &str) -> String {
77
let lower = name.to_ascii_lowercase();
78
if lower.contains("date") {
79
return "20260115".into();
80
}
81
if lower.contains("total") || lower.contains("amount") || lower.contains("price") {
82
return "99.99".into();
83
}
84
if lower.contains("ean") || lower.contains("upc") || lower.contains("barcode") {
85
return "4006381333931".into();
86
}
87
if lower.contains("url") || lower.contains("link") || lower.contains("qr") {
88
return "https://example.com/sample".into();
89
}
90
if lower.contains("name") || lower.contains("store") {
91
return "Sample Store".into();
92
}
93
"1234567890".into()
94
}
95
96
/// Sample payload that encodes successfully for preview when user data is not valid.
97
pub fn preview_barcode_sample(symbology: crate::dsl::BarcodeSymbology) -> &'static str {
98
use crate::dsl::BarcodeSymbology;
99
match symbology {
100
BarcodeSymbology::Ean13 => "4006381333931",
101
BarcodeSymbology::Ean8 => "96385074",
102
BarcodeSymbology::UpcA => "036000291452",
103
BarcodeSymbology::Itf => "123456",
104
BarcodeSymbology::Codabar => "A40156A",
105
_ => "TEST12345",
106
}
107
}
108
55
pub fn substitute_document(
109
pub fn substitute_document(
56
document: &Document,
110
document: &Document,
57
values: &std::collections::HashMap<String, String>,
111
values: &std::collections::HashMap<String, String>,
@@ -66,8 +120,9 @@ pub fn substitute_document(66
align: *align,
120
align: *align,
67
inlines: substitute_inlines(inlines, values),
121
inlines: substitute_inlines(inlines, values),
68
},
122
},
69
Block::Heading { level, inlines } => Block::Heading {
123
Block::Heading { level, align, inlines } => Block::Heading {
70
level: *level,
124
level: *level,
125
align: *align,
71
inlines: substitute_inlines(inlines, values),
126
inlines: substitute_inlines(inlines, values),
72
},
127
},
73
Block::Rule => Block::Rule,
128
Block::Rule => Block::Rule,
@@ -108,6 +163,14 @@ pub fn substitute_document(108
version: *version,
163
version: *version,
109
align: *align,
164
align: *align,
110
},
165
},
166
Block::Date { format, align } => Block::Date {
167
format: format.clone(),
168
align: *align,
169
},
170
Block::Time { format, align } => Block::Time {
171
format: *format,
172
align: *align,
173
},
111
})
174
})
112
.collect();
175
.collect();
113
Document { blocks }
176
Document { blocks }
@@ -122,7 +185,7 @@ fn collect_from_block(block: &crate::dsl::Block, names: &mut BTreeSet<String>) {122
}
185
}
123
Block::Image { path, .. } => collect_from_raw(path, names),
186
Block::Image { path, .. } => collect_from_raw(path, names),
124
Block::Barcode { data, .. } | Block::Qr { data, .. } => collect_from_raw(data, names),
187
Block::Barcode { data, .. } | Block::Qr { data, .. } => collect_from_raw(data, names),
125
Block::Rule | Block::Feed(_) | Block::Cut => {}
188
Block::Rule | Block::Feed(_) | Block::Cut | Block::Date { .. } | Block::Time { .. } => {}
126
}
189
}
127
}
190
}
128
191
@@ -159,6 +222,25 @@ fn collect_from_raw(text: &str, names: &mut BTreeSet<String>) {159
}
222
}
160
}
223
}
161
224
225
pub fn substitute_inlines_for_preview(
226
inlines: &[Inline],
227
values: &std::collections::HashMap<String, String>,
228
) -> String {
229
let mut out = String::new();
230
for inline in inlines {
231
match inline {
232
Inline::Text(t) => out.push_str(t),
233
Inline::Code(t) => out.push_str(t),
234
Inline::Param(name) => {
235
out.push_str(&substitute_for_preview(&format!("${{{name}}}"), values));
236
}
237
Inline::Bold(inner) => out.push_str(&substitute_inlines_for_preview(inner, values)),
238
Inline::Italic(inner) => out.push_str(&substitute_inlines_for_preview(inner, values)),
239
}
240
}
241
out
242
}
243
162
#[cfg(test)]
244
#[cfg(test)]
163
mod tests {
245
mod tests {
164
use super::*;
246
use super::*;
@@ -170,6 +252,26 @@ mod tests {170
assert_eq!(collect_parameter_names(&doc), vec!["A", "B"]);
252
assert_eq!(collect_parameter_names(&doc), vec!["A", "B"]);
171
}
253
}
172
254
255
#[test]
256
fn preview_substitutes_inlines() {
257
let doc = crate::dsl::parse("Hello ${Name}").unwrap();
258
let crate::dsl::Block::Paragraph { inlines, .. } = &doc.blocks[0] else {
259
panic!();
260
};
261
let mut values = HashMap::new();
262
values.insert("Name".into(), "Ada".into());
263
assert_eq!(
264
substitute_inlines_for_preview(inlines, &values),
265
"Hello Ada"
266
);
267
}
268
269
#[test]
270
fn preview_substitutes_placeholders_for_barcodes() {
271
let text = substitute_for_preview("${DocumentNumber}", &HashMap::new());
272
assert_eq!(text, "1234567890");
273
}
274
173
#[test]
275
#[test]
174
fn substitutes_all_occurrences() {
276
fn substitutes_all_occurrences() {
175
let doc = crate::dsl::parse("Hi ${Name} and ${Name}").unwrap();
277
let doc = crate::dsl::parse("Hi ${Name} and ${Name}").unwrap();
@@ -5,7 +5,7 @@ use crate::dsl::{parse, Document};
5
5
use crate::escpos::{EscPosEncoder, EscPosError};
6
6
use crate::io::{LoadError, PosFile};
7
7
use crate::params::{collect_parameter_names, substitute_document};
8
use crate::print::{print_bytes, PrintError, SerialTransport};
8
use crate::print::{open_printer_by_name, print_bytes, PrintError};
9
9
10
10
#[derive(Debug)]
11
11
pub enum PipelineError {
@@ -73,7 +73,7 @@ pub fn print_pos_file(
73
73
let file = PosFile::load_from_path(path).map_err(PipelineError::Load)?;
74
74
let base_dir = path.parent();
75
75
let bytes = encode_pos_file(&file, base_dir, params)?;
76
let mut transport = SerialTransport::open(printer_port).map_err(PipelineError::Print)?;
76
let mut transport = open_printer_by_name(printer_port).map_err(PipelineError::Print)?;
77
77
print_bytes(&mut transport, &bytes).map_err(PipelineError::Print)
78
78
}
79
79
@@ -5,7 +5,7 @@ use crate::dsl::{parse, Document};5
use crate::escpos::{EscPosEncoder, EscPosError};
5
use crate::escpos::{EscPosEncoder, EscPosError};
6
use crate::io::{LoadError, PosFile};
6
use crate::io::{LoadError, PosFile};
7
use crate::params::{collect_parameter_names, substitute_document};
7
use crate::params::{collect_parameter_names, substitute_document};
8
use crate::print::{print_bytes, PrintError, SerialTransport};
8
use crate::print::{open_printer_by_name, print_bytes, PrintError};
9
9
10
#[derive(Debug)]
10
#[derive(Debug)]
11
pub enum PipelineError {
11
pub enum PipelineError {
@@ -73,7 +73,7 @@ pub fn print_pos_file(73
let file = PosFile::load_from_path(path).map_err(PipelineError::Load)?;
73
let file = PosFile::load_from_path(path).map_err(PipelineError::Load)?;
74
let base_dir = path.parent();
74
let base_dir = path.parent();
75
let bytes = encode_pos_file(&file, base_dir, params)?;
75
let bytes = encode_pos_file(&file, base_dir, params)?;
76
let mut transport = SerialTransport::open(printer_port).map_err(PipelineError::Print)?;
76
let mut transport = open_printer_by_name(printer_port).map_err(PipelineError::Print)?;
77
print_bytes(&mut transport, &bytes).map_err(PipelineError::Print)
77
print_bytes(&mut transport, &bytes).map_err(PipelineError::Print)
78
}
78
}
79
79
@@ -1,10 +1,21 @@
1
use crate::dsl::{Align, Block, Document, Inline};
1
use std::collections::HashMap;
2
use std::path::{Path, PathBuf};
3
4
use image::GrayImage;
5
6
use crate::dsl::{
7
Align, BarcodeMode, BarcodeSymbology, Block, Document, ImageWidth, QrMode,
8
};
2
9
use crate::io::PosMetadata;
10
use crate::datetime;
11
use crate::params::{preview_barcode_sample, substitute_for_preview, substitute_inlines_for_preview};
12
use crate::raster::{render_barcode, render_qr};
13
use crate::text_wrap::{self, TextWrapStyle};
3
14
4
15
#[derive(Debug, Clone, PartialEq)]
5
16
pub struct PreviewModel {
6
17
pub lines: Vec<PreviewLine>,
7
pub width_chars: u32,
18
pub width_dots: u32,
8
19
pub width_mm: f32,
9
20
}
10
21
@@ -16,17 +27,12 @@ pub enum PreviewLine {
16
27
style: TextStyle,
17
28
},
18
29
Rule,
19
Barcode {
20
symbology: String,
21
data: String,
22
align: Align,
23
},
24
Qr {
25
data: String,
30
Graphic {
31
image: GrayImage,
26
32
align: Align,
27
33
},
28
Image {
29
label: String,
34
Error {
35
message: String,
30
36
align: Align,
31
37
},
32
38
Spacer(u8),
@@ -43,33 +49,48 @@ pub enum TextStyle {
43
49
Code,
44
50
}
45
51
46
pub fn render_preview(document: &Document, metadata: &PosMetadata) -> PreviewModel {
47
let width_chars = metadata.chars_per_line();
52
pub fn render_preview(
53
document: &Document,
54
metadata: &PosMetadata,
55
base_dir: Option<&Path>,
56
preview_params: &HashMap<String, String>,
57
) -> PreviewModel {
58
let width_dots = metadata.printable_dots() as u32;
48
59
let mut lines = Vec::new();
49
60
50
61
for block in &document.blocks {
51
62
match block {
52
63
Block::Paragraph { align, inlines } => {
53
let text = inlines_to_string(inlines);
54
for line in text.split('\n') {
64
let text = substitute_inlines_for_preview(inlines, preview_params);
65
let cols = text_wrap::wrap_cols(metadata, TextWrapStyle::Normal);
66
for line in text_wrap::wrap_text(&text, cols) {
55
67
lines.push(PreviewLine::Text {
56
content: line.to_string(),
68
content: line,
57
69
align: *align,
58
70
style: TextStyle::Normal,
59
71
});
60
72
}
61
73
}
62
Block::Heading { level, inlines } => {
74
Block::Heading { level, align, inlines } => {
63
75
let style = if *level == 1 {
64
76
TextStyle::Heading1
65
77
} else {
66
78
TextStyle::Heading2
67
79
};
68
lines.push(PreviewLine::Text {
69
content: inlines_to_string(inlines),
70
align: Align::Center,
71
style,
72
});
80
let wrap_style = if *level == 1 {
81
TextWrapStyle::Heading1
82
} else {
83
TextWrapStyle::Heading2
84
};
85
let text = substitute_inlines_for_preview(inlines, preview_params);
86
let cols = text_wrap::wrap_cols(metadata, wrap_style);
87
for line in text_wrap::wrap_text(&text, cols) {
88
lines.push(PreviewLine::Text {
89
content: line,
90
align: *align,
91
style,
92
});
93
}
73
94
}
74
95
Block::Rule => lines.push(PreviewLine::Rule),
75
96
Block::Feed(n) => lines.push(PreviewLine::Spacer(*n)),
@@ -78,73 +99,363 @@ pub fn render_preview(document: &Document, metadata: &PosMetadata) -> PreviewMod
78
99
align: Align::Center,
79
100
style: TextStyle::Code,
80
101
}),
81
Block::Image { path, align, .. } => lines.push(PreviewLine::Image {
82
label: format!("[image: {path}]"),
83
align: *align,
84
}),
102
Block::Image { path, width, align } => {
103
let path = substitute_for_preview(path, preview_params);
104
lines.push(render_image_preview(&path, *width, *align, metadata, base_dir));
105
}
85
106
Block::Barcode {
86
107
mode,
87
108
symbology,
88
109
data,
110
height,
89
111
align,
90
112
..
91
} => lines.push(PreviewLine::Barcode {
92
symbology: format!("{mode:?} {symbology:?}"),
93
data: data.clone(),
94
align: *align,
95
}),
113
} => {
114
let resolved = substitute_for_preview(data, preview_params);
115
lines.push(render_barcode_preview(
116
*mode,
117
*symbology,
118
data,
119
&resolved,
120
*height,
121
*align,
122
metadata,
123
));
124
}
96
125
Block::Qr {
97
126
mode,
98
127
data,
128
size,
129
ecc,
130
version,
99
131
align,
100
..
101
} => lines.push(PreviewLine::Qr {
102
data: format!("[{mode:?}] {data}"),
103
align: *align,
104
}),
132
} => {
133
let data = substitute_for_preview(data, preview_params);
134
lines.push(render_qr_preview(
135
*mode, &data, *size, *ecc, *version, *align, metadata,
136
));
137
}
138
Block::Date { format, align } => {
139
let text = datetime::format_date(format.as_deref());
140
let cols = text_wrap::wrap_cols(metadata, TextWrapStyle::Normal);
141
for line in text_wrap::wrap_text(&text, cols) {
142
lines.push(PreviewLine::Text {
143
content: line,
144
align: *align,
145
style: TextStyle::Normal,
146
});
147
}
148
}
149
Block::Time { format, align } => {
150
let text = datetime::format_time(*format);
151
let cols = text_wrap::wrap_cols(metadata, TextWrapStyle::Normal);
152
for line in text_wrap::wrap_text(&text, cols) {
153
lines.push(PreviewLine::Text {
154
content: line,
155
align: *align,
156
style: TextStyle::Normal,
157
});
158
}
159
}
105
160
}
106
161
}
107
162
108
163
PreviewModel {
109
164
lines,
110
width_chars,
165
width_dots,
111
166
width_mm: metadata.page_width_mm,
112
167
}
113
168
}
114
169
115
fn inlines_to_string(inlines: &[Inline]) -> String {
116
let mut out = String::new();
117
for inline in inlines {
118
match inline {
119
Inline::Text(t) => out.push_str(t),
120
Inline::Code(t) => out.push_str(t),
121
Inline::Param(t) => out.push_str(&format!("${{{t}}}")),
122
Inline::Bold(inner) => out.push_str(&inlines_to_string(inner)),
123
Inline::Italic(inner) => out.push_str(&inlines_to_string(inner)),
170
fn render_barcode_preview(
171
mode: BarcodeMode,
172
symbology: BarcodeSymbology,
173
template_data: &str,
174
resolved_data: &str,
175
height: u8,
176
align: Align,
177
metadata: &PosMetadata,
178
) -> PreviewLine {
179
let height_px = u32::from(height.max(20));
180
let resolved_data = resolved_data.trim();
181
match mode {
182
BarcodeMode::Raster | BarcodeMode::Native => {
183
match render_barcode(symbology, resolved_data, height_px) {
184
Ok(img) => scale_graphic_to_width(img, metadata.printable_dots() as u32, align),
185
Err(e) => {
186
if template_data.contains("${") {
187
if let Ok(img) =
188
render_barcode(symbology, preview_barcode_sample(symbology), height_px)
189
{
190
return scale_graphic_to_width(
191
img,
192
metadata.printable_dots() as u32,
193
align,
194
);
195
}
196
}
197
PreviewLine::Error {
198
message: format!(
199
"barcode: {e} ({} supports alphanumeric data; URLs and punctuation often fail)",
200
symbology.as_str()
201
),
202
align,
203
}
204
}
205
}
206
}
207
}
208
}
209
210
fn render_qr_preview(
211
mode: QrMode,
212
data: &str,
213
size: u8,
214
ecc: crate::dsl::QrEcc,
215
version: Option<u8>,
216
align: Align,
217
metadata: &PosMetadata,
218
) -> PreviewLine {
219
let module_pixels = u32::from(size.max(2));
220
match mode {
221
QrMode::Raster | QrMode::Native => match render_qr(data, version, ecc, module_pixels) {
222
Ok(img) => {
223
let max_w = (metadata.printable_dots() as u32).min(img.width());
224
scale_graphic_to_width(img, max_w, align)
225
}
226
Err(e) => PreviewLine::Error {
227
message: format!("qr: {e}"),
228
align,
229
},
230
},
231
}
232
}
233
234
fn render_image_preview(
235
path: &str,
236
width: ImageWidth,
237
align: Align,
238
metadata: &PosMetadata,
239
base_dir: Option<&Path>,
240
) -> PreviewLine {
241
let resolved = resolve_image_path(path, base_dir);
242
match image::open(&resolved) {
243
Ok(img) => {
244
let gray = img.to_luma8();
245
let target = target_image_width(width, metadata);
246
let scaled = scale_gray_to_width(gray, target);
247
PreviewLine::Graphic {
248
image: scaled,
249
align,
250
}
251
}
252
Err(e) => PreviewLine::Error {
253
message: format!("image {path}: {e}"),
254
align,
255
},
256
}
257
}
258
259
fn scale_graphic_to_width(img: GrayImage, target_width: u32, align: Align) -> PreviewLine {
260
PreviewLine::Graphic {
261
image: scale_gray_to_width(img, target_width),
262
align,
263
}
264
}
265
266
fn scale_gray_to_width(gray: GrayImage, target_width: u32) -> GrayImage {
267
let (w, h) = gray.dimensions();
268
if w == 0 || h == 0 {
269
return gray;
270
}
271
let new_w = target_width.min(w).max(1);
272
if new_w == w {
273
return gray;
274
}
275
let new_h = ((h as f32) * (new_w as f32 / w as f32)).max(1.0) as u32;
276
image::imageops::resize(
277
&gray,
278
new_w,
279
new_h,
280
image::imageops::FilterType::Nearest,
281
)
282
}
283
284
fn target_image_width(width: ImageWidth, metadata: &PosMetadata) -> u32 {
285
match width {
286
ImageWidth::Percent(pct) => {
287
(metadata.printable_dots() as u32 * pct as u32 / 100).max(1)
124
288
}
289
ImageWidth::Dots(d) => d as u32,
290
ImageWidth::Default => metadata.printable_dots() as u32,
291
}
292
}
293
294
fn resolve_image_path(path: &str, base_dir: Option<&Path>) -> PathBuf {
295
let p = Path::new(path);
296
if p.is_absolute() {
297
p.to_path_buf()
298
} else if let Some(base) = base_dir {
299
base.join(p)
300
} else {
301
p.to_path_buf()
125
302
}
126
out
303
}
304
305
/// Pixels per millimetre on screen (preview uses configured page width).
306
const PREVIEW_PX_PER_MM: f32 = 3.0;
307
308
pub fn preview_content_width_px(metadata: &PosMetadata) -> f32 {
309
metadata.page_width_mm * PREVIEW_PX_PER_MM
310
}
311
312
/// User-controlled zoom factor applied on top of the mm-based layout.
313
pub fn preview_zoom_scale(zoom: f32) -> f32 {
314
zoom.clamp(0.25, 4.0)
127
315
}
128
316
129
317
#[cfg(test)]
130
318
mod tests {
131
319
use super::*;
132
320
use crate::dsl::parse;
321
use std::collections::HashMap;
133
322
134
323
#[test]
135
324
fn renders_paragraph_lines() {
136
325
let doc = parse("Line1\nLine2").unwrap();
137
let model = render_preview(&doc, &PosMetadata::default());
326
let model = render_preview(&doc, &PosMetadata::default(), None, &HashMap::new());
138
327
assert!(model.lines.len() >= 2);
139
328
}
140
329
141
330
#[test]
142
fn shows_unresolved_params_in_preview() {
331
fn uses_placeholder_when_param_not_set() {
143
332
let doc = parse("${X}").unwrap();
144
let model = render_preview(&doc, &PosMetadata::default());
333
let model = render_preview(&doc, &PosMetadata::default(), None, &HashMap::new());
334
let PreviewLine::Text { content, .. } = &model.lines[0] else {
335
panic!();
336
};
337
assert_eq!(content, "1234567890");
338
}
339
340
#[test]
341
fn uses_dialog_params_in_preview() {
342
let doc = parse("Hello ${Name}").unwrap();
343
let mut params = HashMap::new();
344
params.insert("Name".into(), "Ada".into());
345
let model = render_preview(&doc, &PosMetadata::default(), None, ¶ms);
145
346
let PreviewLine::Text { content, .. } = &model.lines[0] else {
146
347
panic!();
147
348
};
148
assert_eq!(content, "${X}");
349
assert_eq!(content, "Hello Ada");
350
}
351
352
#[test]
353
fn renders_barcode_graphic() {
354
let doc = parse("@barcode CODE128 TEST").unwrap();
355
let model = render_preview(&doc, &PosMetadata::default(), None, &HashMap::new());
356
assert!(model
357
.lines
358
.iter()
359
.any(|l| matches!(l, PreviewLine::Graphic { .. })));
360
}
361
362
#[test]
363
fn renders_barcode_with_unresolved_params() {
364
let doc = parse("@barcode CODE128 ${DocumentNumber}").unwrap();
365
let model = render_preview(&doc, &PosMetadata::default(), None, &HashMap::new());
366
assert!(model
367
.lines
368
.iter()
369
.any(|l| matches!(l, PreviewLine::Graphic { .. })));
370
}
371
372
#[test]
373
fn renders_raster_code128_with_data_param() {
374
let doc = parse(
375
":center:\n# Hello\n@qr ${Data}\n@barcode RASTER CODE128 ${Data}\n",
376
)
377
.unwrap();
378
let model = render_preview(&doc, &PosMetadata::default(), None, &HashMap::new());
379
let graphics = model
380
.lines
381
.iter()
382
.filter(|l| matches!(l, PreviewLine::Graphic { .. }))
383
.count();
384
let errors: Vec<_> = model
385
.lines
386
.iter()
387
.filter_map(|l| match l {
388
PreviewLine::Error { message, .. } => Some(message.as_str()),
389
_ => None,
390
})
391
.collect();
392
assert_eq!(graphics, 2, "expected QR and barcode graphics, errors: {errors:?}");
393
}
394
395
#[test]
396
fn empty_param_value_uses_barcode_placeholder() {
397
let doc = parse("@barcode RASTER CODE128 ${Data}\n").unwrap();
398
let mut params = HashMap::new();
399
params.insert("Data".into(), String::new());
400
let model = render_preview(&doc, &PosMetadata::default(), None, ¶ms);
401
assert!(model
402
.lines
403
.iter()
404
.any(|l| matches!(l, PreviewLine::Graphic { .. })));
405
}
406
407
#[test]
408
fn shared_data_param_url_still_renders_barcode_preview() {
409
let doc = parse("@qr ${Data}\n@barcode RASTER CODE128 ${Data}\n").unwrap();
410
let mut params = HashMap::new();
411
params.insert("Data".into(), "https://example.com".into());
412
let model = render_preview(&doc, &PosMetadata::default(), None, ¶ms);
413
let graphics = model
414
.lines
415
.iter()
416
.filter(|l| matches!(l, PreviewLine::Graphic { .. }))
417
.count();
418
assert_eq!(graphics, 2, "QR and barcode preview should both render");
419
}
420
421
#[test]
422
fn persistent_center_heading_uses_center_in_preview() {
423
let doc = parse(":center:\n# Hello").unwrap();
424
let model = render_preview(&doc, &PosMetadata::default(), None, &HashMap::new());
425
let PreviewLine::Text { align, content, .. } = &model.lines[0] else {
426
panic!();
427
};
428
assert_eq!(content, "Hello");
429
assert_eq!(*align, Align::Center);
430
}
431
432
#[test]
433
fn heading_wraps_in_preview_on_narrow_paper() {
434
let doc = parse("# Proof of Transfer").unwrap();
435
let meta = PosMetadata {
436
page_width_mm: 53.0,
437
..Default::default()
438
};
439
let model = render_preview(&doc, &meta, None, &HashMap::new());
440
let text_lines: Vec<_> = model
441
.lines
442
.iter()
443
.filter_map(|l| match l {
444
PreviewLine::Text { content, style, .. } if *style == TextStyle::Heading1 => {
445
Some(content.as_str())
446
}
447
_ => None,
448
})
449
.collect();
450
assert_eq!(text_lines, vec!["Proof of", "Transfer"]);
451
}
452
453
#[test]
454
fn preview_width_follows_page_mm() {
455
let meta = PosMetadata {
456
page_width_mm: 58.0,
457
..Default::default()
458
};
459
assert!((preview_content_width_px(&meta) - 58.0 * PREVIEW_PX_PER_MM).abs() < 0.01);
149
460
}
150
461
}
@@ -1,10 +1,21 @@1
use crate::dsl::{Align, Block, Document, Inline};
1
use std::collections::HashMap;
2
use std::path::{Path, PathBuf};
3
4
use image::GrayImage;
5
6
use crate::dsl::{
7
Align, BarcodeMode, BarcodeSymbology, Block, Document, ImageWidth, QrMode,
8
};
2
use crate::io::PosMetadata;
9
use crate::io::PosMetadata;
10
use crate::datetime;
11
use crate::params::{preview_barcode_sample, substitute_for_preview, substitute_inlines_for_preview};
12
use crate::raster::{render_barcode, render_qr};
13
use crate::text_wrap::{self, TextWrapStyle};
3
14
4
#[derive(Debug, Clone, PartialEq)]
15
#[derive(Debug, Clone, PartialEq)]
5
pub struct PreviewModel {
16
pub struct PreviewModel {
6
pub lines: Vec<PreviewLine>,
17
pub lines: Vec<PreviewLine>,
7
pub width_chars: u32,
18
pub width_dots: u32,
8
pub width_mm: f32,
19
pub width_mm: f32,
9
}
20
}
10
21
@@ -16,17 +27,12 @@ pub enum PreviewLine {16
style: TextStyle,
27
style: TextStyle,
17
},
28
},
18
Rule,
29
Rule,
19
Barcode {
30
Graphic {
20
symbology: String,
31
image: GrayImage,
21
data: String,
22
align: Align,
23
},
24
Qr {
25
data: String,
26
align: Align,
32
align: Align,
27
},
33
},
28
Image {
34
Error {
29
label: String,
35
message: String,
30
align: Align,
36
align: Align,
31
},
37
},
32
Spacer(u8),
38
Spacer(u8),
@@ -43,33 +49,48 @@ pub enum TextStyle {43
Code,
49
Code,
44
}
50
}
45
51
46
pub fn render_preview(document: &Document, metadata: &PosMetadata) -> PreviewModel {
52
pub fn render_preview(
47
let width_chars = metadata.chars_per_line();
53
document: &Document,
54
metadata: &PosMetadata,
55
base_dir: Option<&Path>,
56
preview_params: &HashMap<String, String>,
57
) -> PreviewModel {
58
let width_dots = metadata.printable_dots() as u32;
48
let mut lines = Vec::new();
59
let mut lines = Vec::new();
49
60
50
for block in &document.blocks {
61
for block in &document.blocks {
51
match block {
62
match block {
52
Block::Paragraph { align, inlines } => {
63
Block::Paragraph { align, inlines } => {
53
let text = inlines_to_string(inlines);
64
let text = substitute_inlines_for_preview(inlines, preview_params);
54
for line in text.split('\n') {
65
let cols = text_wrap::wrap_cols(metadata, TextWrapStyle::Normal);
66
for line in text_wrap::wrap_text(&text, cols) {
55
lines.push(PreviewLine::Text {
67
lines.push(PreviewLine::Text {
56
content: line.to_string(),
68
content: line,
57
align: *align,
69
align: *align,
58
style: TextStyle::Normal,
70
style: TextStyle::Normal,
59
});
71
});
60
}
72
}
61
}
73
}
62
Block::Heading { level, inlines } => {
74
Block::Heading { level, align, inlines } => {
63
let style = if *level == 1 {
75
let style = if *level == 1 {
64
TextStyle::Heading1
76
TextStyle::Heading1
65
} else {
77
} else {
66
TextStyle::Heading2
78
TextStyle::Heading2
67
};
79
};
68
lines.push(PreviewLine::Text {
80
let wrap_style = if *level == 1 {
69
content: inlines_to_string(inlines),
81
TextWrapStyle::Heading1
70
align: Align::Center,
82
} else {
71
style,
83
TextWrapStyle::Heading2
72
});
84
};
85
let text = substitute_inlines_for_preview(inlines, preview_params);
86
let cols = text_wrap::wrap_cols(metadata, wrap_style);
87
for line in text_wrap::wrap_text(&text, cols) {
88
lines.push(PreviewLine::Text {
89
content: line,
90
align: *align,
91
style,
92
});
93
}
73
}
94
}
74
Block::Rule => lines.push(PreviewLine::Rule),
95
Block::Rule => lines.push(PreviewLine::Rule),
75
Block::Feed(n) => lines.push(PreviewLine::Spacer(*n)),
96
Block::Feed(n) => lines.push(PreviewLine::Spacer(*n)),
@@ -78,73 +99,363 @@ pub fn render_preview(document: &Document, metadata: &PosMetadata) -> PreviewMod78
align: Align::Center,
99
align: Align::Center,
79
style: TextStyle::Code,
100
style: TextStyle::Code,
80
}),
101
}),
81
Block::Image { path, align, .. } => lines.push(PreviewLine::Image {
102
Block::Image { path, width, align } => {
82
label: format!("[image: {path}]"),
103
let path = substitute_for_preview(path, preview_params);
83
align: *align,
104
lines.push(render_image_preview(&path, *width, *align, metadata, base_dir));
84
}),
105
}
85
Block::Barcode {
106
Block::Barcode {
86
mode,
107
mode,
87
symbology,
108
symbology,
88
data,
109
data,
110
height,
89
align,
111
align,
90
..
112
..
91
} => lines.push(PreviewLine::Barcode {
113
} => {
92
symbology: format!("{mode:?} {symbology:?}"),
114
let resolved = substitute_for_preview(data, preview_params);
93
data: data.clone(),
115
lines.push(render_barcode_preview(
94
align: *align,
116
*mode,
95
}),
117
*symbology,
118
data,
119
&resolved,
120
*height,
121
*align,
122
metadata,
123
));
124
}
96
Block::Qr {
125
Block::Qr {
97
mode,
126
mode,
98
data,
127
data,
128
size,
129
ecc,
130
version,
99
align,
131
align,
100
..
132
} => {
101
} => lines.push(PreviewLine::Qr {
133
let data = substitute_for_preview(data, preview_params);
102
data: format!("[{mode:?}] {data}"),
134
lines.push(render_qr_preview(
103
align: *align,
135
*mode, &data, *size, *ecc, *version, *align, metadata,
104
}),
136
));
137
}
138
Block::Date { format, align } => {
139
let text = datetime::format_date(format.as_deref());
140
let cols = text_wrap::wrap_cols(metadata, TextWrapStyle::Normal);
141
for line in text_wrap::wrap_text(&text, cols) {
142
lines.push(PreviewLine::Text {
143
content: line,
144
align: *align,
145
style: TextStyle::Normal,
146
});
147
}
148
}
149
Block::Time { format, align } => {
150
let text = datetime::format_time(*format);
151
let cols = text_wrap::wrap_cols(metadata, TextWrapStyle::Normal);
152
for line in text_wrap::wrap_text(&text, cols) {
153
lines.push(PreviewLine::Text {
154
content: line,
155
align: *align,
156
style: TextStyle::Normal,
157
});
158
}
159
}
105
}
160
}
106
}
161
}
107
162
108
PreviewModel {
163
PreviewModel {
109
lines,
164
lines,
110
width_chars,
165
width_dots,
111
width_mm: metadata.page_width_mm,
166
width_mm: metadata.page_width_mm,
112
}
167
}
113
}
168
}
114
169
115
fn inlines_to_string(inlines: &[Inline]) -> String {
170
fn render_barcode_preview(
116
let mut out = String::new();
171
mode: BarcodeMode,
117
for inline in inlines {
172
symbology: BarcodeSymbology,
118
match inline {
173
template_data: &str,
119
Inline::Text(t) => out.push_str(t),
174
resolved_data: &str,
120
Inline::Code(t) => out.push_str(t),
175
height: u8,
121
Inline::Param(t) => out.push_str(&format!("${{{t}}}")),
176
align: Align,
122
Inline::Bold(inner) => out.push_str(&inlines_to_string(inner)),
177
metadata: &PosMetadata,
123
Inline::Italic(inner) => out.push_str(&inlines_to_string(inner)),
178
) -> PreviewLine {
179
let height_px = u32::from(height.max(20));
180
let resolved_data = resolved_data.trim();
181
match mode {
182
BarcodeMode::Raster | BarcodeMode::Native => {
183
match render_barcode(symbology, resolved_data, height_px) {
184
Ok(img) => scale_graphic_to_width(img, metadata.printable_dots() as u32, align),
185
Err(e) => {
186
if template_data.contains("${") {
187
if let Ok(img) =
188
render_barcode(symbology, preview_barcode_sample(symbology), height_px)
189
{
190
return scale_graphic_to_width(
191
img,
192
metadata.printable_dots() as u32,
193
align,
194
);
195
}
196
}
197
PreviewLine::Error {
198
message: format!(
199
"barcode: {e} ({} supports alphanumeric data; URLs and punctuation often fail)",
200
symbology.as_str()
201
),
202
align,
203
}
204
}
205
}
206
}
207
}
208
}
209
210
fn render_qr_preview(
211
mode: QrMode,
212
data: &str,
213
size: u8,
214
ecc: crate::dsl::QrEcc,
215
version: Option<u8>,
216
align: Align,
217
metadata: &PosMetadata,
218
) -> PreviewLine {
219
let module_pixels = u32::from(size.max(2));
220
match mode {
221
QrMode::Raster | QrMode::Native => match render_qr(data, version, ecc, module_pixels) {
222
Ok(img) => {
223
let max_w = (metadata.printable_dots() as u32).min(img.width());
224
scale_graphic_to_width(img, max_w, align)
225
}
226
Err(e) => PreviewLine::Error {
227
message: format!("qr: {e}"),
228
align,
229
},
230
},
231
}
232
}
233
234
fn render_image_preview(
235
path: &str,
236
width: ImageWidth,
237
align: Align,
238
metadata: &PosMetadata,
239
base_dir: Option<&Path>,
240
) -> PreviewLine {
241
let resolved = resolve_image_path(path, base_dir);
242
match image::open(&resolved) {
243
Ok(img) => {
244
let gray = img.to_luma8();
245
let target = target_image_width(width, metadata);
246
let scaled = scale_gray_to_width(gray, target);
247
PreviewLine::Graphic {
248
image: scaled,
249
align,
250
}
251
}
252
Err(e) => PreviewLine::Error {
253
message: format!("image {path}: {e}"),
254
align,
255
},
256
}
257
}
258
259
fn scale_graphic_to_width(img: GrayImage, target_width: u32, align: Align) -> PreviewLine {
260
PreviewLine::Graphic {
261
image: scale_gray_to_width(img, target_width),
262
align,
263
}
264
}
265
266
fn scale_gray_to_width(gray: GrayImage, target_width: u32) -> GrayImage {
267
let (w, h) = gray.dimensions();
268
if w == 0 || h == 0 {
269
return gray;
270
}
271
let new_w = target_width.min(w).max(1);
272
if new_w == w {
273
return gray;
274
}
275
let new_h = ((h as f32) * (new_w as f32 / w as f32)).max(1.0) as u32;
276
image::imageops::resize(
277
&gray,
278
new_w,
279
new_h,
280
image::imageops::FilterType::Nearest,
281
)
282
}
283
284
fn target_image_width(width: ImageWidth, metadata: &PosMetadata) -> u32 {
285
match width {
286
ImageWidth::Percent(pct) => {
287
(metadata.printable_dots() as u32 * pct as u32 / 100).max(1)
124
}
288
}
289
ImageWidth::Dots(d) => d as u32,
290
ImageWidth::Default => metadata.printable_dots() as u32,
291
}
292
}
293
294
fn resolve_image_path(path: &str, base_dir: Option<&Path>) -> PathBuf {
295
let p = Path::new(path);
296
if p.is_absolute() {
297
p.to_path_buf()
298
} else if let Some(base) = base_dir {
299
base.join(p)
300
} else {
301
p.to_path_buf()
125
}
302
}
126
out
303
}
304
305
/// Pixels per millimetre on screen (preview uses configured page width).
306
const PREVIEW_PX_PER_MM: f32 = 3.0;
307
308
pub fn preview_content_width_px(metadata: &PosMetadata) -> f32 {
309
metadata.page_width_mm * PREVIEW_PX_PER_MM
310
}
311
312
/// User-controlled zoom factor applied on top of the mm-based layout.
313
pub fn preview_zoom_scale(zoom: f32) -> f32 {
314
zoom.clamp(0.25, 4.0)
127
}
315
}
128
316
129
#[cfg(test)]
317
#[cfg(test)]
130
mod tests {
318
mod tests {
131
use super::*;
319
use super::*;
132
use crate::dsl::parse;
320
use crate::dsl::parse;
321
use std::collections::HashMap;
133
322
134
#[test]
323
#[test]
135
fn renders_paragraph_lines() {
324
fn renders_paragraph_lines() {
136
let doc = parse("Line1\nLine2").unwrap();
325
let doc = parse("Line1\nLine2").unwrap();
137
let model = render_preview(&doc, &PosMetadata::default());
326
let model = render_preview(&doc, &PosMetadata::default(), None, &HashMap::new());
138
assert!(model.lines.len() >= 2);
327
assert!(model.lines.len() >= 2);
139
}
328
}
140
329
141
#[test]
330
#[test]
142
fn shows_unresolved_params_in_preview() {
331
fn uses_placeholder_when_param_not_set() {
143
let doc = parse("${X}").unwrap();
332
let doc = parse("${X}").unwrap();
144
let model = render_preview(&doc, &PosMetadata::default());
333
let model = render_preview(&doc, &PosMetadata::default(), None, &HashMap::new());
334
let PreviewLine::Text { content, .. } = &model.lines[0] else {
335
panic!();
336
};
337
assert_eq!(content, "1234567890");
338
}
339
340
#[test]
341
fn uses_dialog_params_in_preview() {
342
let doc = parse("Hello ${Name}").unwrap();
343
let mut params = HashMap::new();
344
params.insert("Name".into(), "Ada".into());
345
let model = render_preview(&doc, &PosMetadata::default(), None, ¶ms);
145
let PreviewLine::Text { content, .. } = &model.lines[0] else {
346
let PreviewLine::Text { content, .. } = &model.lines[0] else {
146
panic!();
347
panic!();
147
};
348
};
148
assert_eq!(content, "${X}");
349
assert_eq!(content, "Hello Ada");
350
}
351
352
#[test]
353
fn renders_barcode_graphic() {
354
let doc = parse("@barcode CODE128 TEST").unwrap();
355
let model = render_preview(&doc, &PosMetadata::default(), None, &HashMap::new());
356
assert!(model
357
.lines
358
.iter()
359
.any(|l| matches!(l, PreviewLine::Graphic { .. })));
360
}
361
362
#[test]
363
fn renders_barcode_with_unresolved_params() {
364
let doc = parse("@barcode CODE128 ${DocumentNumber}").unwrap();
365
let model = render_preview(&doc, &PosMetadata::default(), None, &HashMap::new());
366
assert!(model
367
.lines
368
.iter()
369
.any(|l| matches!(l, PreviewLine::Graphic { .. })));
370
}
371
372
#[test]
373
fn renders_raster_code128_with_data_param() {
374
let doc = parse(
375
":center:\n# Hello\n@qr ${Data}\n@barcode RASTER CODE128 ${Data}\n",
376
)
377
.unwrap();
378
let model = render_preview(&doc, &PosMetadata::default(), None, &HashMap::new());
379
let graphics = model
380
.lines
381
.iter()
382
.filter(|l| matches!(l, PreviewLine::Graphic { .. }))
383
.count();
384
let errors: Vec<_> = model
385
.lines
386
.iter()
387
.filter_map(|l| match l {
388
PreviewLine::Error { message, .. } => Some(message.as_str()),
389
_ => None,
390
})
391
.collect();
392
assert_eq!(graphics, 2, "expected QR and barcode graphics, errors: {errors:?}");
393
}
394
395
#[test]
396
fn empty_param_value_uses_barcode_placeholder() {
397
let doc = parse("@barcode RASTER CODE128 ${Data}\n").unwrap();
398
let mut params = HashMap::new();
399
params.insert("Data".into(), String::new());
400
let model = render_preview(&doc, &PosMetadata::default(), None, ¶ms);
401
assert!(model
402
.lines
403
.iter()
404
.any(|l| matches!(l, PreviewLine::Graphic { .. })));
405
}
406
407
#[test]
408
fn shared_data_param_url_still_renders_barcode_preview() {
409
let doc = parse("@qr ${Data}\n@barcode RASTER CODE128 ${Data}\n").unwrap();
410
let mut params = HashMap::new();
411
params.insert("Data".into(), "https://example.com".into());
412
let model = render_preview(&doc, &PosMetadata::default(), None, ¶ms);
413
let graphics = model
414
.lines
415
.iter()
416
.filter(|l| matches!(l, PreviewLine::Graphic { .. }))
417
.count();
418
assert_eq!(graphics, 2, "QR and barcode preview should both render");
419
}
420
421
#[test]
422
fn persistent_center_heading_uses_center_in_preview() {
423
let doc = parse(":center:\n# Hello").unwrap();
424
let model = render_preview(&doc, &PosMetadata::default(), None, &HashMap::new());
425
let PreviewLine::Text { align, content, .. } = &model.lines[0] else {
426
panic!();
427
};
428
assert_eq!(content, "Hello");
429
assert_eq!(*align, Align::Center);
430
}
431
432
#[test]
433
fn heading_wraps_in_preview_on_narrow_paper() {
434
let doc = parse("# Proof of Transfer").unwrap();
435
let meta = PosMetadata {
436
page_width_mm: 53.0,
437
..Default::default()
438
};
439
let model = render_preview(&doc, &meta, None, &HashMap::new());
440
let text_lines: Vec<_> = model
441
.lines
442
.iter()
443
.filter_map(|l| match l {
444
PreviewLine::Text { content, style, .. } if *style == TextStyle::Heading1 => {
445
Some(content.as_str())
446
}
447
_ => None,
448
})
449
.collect();
450
assert_eq!(text_lines, vec!["Proof of", "Transfer"]);
451
}
452
453
#[test]
454
fn preview_width_follows_page_mm() {
455
let meta = PosMetadata {
456
page_width_mm: 58.0,
457
..Default::default()
458
};
459
assert!((preview_content_width_px(&meta) - 58.0 * PREVIEW_PX_PER_MM).abs() < 0.01);
149
}
460
}
150
}
461
}
@@ -3,11 +3,30 @@ use std::time::Duration;
3
3
4
4
use serialport::SerialPortType;
5
5
6
mod usb_direct;
7
#[cfg(windows)]
8
mod win_spool;
9
10
/// Common baud rates for USB POS printers (115200 first — many modern devices).
11
pub const BAUD_RATES: [u32; 6] = [115200, 9600, 19200, 38400, 57600, 4800];
12
13
#[derive(Debug, Clone, PartialEq, Eq)]
14
pub enum PrinterTarget {
15
Serial(String),
16
UsbDirect {
17
vid: u16,
18
pid: u16,
19
bus: u8,
20
address: u8,
21
},
22
WinSpooler(String),
23
}
24
6
25
#[derive(Debug, Clone, PartialEq, Eq)]
7
26
pub struct PrinterDevice {
8
27
pub id: String,
9
28
pub display_name: String,
10
pub port_name: String,
29
pub target: PrinterTarget,
11
30
}
12
31
13
32
#[derive(Debug)]
@@ -18,6 +37,12 @@ pub enum PrintError {
18
37
Serial(serialport::Error),
19
38
}
20
39
40
impl From<serialport::Error> for PrintError {
41
fn from(value: serialport::Error) -> Self {
42
Self::Serial(value)
43
}
44
}
45
21
46
pub trait PrinterTransport {
22
47
fn write_all(&mut self, data: &[u8]) -> io::Result<()>;
23
48
fn flush(&mut self) -> io::Result<()>;
@@ -25,15 +50,24 @@ pub trait PrinterTransport {
25
50
26
51
pub struct SerialTransport {
27
52
port: Box<dyn serialport::SerialPort>,
53
pub baud_rate: u32,
28
54
}
29
55
30
56
impl SerialTransport {
31
57
pub fn open(port_name: &str) -> Result<Self, PrintError> {
32
let port = serialport::new(port_name, 9600)
33
.timeout(Duration::from_millis(2000))
34
.open()
35
.map_err(|e| PrintError::Open(e.to_string()))?;
36
Ok(Self { port })
58
let mut last_err = String::from("no baud rate succeeded");
59
for &baud in &BAUD_RATES {
60
match serialport::new(port_name, baud)
61
.timeout(Duration::from_millis(2000))
62
.open()
63
{
64
Ok(port) => {
65
return Ok(Self { port, baud_rate: baud });
66
}
67
Err(e) => last_err = format!("{baud} baud: {e}"),
68
}
69
}
70
Err(PrintError::Open(last_err))
37
71
}
38
72
}
39
73
@@ -47,33 +81,113 @@ impl PrinterTransport for SerialTransport {
47
81
}
48
82
}
49
83
84
/// List POS printers: USB printer-class devices, Windows spooler queues, then serial ports.
85
pub fn list_printers() -> Result<Vec<PrinterDevice>, PrintError> {
86
let mut devices = usb_direct::list_usb_printer_devices();
87
88
#[cfg(windows)]
89
devices.extend(win_spool::list_windows_spooler_printers());
90
91
devices.extend(list_serial_devices()?);
92
Ok(devices)
93
}
94
50
95
pub fn list_usb_serial_printers() -> Result<Vec<PrinterDevice>, serialport::Error> {
96
list_serial_devices()
97
}
98
99
fn list_serial_devices() -> Result<Vec<PrinterDevice>, serialport::Error> {
51
100
let mut devices = Vec::new();
52
101
for port in serialport::available_ports()? {
53
102
let label = match &port.port_type {
54
SerialPortType::UsbPort(info) => format!(
55
"{} — USB {}:{}",
56
port.port_name,
57
fmt_vid_pid(info.vid),
58
fmt_vid_pid(info.pid)
59
),
60
_ => format!("{} — Serial", port.port_name),
103
SerialPortType::UsbPort(info) => {
104
let product = info
105
.product
106
.as_deref()
107
.or(info.serial_number.as_deref())
108
.unwrap_or("USB device");
109
format!(
110
"{} — {product} (serial {}:{})",
111
port.port_name,
112
fmt_vid_pid(info.vid),
113
fmt_vid_pid(info.pid)
114
)
115
}
116
SerialPortType::BluetoothPort => format!("{} — Bluetooth", port.port_name),
117
SerialPortType::PciPort => format!("{} — PCI", port.port_name),
118
SerialPortType::Unknown => format!("{} — Serial", port.port_name),
61
119
};
62
120
devices.push(PrinterDevice {
63
121
id: format!("serial:{}", port.port_name),
64
122
display_name: label,
65
port_name: port.port_name.clone(),
123
target: PrinterTarget::Serial(port.port_name.clone()),
66
124
});
67
125
}
68
126
devices.sort_by(|a, b| a.display_name.cmp(&b.display_name));
69
127
Ok(devices)
70
128
}
71
129
130
pub fn open_printer(target: &PrinterTarget) -> Result<Box<dyn PrinterTransport>, PrintError> {
131
match target {
132
PrinterTarget::Serial(port) => Ok(Box::new(SerialTransport::open(port)?)),
133
PrinterTarget::UsbDirect {
134
vid,
135
pid,
136
bus,
137
address,
138
} => Ok(Box::new(usb_direct::UsbDirectTransport::open(
139
*vid, *pid, *bus, *address,
140
)?)),
141
#[cfg(windows)]
142
PrinterTarget::WinSpooler(name) => Ok(Box::new(win_spool::WinSpoolerTransport::new(
143
name.clone(),
144
))),
145
#[cfg(not(windows))]
146
PrinterTarget::WinSpooler(_) => Err(PrintError::Open(
147
"Windows spooler printing is only available on Windows".into(),
148
)),
149
}
150
}
151
152
/// Open by manual name: tries serial/COM first, then Windows spooler queue name.
153
pub fn open_printer_by_name(name: &str) -> Result<Box<dyn PrinterTransport>, PrintError> {
154
let name = name.trim();
155
if name.is_empty() {
156
return Err(PrintError::NotFound);
157
}
158
159
if let Ok(transport) = SerialTransport::open(name) {
160
return Ok(Box::new(transport));
161
}
162
163
#[cfg(windows)]
164
{
165
return Ok(Box::new(win_spool::WinSpoolerTransport::new(
166
name.to_string(),
167
)));
168
}
169
170
#[cfg(not(windows))]
171
Err(PrintError::Open(format!(
172
"could not open serial port '{name}'"
173
)))
174
}
175
72
176
fn fmt_vid_pid(v: u16) -> String {
73
177
format!("{v:04x}")
74
178
}
75
179
76
pub fn print_bytes<T: PrinterTransport>(transport: &mut T, data: &[u8]) -> Result<(), PrintError> {
180
impl PrinterTransport for Box<dyn PrinterTransport> {
181
fn write_all(&mut self, data: &[u8]) -> io::Result<()> {
182
(**self).write_all(data)
183
}
184
185
fn flush(&mut self) -> io::Result<()> {
186
(**self).flush()
187
}
188
}
189
190
pub fn print_bytes<T: PrinterTransport + ?Sized>(transport: &mut T, data: &[u8]) -> Result<(), PrintError> {
77
191
transport
78
192
.write_all(data)
79
193
.map_err(|e| PrintError::Write(e.to_string()))?;
@@ -123,8 +237,7 @@ mod tests {
123
237
124
238
#[test]
125
239
fn list_printers_returns_vec() {
126
// May be empty on CI; must not error.
127
let list = list_usb_serial_printers();
240
let list = list_printers();
128
241
assert!(list.is_ok());
129
242
}
130
243
}
@@ -3,11 +3,30 @@ use std::time::Duration;3
3
4
use serialport::SerialPortType;
4
use serialport::SerialPortType;
5
5
6
mod usb_direct;
7
#[cfg(windows)]
8
mod win_spool;
9
10
/// Common baud rates for USB POS printers (115200 first — many modern devices).
11
pub const BAUD_RATES: [u32; 6] = [115200, 9600, 19200, 38400, 57600, 4800];
12
13
#[derive(Debug, Clone, PartialEq, Eq)]
14
pub enum PrinterTarget {
15
Serial(String),
16
UsbDirect {
17
vid: u16,
18
pid: u16,
19
bus: u8,
20
address: u8,
21
},
22
WinSpooler(String),
23
}
24
6
#[derive(Debug, Clone, PartialEq, Eq)]
25
#[derive(Debug, Clone, PartialEq, Eq)]
7
pub struct PrinterDevice {
26
pub struct PrinterDevice {
8
pub id: String,
27
pub id: String,
9
pub display_name: String,
28
pub display_name: String,
10
pub port_name: String,
29
pub target: PrinterTarget,
11
}
30
}
12
31
13
#[derive(Debug)]
32
#[derive(Debug)]
@@ -18,6 +37,12 @@ pub enum PrintError {18
Serial(serialport::Error),
37
Serial(serialport::Error),
19
}
38
}
20
39
40
impl From<serialport::Error> for PrintError {
41
fn from(value: serialport::Error) -> Self {
42
Self::Serial(value)
43
}
44
}
45
21
pub trait PrinterTransport {
46
pub trait PrinterTransport {
22
fn write_all(&mut self, data: &[u8]) -> io::Result<()>;
47
fn write_all(&mut self, data: &[u8]) -> io::Result<()>;
23
fn flush(&mut self) -> io::Result<()>;
48
fn flush(&mut self) -> io::Result<()>;
@@ -25,15 +50,24 @@ pub trait PrinterTransport {25
50
26
pub struct SerialTransport {
51
pub struct SerialTransport {
27
port: Box<dyn serialport::SerialPort>,
52
port: Box<dyn serialport::SerialPort>,
53
pub baud_rate: u32,
28
}
54
}
29
55
30
impl SerialTransport {
56
impl SerialTransport {
31
pub fn open(port_name: &str) -> Result<Self, PrintError> {
57
pub fn open(port_name: &str) -> Result<Self, PrintError> {
32
let port = serialport::new(port_name, 9600)
58
let mut last_err = String::from("no baud rate succeeded");
33
.timeout(Duration::from_millis(2000))
59
for &baud in &BAUD_RATES {
34
.open()
60
match serialport::new(port_name, baud)
35
.map_err(|e| PrintError::Open(e.to_string()))?;
61
.timeout(Duration::from_millis(2000))
36
Ok(Self { port })
62
.open()
63
{
64
Ok(port) => {
65
return Ok(Self { port, baud_rate: baud });
66
}
67
Err(e) => last_err = format!("{baud} baud: {e}"),
68
}
69
}
70
Err(PrintError::Open(last_err))
37
}
71
}
38
}
72
}
39
73
@@ -47,33 +81,113 @@ impl PrinterTransport for SerialTransport {47
}
81
}
48
}
82
}
49
83
84
/// List POS printers: USB printer-class devices, Windows spooler queues, then serial ports.
85
pub fn list_printers() -> Result<Vec<PrinterDevice>, PrintError> {
86
let mut devices = usb_direct::list_usb_printer_devices();
87
88
#[cfg(windows)]
89
devices.extend(win_spool::list_windows_spooler_printers());
90
91
devices.extend(list_serial_devices()?);
92
Ok(devices)
93
}
94
50
pub fn list_usb_serial_printers() -> Result<Vec<PrinterDevice>, serialport::Error> {
95
pub fn list_usb_serial_printers() -> Result<Vec<PrinterDevice>, serialport::Error> {
96
list_serial_devices()
97
}
98
99
fn list_serial_devices() -> Result<Vec<PrinterDevice>, serialport::Error> {
51
let mut devices = Vec::new();
100
let mut devices = Vec::new();
52
for port in serialport::available_ports()? {
101
for port in serialport::available_ports()? {
53
let label = match &port.port_type {
102
let label = match &port.port_type {
54
SerialPortType::UsbPort(info) => format!(
103
SerialPortType::UsbPort(info) => {
55
"{} — USB {}:{}",
104
let product = info
56
port.port_name,
105
.product
57
fmt_vid_pid(info.vid),
106
.as_deref()
58
fmt_vid_pid(info.pid)
107
.or(info.serial_number.as_deref())
59
),
108
.unwrap_or("USB device");
60
_ => format!("{} — Serial", port.port_name),
109
format!(
110
"{} — {product} (serial {}:{})",
111
port.port_name,
112
fmt_vid_pid(info.vid),
113
fmt_vid_pid(info.pid)
114
)
115
}
116
SerialPortType::BluetoothPort => format!("{} — Bluetooth", port.port_name),
117
SerialPortType::PciPort => format!("{} — PCI", port.port_name),
118
SerialPortType::Unknown => format!("{} — Serial", port.port_name),
61
};
119
};
62
devices.push(PrinterDevice {
120
devices.push(PrinterDevice {
63
id: format!("serial:{}", port.port_name),
121
id: format!("serial:{}", port.port_name),
64
display_name: label,
122
display_name: label,
65
port_name: port.port_name.clone(),
123
target: PrinterTarget::Serial(port.port_name.clone()),
66
});
124
});
67
}
125
}
68
devices.sort_by(|a, b| a.display_name.cmp(&b.display_name));
126
devices.sort_by(|a, b| a.display_name.cmp(&b.display_name));
69
Ok(devices)
127
Ok(devices)
70
}
128
}
71
129
130
pub fn open_printer(target: &PrinterTarget) -> Result<Box<dyn PrinterTransport>, PrintError> {
131
match target {
132
PrinterTarget::Serial(port) => Ok(Box::new(SerialTransport::open(port)?)),
133
PrinterTarget::UsbDirect {
134
vid,
135
pid,
136
bus,
137
address,
138
} => Ok(Box::new(usb_direct::UsbDirectTransport::open(
139
*vid, *pid, *bus, *address,
140
)?)),
141
#[cfg(windows)]
142
PrinterTarget::WinSpooler(name) => Ok(Box::new(win_spool::WinSpoolerTransport::new(
143
name.clone(),
144
))),
145
#[cfg(not(windows))]
146
PrinterTarget::WinSpooler(_) => Err(PrintError::Open(
147
"Windows spooler printing is only available on Windows".into(),
148
)),
149
}
150
}
151
152
/// Open by manual name: tries serial/COM first, then Windows spooler queue name.
153
pub fn open_printer_by_name(name: &str) -> Result<Box<dyn PrinterTransport>, PrintError> {
154
let name = name.trim();
155
if name.is_empty() {
156
return Err(PrintError::NotFound);
157
}
158
159
if let Ok(transport) = SerialTransport::open(name) {
160
return Ok(Box::new(transport));
161
}
162
163
#[cfg(windows)]
164
{
165
return Ok(Box::new(win_spool::WinSpoolerTransport::new(
166
name.to_string(),
167
)));
168
}
169
170
#[cfg(not(windows))]
171
Err(PrintError::Open(format!(
172
"could not open serial port '{name}'"
173
)))
174
}
175
72
fn fmt_vid_pid(v: u16) -> String {
176
fn fmt_vid_pid(v: u16) -> String {
73
format!("{v:04x}")
177
format!("{v:04x}")
74
}
178
}
75
179
76
pub fn print_bytes<T: PrinterTransport>(transport: &mut T, data: &[u8]) -> Result<(), PrintError> {
180
impl PrinterTransport for Box<dyn PrinterTransport> {
181
fn write_all(&mut self, data: &[u8]) -> io::Result<()> {
182
(**self).write_all(data)
183
}
184
185
fn flush(&mut self) -> io::Result<()> {
186
(**self).flush()
187
}
188
}
189
190
pub fn print_bytes<T: PrinterTransport + ?Sized>(transport: &mut T, data: &[u8]) -> Result<(), PrintError> {
77
transport
191
transport
78
.write_all(data)
192
.write_all(data)
79
.map_err(|e| PrintError::Write(e.to_string()))?;
193
.map_err(|e| PrintError::Write(e.to_string()))?;
@@ -123,8 +237,7 @@ mod tests {123
237
124
#[test]
238
#[test]
125
fn list_printers_returns_vec() {
239
fn list_printers_returns_vec() {
126
// May be empty on CI; must not error.
240
let list = list_printers();
127
let list = list_usb_serial_printers();
128
assert!(list.is_ok());
241
assert!(list.is_ok());
129
}
242
}
130
}
243
}
@@ -0,0 +1,202 @@
1
//! USB printer-class device discovery and RAW bulk printing (libusb).
2
3
use std::io;
4
use std::time::Duration;
5
6
use rusb::{Context, Device, DeviceHandle, Direction, TransferType, UsbContext};
7
8
use super::{PrintError, PrinterDevice, PrinterTarget};
9
10
const USB_CLASS_PRINTER: u8 = 0x07;
11
const WRITE_CHUNK: usize = 512;
12
13
pub fn list_usb_printer_devices() -> Vec<PrinterDevice> {
14
let Ok(context) = Context::new() else {
15
return Vec::new();
16
};
17
18
let Ok(devices) = context.devices() else {
19
return Vec::new();
20
};
21
22
let mut out = Vec::new();
23
for device in devices.iter() {
24
let Ok(desc) = device.device_descriptor() else {
25
continue;
26
};
27
if !device_has_printer_interface(&device) {
28
continue;
29
}
30
31
let vid = desc.vendor_id();
32
let pid = desc.product_id();
33
let bus = device.bus_number();
34
let address = device.address();
35
36
let product = read_product_string(&device, &desc).unwrap_or_else(|| {
37
format!("USB printer {vid:04x}:{pid:04x}")
38
});
39
40
out.push(PrinterDevice {
41
id: format!("usb:{bus}:{address}:{vid:04x}:{pid:04x}"),
42
display_name: format!("{product} — USB {vid:04x}:{pid:04x} (direct)"),
43
target: PrinterTarget::UsbDirect {
44
vid,
45
pid,
46
bus,
47
address,
48
},
49
});
50
}
51
out
52
}
53
54
fn device_has_printer_interface(device: &Device<Context>) -> bool {
55
for config_index in 0..device.device_descriptor().map(|d| d.num_configurations()).unwrap_or(0)
56
{
57
let Ok(config) = device.config_descriptor(config_index) else {
58
continue;
59
};
60
for interface in config.interfaces() {
61
for descriptor in interface.descriptors() {
62
if descriptor.class_code() == USB_CLASS_PRINTER {
63
return true;
64
}
65
}
66
}
67
}
68
false
69
}
70
71
fn read_product_string(device: &Device<Context>, desc: &rusb::DeviceDescriptor) -> Option<String> {
72
if desc.product_string_index().is_none() {
73
return None;
74
}
75
let handle = device.open().ok()?;
76
let lang = handle
77
.read_languages(Duration::from_millis(200))
78
.ok()?
79
.into_iter()
80
.next()?;
81
handle
82
.read_product_string(lang, desc, Duration::from_millis(200))
83
.ok()
84
}
85
86
pub struct UsbDirectTransport {
87
handle: DeviceHandle<Context>,
88
endpoint: u8,
89
timeout: Duration,
90
}
91
92
impl UsbDirectTransport {
93
pub fn open(vid: u16, pid: u16, bus: u8, address: u8) -> Result<Self, PrintError> {
94
let context = Context::new().map_err(|e| PrintError::Open(e.to_string()))?;
95
let device = find_device(&context, vid, pid, bus, address)
96
.ok_or(PrintError::NotFound)?;
97
98
let handle = device
99
.open()
100
.map_err(|e| PrintError::Open(e.to_string()))?;
101
102
#[cfg(any(target_os = "linux", target_os = "macos"))]
103
if handle.kernel_driver_active(0).unwrap_or(false) {
104
let _ = handle.detach_kernel_driver(0);
105
}
106
107
let (interface, endpoint) = find_printer_out_endpoint(&device)?;
108
handle
109
.claim_interface(interface)
110
.map_err(|e| PrintError::Open(e.to_string()))?;
111
112
Ok(Self {
113
handle,
114
endpoint,
115
timeout: Duration::from_secs(5),
116
})
117
}
118
}
119
120
impl super::PrinterTransport for UsbDirectTransport {
121
fn write_all(&mut self, data: &[u8]) -> io::Result<()> {
122
for chunk in data.chunks(WRITE_CHUNK) {
123
self.handle
124
.write_bulk(self.endpoint, chunk, self.timeout)
125
.map_err(io::Error::other)?;
126
}
127
Ok(())
128
}
129
130
fn flush(&mut self) -> io::Result<()> {
131
Ok(())
132
}
133
}
134
135
fn find_device(
136
context: &Context,
137
vid: u16,
138
pid: u16,
139
bus: u8,
140
address: u8,
141
) -> Option<Device<Context>> {
142
let devices = context.devices().ok()?;
143
for device in devices.iter() {
144
let Ok(desc) = device.device_descriptor() else {
145
continue;
146
};
147
if desc.vendor_id() == vid
148
&& desc.product_id() == pid
149
&& device.bus_number() == bus
150
&& device.address() == address
151
{
152
return Some(device);
153
}
154
}
155
None
156
}
157
158
fn find_printer_out_endpoint(device: &Device<Context>) -> Result<(u8, u8), PrintError> {
159
let config = device
160
.active_config_descriptor()
161
.or_else(|_| device.config_descriptor(0))
162
.map_err(|e| PrintError::Open(e.to_string()))?;
163
164
for interface in config.interfaces() {
165
for descriptor in interface.descriptors() {
166
if descriptor.class_code() != USB_CLASS_PRINTER {
167
continue;
168
}
169
let iface = descriptor.interface_number();
170
for endpoint in descriptor.endpoint_descriptors() {
171
if endpoint.direction() == Direction::Out {
172
return Ok((iface, endpoint.address()));
173
}
174
}
175
}
176
}
177
178
for interface in config.interfaces() {
179
for descriptor in interface.descriptors() {
180
let iface = descriptor.interface_number();
181
for endpoint in descriptor.endpoint_descriptors() {
182
if endpoint.transfer_type() == TransferType::Bulk
183
&& endpoint.direction() == Direction::Out
184
{
185
return Ok((iface, endpoint.address()));
186
}
187
}
188
}
189
}
190
191
Err(PrintError::Open("no USB OUT endpoint found".into()))
192
}
193
194
#[cfg(test)]
195
mod tests {
196
use super::*;
197
198
#[test]
199
fn list_usb_devices_does_not_panic() {
200
let _ = list_usb_printer_devices();
201
}
202
}
@@ -0,0 +1,202 @@1
//! USB printer-class device discovery and RAW bulk printing (libusb).
2
3
use std::io;
4
use std::time::Duration;
5
6
use rusb::{Context, Device, DeviceHandle, Direction, TransferType, UsbContext};
7
8
use super::{PrintError, PrinterDevice, PrinterTarget};
9
10
const USB_CLASS_PRINTER: u8 = 0x07;
11
const WRITE_CHUNK: usize = 512;
12
13
pub fn list_usb_printer_devices() -> Vec<PrinterDevice> {
14
let Ok(context) = Context::new() else {
15
return Vec::new();
16
};
17
18
let Ok(devices) = context.devices() else {
19
return Vec::new();
20
};
21
22
let mut out = Vec::new();
23
for device in devices.iter() {
24
let Ok(desc) = device.device_descriptor() else {
25
continue;
26
};
27
if !device_has_printer_interface(&device) {
28
continue;
29
}
30
31
let vid = desc.vendor_id();
32
let pid = desc.product_id();
33
let bus = device.bus_number();
34
let address = device.address();
35
36
let product = read_product_string(&device, &desc).unwrap_or_else(|| {
37
format!("USB printer {vid:04x}:{pid:04x}")
38
});
39
40
out.push(PrinterDevice {
41
id: format!("usb:{bus}:{address}:{vid:04x}:{pid:04x}"),
42
display_name: format!("{product} — USB {vid:04x}:{pid:04x} (direct)"),
43
target: PrinterTarget::UsbDirect {
44
vid,
45
pid,
46
bus,
47
address,
48
},
49
});
50
}
51
out
52
}
53
54
fn device_has_printer_interface(device: &Device<Context>) -> bool {
55
for config_index in 0..device.device_descriptor().map(|d| d.num_configurations()).unwrap_or(0)
56
{
57
let Ok(config) = device.config_descriptor(config_index) else {
58
continue;
59
};
60
for interface in config.interfaces() {
61
for descriptor in interface.descriptors() {
62
if descriptor.class_code() == USB_CLASS_PRINTER {
63
return true;
64
}
65
}
66
}
67
}
68
false
69
}
70
71
fn read_product_string(device: &Device<Context>, desc: &rusb::DeviceDescriptor) -> Option<String> {
72
if desc.product_string_index().is_none() {
73
return None;
74
}
75
let handle = device.open().ok()?;
76
let lang = handle
77
.read_languages(Duration::from_millis(200))
78
.ok()?
79
.into_iter()
80
.next()?;
81
handle
82
.read_product_string(lang, desc, Duration::from_millis(200))
83
.ok()
84
}
85
86
pub struct UsbDirectTransport {
87
handle: DeviceHandle<Context>,
88
endpoint: u8,
89
timeout: Duration,
90
}
91
92
impl UsbDirectTransport {
93
pub fn open(vid: u16, pid: u16, bus: u8, address: u8) -> Result<Self, PrintError> {
94
let context = Context::new().map_err(|e| PrintError::Open(e.to_string()))?;
95
let device = find_device(&context, vid, pid, bus, address)
96
.ok_or(PrintError::NotFound)?;
97
98
let handle = device
99
.open()
100
.map_err(|e| PrintError::Open(e.to_string()))?;
101
102
#[cfg(any(target_os = "linux", target_os = "macos"))]
103
if handle.kernel_driver_active(0).unwrap_or(false) {
104
let _ = handle.detach_kernel_driver(0);
105
}
106
107
let (interface, endpoint) = find_printer_out_endpoint(&device)?;
108
handle
109
.claim_interface(interface)
110
.map_err(|e| PrintError::Open(e.to_string()))?;
111
112
Ok(Self {
113
handle,
114
endpoint,
115
timeout: Duration::from_secs(5),
116
})
117
}
118
}
119
120
impl super::PrinterTransport for UsbDirectTransport {
121
fn write_all(&mut self, data: &[u8]) -> io::Result<()> {
122
for chunk in data.chunks(WRITE_CHUNK) {
123
self.handle
124
.write_bulk(self.endpoint, chunk, self.timeout)
125
.map_err(io::Error::other)?;
126
}
127
Ok(())
128
}
129
130
fn flush(&mut self) -> io::Result<()> {
131
Ok(())
132
}
133
}
134
135
fn find_device(
136
context: &Context,
137
vid: u16,
138
pid: u16,
139
bus: u8,
140
address: u8,
141
) -> Option<Device<Context>> {
142
let devices = context.devices().ok()?;
143
for device in devices.iter() {
144
let Ok(desc) = device.device_descriptor() else {
145
continue;
146
};
147
if desc.vendor_id() == vid
148
&& desc.product_id() == pid
149
&& device.bus_number() == bus
150
&& device.address() == address
151
{
152
return Some(device);
153
}
154
}
155
None
156
}
157
158
fn find_printer_out_endpoint(device: &Device<Context>) -> Result<(u8, u8), PrintError> {
159
let config = device
160
.active_config_descriptor()
161
.or_else(|_| device.config_descriptor(0))
162
.map_err(|e| PrintError::Open(e.to_string()))?;
163
164
for interface in config.interfaces() {
165
for descriptor in interface.descriptors() {
166
if descriptor.class_code() != USB_CLASS_PRINTER {
167
continue;
168
}
169
let iface = descriptor.interface_number();
170
for endpoint in descriptor.endpoint_descriptors() {
171
if endpoint.direction() == Direction::Out {
172
return Ok((iface, endpoint.address()));
173
}
174
}
175
}
176
}
177
178
for interface in config.interfaces() {
179
for descriptor in interface.descriptors() {
180
let iface = descriptor.interface_number();
181
for endpoint in descriptor.endpoint_descriptors() {
182
if endpoint.transfer_type() == TransferType::Bulk
183
&& endpoint.direction() == Direction::Out
184
{
185
return Ok((iface, endpoint.address()));
186
}
187
}
188
}
189
}
190
191
Err(PrintError::Open("no USB OUT endpoint found".into()))
192
}
193
194
#[cfg(test)]
195
mod tests {
196
use super::*;
197
198
#[test]
199
fn list_usb_devices_does_not_panic() {
200
let _ = list_usb_printer_devices();
201
}
202
}
@@ -0,0 +1,263 @@
1
//! Windows print spooler discovery and RAW printing (like Moirai print-bridge).
2
3
use std::io;
4
use std::process::Command;
5
6
#[cfg(windows)]
7
use std::os::windows::process::CommandExt;
8
9
use serde::Deserialize;
10
11
use super::{PrintError, PrinterDevice, PrinterTarget};
12
13
#[cfg(windows)]
14
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
15
16
#[cfg(windows)]
17
fn hidden_command(program: &str) -> Command {
18
let mut command = Command::new(program);
19
command.creation_flags(CREATE_NO_WINDOW);
20
command
21
}
22
23
#[cfg(not(windows))]
24
fn hidden_command(program: &str) -> Command {
25
Command::new(program)
26
}
27
28
const POS_NAME_PATTERNS: &[&str] = &[
29
"gooj", "pt-210", "pt210", "pos-58", "pos58", "thermal", "receipt", "58mm", "pos", "escpos",
30
];
31
32
#[derive(Debug, Deserialize)]
33
struct WinPrinterRow {
34
#[serde(rename = "Name")]
35
name: String,
36
#[serde(rename = "PortName")]
37
port: String,
38
#[serde(rename = "DriverName")]
39
driver: String,
40
}
41
42
pub fn list_windows_spooler_printers() -> Vec<PrinterDevice> {
43
let Ok(rows) = query_printers() else {
44
return Vec::new();
45
};
46
47
let usable: Vec<_> = rows
48
.into_iter()
49
.filter(|row| !row.name.is_empty() && !is_com_port(&row.port))
50
.collect();
51
52
let mut matched = Vec::new();
53
let mut rest = Vec::new();
54
55
for row in usable {
56
let device = PrinterDevice {
57
id: format!("winspool:{}", row.name),
58
display_name: format!(
59
"{} — Windows printer ({})",
60
row.name,
61
row.port.trim()
62
),
63
target: PrinterTarget::WinSpooler(row.name.clone()),
64
};
65
66
if is_raw_driver(&row.driver) || matches_pos_name(&row.name) {
67
matched.push(device);
68
} else {
69
rest.push(device);
70
}
71
}
72
73
matched.extend(rest);
74
matched
75
}
76
77
fn query_printers() -> Result<Vec<WinPrinterRow>, PrintError> {
78
let output = hidden_command("powershell")
79
.args([
80
"-NoProfile",
81
"-ExecutionPolicy",
82
"Bypass",
83
"-Command",
84
"Get-Printer | Select-Object Name, PortName, DriverName | ConvertTo-Json -Compress",
85
])
86
.output()
87
.map_err(|e| PrintError::Open(e.to_string()))?;
88
89
if !output.status.success() {
90
let stderr = String::from_utf8_lossy(&output.stderr);
91
return Err(PrintError::Open(stderr.trim().to_string()));
92
}
93
94
let text = String::from_utf8_lossy(&output.stdout).trim().to_string();
95
if text.is_empty() {
96
return Ok(Vec::new());
97
}
98
99
if let Ok(rows) = serde_json::from_str::<Vec<WinPrinterRow>>(&text) {
100
return Ok(rows);
101
}
102
if let Ok(row) = serde_json::from_str::<WinPrinterRow>(&text) {
103
return Ok(vec![row]);
104
}
105
Ok(Vec::new())
106
}
107
108
fn is_com_port(port: &str) -> bool {
109
let port = port.trim();
110
port.len() >= 4
111
&& port[..3].eq_ignore_ascii_case("COM")
112
&& port[3..].chars().all(|c| c.is_ascii_digit())
113
}
114
115
fn is_raw_driver(driver: &str) -> bool {
116
let driver = driver.to_ascii_lowercase();
117
driver.contains("generic")
118
|| driver.contains("text only")
119
|| driver.contains("raw")
120
|| driver.contains("escpos")
121
}
122
123
fn matches_pos_name(name: &str) -> bool {
124
let lower = name.to_ascii_lowercase();
125
POS_NAME_PATTERNS.iter().any(|needle| lower.contains(needle))
126
}
127
128
pub struct WinSpoolerTransport {
129
printer_name: String,
130
}
131
132
impl WinSpoolerTransport {
133
pub fn new(printer_name: impl Into<String>) -> Self {
134
Self {
135
printer_name: printer_name.into(),
136
}
137
}
138
}
139
140
impl super::PrinterTransport for WinSpoolerTransport {
141
fn write_all(&mut self, data: &[u8]) -> io::Result<()> {
142
let tmp = tempfile::NamedTempFile::new()?;
143
std::fs::write(tmp.path(), data)?;
144
145
let safe_printer = self.printer_name.replace('\'', "''");
146
let safe_file = tmp
147
.path()
148
.to_string_lossy()
149
.replace('\'', "''");
150
151
let script = format!(
152
r#"
153
$ErrorActionPreference = 'Stop'
154
Add-Type @"
155
using System;
156
using System.Runtime.InteropServices;
157
public class RawPrinterHelper {{
158
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
159
public class DOCINFOA {{
160
[MarshalAs(UnmanagedType.LPStr)] public string pDocName;
161
[MarshalAs(UnmanagedType.LPStr)] public string pOutputFile;
162
[MarshalAs(UnmanagedType.LPStr)] public string pDataType;
163
}}
164
[DllImport("winspool.drv", EntryPoint = "OpenPrinterA", SetLastError = true, CharSet = CharSet.Ansi)]
165
public static extern bool OpenPrinter(string szPrinter, out IntPtr hPrinter, IntPtr pd);
166
[DllImport("winspool.drv", EntryPoint = "ClosePrinter", SetLastError = true)]
167
public static extern bool ClosePrinter(IntPtr hPrinter);
168
[DllImport("winspool.drv", EntryPoint = "StartDocPrinterA", SetLastError = true, CharSet = CharSet.Ansi)]
169
public static extern bool StartDocPrinter(IntPtr hPrinter, int level, [In] DOCINFOA di);
170
[DllImport("winspool.drv", EntryPoint = "EndDocPrinter", SetLastError = true)]
171
public static extern bool EndDocPrinter(IntPtr hPrinter);
172
[DllImport("winspool.drv", EntryPoint = "StartPagePrinter", SetLastError = true)]
173
public static extern bool StartPagePrinter(IntPtr hPrinter);
174
[DllImport("winspool.drv", EntryPoint = "EndPagePrinter", SetLastError = true)]
175
public static extern bool EndPagePrinter(IntPtr hPrinter);
176
[DllImport("winspool.drv", EntryPoint = "WritePrinter", SetLastError = true)]
177
public static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, int dwCount, out int dwWritten);
178
public static void SendBytesToPrinter(string printerName, byte[] bytes) {{
179
IntPtr hPrinter;
180
if (!OpenPrinter(printerName, out hPrinter, IntPtr.Zero)) {{
181
throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error(), "OpenPrinter failed");
182
}}
183
try {{
184
DOCINFOA di = new DOCINFOA();
185
di.pDocName = "posprint";
186
di.pDataType = "RAW";
187
if (!StartDocPrinter(hPrinter, 1, di)) {{
188
throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error(), "StartDocPrinter failed");
189
}}
190
try {{
191
if (!StartPagePrinter(hPrinter)) {{
192
throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error(), "StartPagePrinter failed");
193
}}
194
try {{
195
const int chunkSize = 512;
196
for (int offset = 0; offset < bytes.Length; offset += chunkSize) {{
197
int length = Math.Min(chunkSize, bytes.Length - offset);
198
IntPtr unmanagedBytes = Marshal.AllocCoTaskMem(length);
199
try {{
200
Marshal.Copy(bytes, offset, unmanagedBytes, length);
201
int written;
202
if (!WritePrinter(hPrinter, unmanagedBytes, length, out written) || written != length) {{
203
throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error(), "WritePrinter failed");
204
}}
205
}} finally {{
206
Marshal.FreeCoTaskMem(unmanagedBytes);
207
}}
208
}}
209
}} finally {{
210
EndPagePrinter(hPrinter);
211
}}
212
}} finally {{
213
EndDocPrinter(hPrinter);
214
}}
215
}} finally {{
216
ClosePrinter(hPrinter);
217
}}
218
}}
219
}}
220
"@
221
$bytes = [System.IO.File]::ReadAllBytes('{safe_file}')
222
[RawPrinterHelper]::SendBytesToPrinter('{safe_printer}', $bytes)
223
Write-Output 'OK'
224
"#
225
);
226
227
let output = hidden_command("powershell")
228
.args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", &script])
229
.output()
230
.map_err(io::Error::other)?;
231
232
if !output.status.success() {
233
let stderr = String::from_utf8_lossy(&output.stderr);
234
return Err(io::Error::other(stderr.trim()));
235
}
236
237
let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
238
if stdout != "OK" {
239
return Err(io::Error::other(stdout));
240
}
241
Ok(())
242
}
243
244
fn flush(&mut self) -> io::Result<()> {
245
Ok(())
246
}
247
}
248
249
#[cfg(test)]
250
mod tests {
251
use super::*;
252
253
#[test]
254
fn list_spooler_does_not_panic() {
255
let _ = list_windows_spooler_printers();
256
}
257
258
#[test]
259
fn detects_com_ports() {
260
assert!(is_com_port("COM3"));
261
assert!(!is_com_port("USB001"));
262
}
263
}
@@ -0,0 +1,263 @@1
//! Windows print spooler discovery and RAW printing (like Moirai print-bridge).
2
3
use std::io;
4
use std::process::Command;
5
6
#[cfg(windows)]
7
use std::os::windows::process::CommandExt;
8
9
use serde::Deserialize;
10
11
use super::{PrintError, PrinterDevice, PrinterTarget};
12
13
#[cfg(windows)]
14
const CREATE_NO_WINDOW: u32 = 0x0800_0000;
15
16
#[cfg(windows)]
17
fn hidden_command(program: &str) -> Command {
18
let mut command = Command::new(program);
19
command.creation_flags(CREATE_NO_WINDOW);
20
command
21
}
22
23
#[cfg(not(windows))]
24
fn hidden_command(program: &str) -> Command {
25
Command::new(program)
26
}
27
28
const POS_NAME_PATTERNS: &[&str] = &[
29
"gooj", "pt-210", "pt210", "pos-58", "pos58", "thermal", "receipt", "58mm", "pos", "escpos",
30
];
31
32
#[derive(Debug, Deserialize)]
33
struct WinPrinterRow {
34
#[serde(rename = "Name")]
35
name: String,
36
#[serde(rename = "PortName")]
37
port: String,
38
#[serde(rename = "DriverName")]
39
driver: String,
40
}
41
42
pub fn list_windows_spooler_printers() -> Vec<PrinterDevice> {
43
let Ok(rows) = query_printers() else {
44
return Vec::new();
45
};
46
47
let usable: Vec<_> = rows
48
.into_iter()
49
.filter(|row| !row.name.is_empty() && !is_com_port(&row.port))
50
.collect();
51
52
let mut matched = Vec::new();
53
let mut rest = Vec::new();
54
55
for row in usable {
56
let device = PrinterDevice {
57
id: format!("winspool:{}", row.name),
58
display_name: format!(
59
"{} — Windows printer ({})",
60
row.name,
61
row.port.trim()
62
),
63
target: PrinterTarget::WinSpooler(row.name.clone()),
64
};
65
66
if is_raw_driver(&row.driver) || matches_pos_name(&row.name) {
67
matched.push(device);
68
} else {
69
rest.push(device);
70
}
71
}
72
73
matched.extend(rest);
74
matched
75
}
76
77
fn query_printers() -> Result<Vec<WinPrinterRow>, PrintError> {
78
let output = hidden_command("powershell")
79
.args([
80
"-NoProfile",
81
"-ExecutionPolicy",
82
"Bypass",
83
"-Command",
84
"Get-Printer | Select-Object Name, PortName, DriverName | ConvertTo-Json -Compress",
85
])
86
.output()
87
.map_err(|e| PrintError::Open(e.to_string()))?;
88
89
if !output.status.success() {
90
let stderr = String::from_utf8_lossy(&output.stderr);
91
return Err(PrintError::Open(stderr.trim().to_string()));
92
}
93
94
let text = String::from_utf8_lossy(&output.stdout).trim().to_string();
95
if text.is_empty() {
96
return Ok(Vec::new());
97
}
98
99
if let Ok(rows) = serde_json::from_str::<Vec<WinPrinterRow>>(&text) {
100
return Ok(rows);
101
}
102
if let Ok(row) = serde_json::from_str::<WinPrinterRow>(&text) {
103
return Ok(vec![row]);
104
}
105
Ok(Vec::new())
106
}
107
108
fn is_com_port(port: &str) -> bool {
109
let port = port.trim();
110
port.len() >= 4
111
&& port[..3].eq_ignore_ascii_case("COM")
112
&& port[3..].chars().all(|c| c.is_ascii_digit())
113
}
114
115
fn is_raw_driver(driver: &str) -> bool {
116
let driver = driver.to_ascii_lowercase();
117
driver.contains("generic")
118
|| driver.contains("text only")
119
|| driver.contains("raw")
120
|| driver.contains("escpos")
121
}
122
123
fn matches_pos_name(name: &str) -> bool {
124
let lower = name.to_ascii_lowercase();
125
POS_NAME_PATTERNS.iter().any(|needle| lower.contains(needle))
126
}
127
128
pub struct WinSpoolerTransport {
129
printer_name: String,
130
}
131
132
impl WinSpoolerTransport {
133
pub fn new(printer_name: impl Into<String>) -> Self {
134
Self {
135
printer_name: printer_name.into(),
136
}
137
}
138
}
139
140
impl super::PrinterTransport for WinSpoolerTransport {
141
fn write_all(&mut self, data: &[u8]) -> io::Result<()> {
142
let tmp = tempfile::NamedTempFile::new()?;
143
std::fs::write(tmp.path(), data)?;
144
145
let safe_printer = self.printer_name.replace('\'', "''");
146
let safe_file = tmp
147
.path()
148
.to_string_lossy()
149
.replace('\'', "''");
150
151
let script = format!(
152
r#"
153
$ErrorActionPreference = 'Stop'
154
Add-Type @"
155
using System;
156
using System.Runtime.InteropServices;
157
public class RawPrinterHelper {{
158
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
159
public class DOCINFOA {{
160
[MarshalAs(UnmanagedType.LPStr)] public string pDocName;
161
[MarshalAs(UnmanagedType.LPStr)] public string pOutputFile;
162
[MarshalAs(UnmanagedType.LPStr)] public string pDataType;
163
}}
164
[DllImport("winspool.drv", EntryPoint = "OpenPrinterA", SetLastError = true, CharSet = CharSet.Ansi)]
165
public static extern bool OpenPrinter(string szPrinter, out IntPtr hPrinter, IntPtr pd);
166
[DllImport("winspool.drv", EntryPoint = "ClosePrinter", SetLastError = true)]
167
public static extern bool ClosePrinter(IntPtr hPrinter);
168
[DllImport("winspool.drv", EntryPoint = "StartDocPrinterA", SetLastError = true, CharSet = CharSet.Ansi)]
169
public static extern bool StartDocPrinter(IntPtr hPrinter, int level, [In] DOCINFOA di);
170
[DllImport("winspool.drv", EntryPoint = "EndDocPrinter", SetLastError = true)]
171
public static extern bool EndDocPrinter(IntPtr hPrinter);
172
[DllImport("winspool.drv", EntryPoint = "StartPagePrinter", SetLastError = true)]
173
public static extern bool StartPagePrinter(IntPtr hPrinter);
174
[DllImport("winspool.drv", EntryPoint = "EndPagePrinter", SetLastError = true)]
175
public static extern bool EndPagePrinter(IntPtr hPrinter);
176
[DllImport("winspool.drv", EntryPoint = "WritePrinter", SetLastError = true)]
177
public static extern bool WritePrinter(IntPtr hPrinter, IntPtr pBytes, int dwCount, out int dwWritten);
178
public static void SendBytesToPrinter(string printerName, byte[] bytes) {{
179
IntPtr hPrinter;
180
if (!OpenPrinter(printerName, out hPrinter, IntPtr.Zero)) {{
181
throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error(), "OpenPrinter failed");
182
}}
183
try {{
184
DOCINFOA di = new DOCINFOA();
185
di.pDocName = "posprint";
186
di.pDataType = "RAW";
187
if (!StartDocPrinter(hPrinter, 1, di)) {{
188
throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error(), "StartDocPrinter failed");
189
}}
190
try {{
191
if (!StartPagePrinter(hPrinter)) {{
192
throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error(), "StartPagePrinter failed");
193
}}
194
try {{
195
const int chunkSize = 512;
196
for (int offset = 0; offset < bytes.Length; offset += chunkSize) {{
197
int length = Math.Min(chunkSize, bytes.Length - offset);
198
IntPtr unmanagedBytes = Marshal.AllocCoTaskMem(length);
199
try {{
200
Marshal.Copy(bytes, offset, unmanagedBytes, length);
201
int written;
202
if (!WritePrinter(hPrinter, unmanagedBytes, length, out written) || written != length) {{
203
throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error(), "WritePrinter failed");
204
}}
205
}} finally {{
206
Marshal.FreeCoTaskMem(unmanagedBytes);
207
}}
208
}}
209
}} finally {{
210
EndPagePrinter(hPrinter);
211
}}
212
}} finally {{
213
EndDocPrinter(hPrinter);
214
}}
215
}} finally {{
216
ClosePrinter(hPrinter);
217
}}
218
}}
219
}}
220
"@
221
$bytes = [System.IO.File]::ReadAllBytes('{safe_file}')
222
[RawPrinterHelper]::SendBytesToPrinter('{safe_printer}', $bytes)
223
Write-Output 'OK'
224
"#
225
);
226
227
let output = hidden_command("powershell")
228
.args(["-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", &script])
229
.output()
230
.map_err(io::Error::other)?;
231
232
if !output.status.success() {
233
let stderr = String::from_utf8_lossy(&output.stderr);
234
return Err(io::Error::other(stderr.trim()));
235
}
236
237
let stdout = String::from_utf8_lossy(&output.stdout).trim().to_string();
238
if stdout != "OK" {
239
return Err(io::Error::other(stdout));
240
}
241
Ok(())
242
}
243
244
fn flush(&mut self) -> io::Result<()> {
245
Ok(())
246
}
247
}
248
249
#[cfg(test)]
250
mod tests {
251
use super::*;
252
253
#[test]
254
fn list_spooler_does_not_panic() {
255
let _ = list_windows_spooler_printers();
256
}
257
258
#[test]
259
fn detects_com_ports() {
260
assert!(is_com_port("COM3"));
261
assert!(!is_com_port("USB001"));
262
}
263
}
@@ -0,0 +1,261 @@
1
//! Shared print dialog state and UI (full app and print-only launcher).
2
3
use std::collections::HashMap;
4
use std::path::PathBuf;
5
use std::sync::mpsc::{self, Receiver, TryRecvError};
6
7
use eframe::egui;
8
9
use posprint::dsl::parse;
10
use posprint::io::{PosFile, PosMetadata};
11
use posprint::params::collect_parameter_names;
12
use posprint::pipeline;
13
use posprint::print::{
14
list_printers, open_printer, open_printer_by_name, print_bytes, PrintError, PrinterDevice,
15
};
16
17
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18
pub enum PrintExecuteResult {
19
StillOpen,
20
Printed,
21
}
22
23
pub struct PrintDialog {
24
pub param_inputs: HashMap<String, String>,
25
pub param_names: Vec<String>,
26
pub last_params: HashMap<String, String>,
27
pub printers: Vec<PrinterDevice>,
28
pub printers_loading: bool,
29
printers_rx: Option<Receiver<Result<Vec<PrinterDevice>, PrintError>>>,
30
pub selected_printer: Option<usize>,
31
pub manual_port: String,
32
pub use_manual_port: bool,
33
pub error: Option<String>,
34
}
35
36
impl Default for PrintDialog {
37
fn default() -> Self {
38
Self {
39
param_inputs: HashMap::new(),
40
param_names: Vec::new(),
41
last_params: HashMap::new(),
42
printers: Vec::new(),
43
printers_loading: false,
44
printers_rx: None,
45
selected_printer: None,
46
manual_port: String::new(),
47
use_manual_port: false,
48
error: None,
49
}
50
}
51
}
52
53
impl PrintDialog {
54
pub fn prepare(&mut self, body: &str) -> Result<(), String> {
55
self.error = None;
56
let doc = parse(body).map_err(|e| e.to_string())?;
57
self.param_names = collect_parameter_names(&doc);
58
self.param_inputs.clear();
59
for name in &self.param_names {
60
let value = self
61
.last_params
62
.get(name)
63
.cloned()
64
.unwrap_or_default();
65
self.param_inputs.insert(name.clone(), value);
66
}
67
self.start_printer_discovery();
68
Ok(())
69
}
70
71
pub fn start_printer_discovery(&mut self) {
72
self.printers_loading = true;
73
self.error = None;
74
let (tx, rx) = mpsc::channel();
75
self.printers_rx = Some(rx);
76
std::thread::spawn(move || {
77
let _ = tx.send(list_printers());
78
});
79
}
80
81
pub fn poll_printer_discovery(&mut self, ctx: &egui::Context) {
82
let Some(rx) = &self.printers_rx else {
83
return;
84
};
85
86
match rx.try_recv() {
87
Ok(result) => {
88
self.printers_rx = None;
89
self.printers_loading = false;
90
match result {
91
Ok(list) => {
92
self.printers = list;
93
if self.selected_printer.is_none() && !self.printers.is_empty() {
94
self.selected_printer = Some(0);
95
}
96
}
97
Err(e) => self.error = Some(format!("{e:?}")),
98
}
99
}
100
Err(TryRecvError::Empty) => {
101
ctx.request_repaint();
102
}
103
Err(TryRecvError::Disconnected) => {
104
self.printers_rx = None;
105
self.printers_loading = false;
106
}
107
}
108
}
109
110
pub fn refresh_printers(&mut self) {
111
self.start_printer_discovery();
112
}
113
114
pub fn apply_inputs_to_last_params(&mut self) {
115
self.last_params = self.param_inputs.clone();
116
}
117
118
pub fn execute_print(
119
&mut self,
120
body: &str,
121
metadata: &PosMetadata,
122
file_path: Option<&PathBuf>,
123
) -> PrintExecuteResult {
124
self.error = None;
125
if parse(body).is_err() {
126
self.error = Some("Template has parse errors".into());
127
return PrintExecuteResult::StillOpen;
128
}
129
130
for name in &self.param_names {
131
if !self.param_inputs.contains_key(name) {
132
self.error = Some(format!("Missing value for parameter {name}"));
133
return PrintExecuteResult::StillOpen;
134
}
135
}
136
137
self.last_params = self.param_inputs.clone();
138
139
let base_dir = file_path.and_then(|p| p.parent());
140
let file = PosFile {
141
version: 1,
142
metadata: metadata.clone(),
143
body: body.to_string(),
144
};
145
let bytes = match pipeline::encode_pos_file(&file, base_dir, &self.last_params) {
146
Ok(b) => b,
147
Err(e) => {
148
self.error = Some(e.to_string());
149
return PrintExecuteResult::StillOpen;
150
}
151
};
152
153
let transport_result = if self.use_manual_port {
154
let name = self.manual_port.trim();
155
if name.is_empty() {
156
self.error = Some("Select a printer or enter a port/queue name".into());
157
return PrintExecuteResult::StillOpen;
158
}
159
open_printer_by_name(name)
160
} else if let Some(target) = self.selected_printer_target() {
161
open_printer(target)
162
} else {
163
self.error = Some("Select a printer".into());
164
return PrintExecuteResult::StillOpen;
165
};
166
167
match transport_result {
168
Ok(mut transport) => match print_bytes(transport.as_mut(), &bytes) {
169
Ok(()) => PrintExecuteResult::Printed,
170
Err(e) => {
171
self.error = Some(format!("{e:?}"));
172
PrintExecuteResult::StillOpen
173
}
174
},
175
Err(e) => {
176
self.error = Some(format!("{e:?}"));
177
PrintExecuteResult::StillOpen
178
}
179
}
180
}
181
182
fn selected_printer_target(&self) -> Option<&posprint::print::PrinterTarget> {
183
if self.use_manual_port {
184
return None;
185
}
186
self.selected_printer
187
.and_then(|i| self.printers.get(i))
188
.map(|p| &p.target)
189
}
190
191
pub fn show_ui(&mut self, ui: &mut egui::Ui, cancel_label: &str) -> PrintDialogAction {
192
ui.heading("Parameters");
193
if self.param_names.is_empty() {
194
ui.label("No parameters in this template.");
195
} else {
196
for name in self.param_names.clone() {
197
ui.horizontal(|ui| {
198
ui.label(format!("{name}:"));
199
let entry = self.param_inputs.entry(name).or_insert_with(String::new);
200
ui.text_edit_singleline(entry);
201
});
202
}
203
}
204
205
ui.separator();
206
ui.heading("Printer");
207
ui.horizontal(|ui| {
208
if ui
209
.add_enabled(!self.printers_loading, egui::Button::new("Refresh"))
210
.clicked()
211
{
212
self.refresh_printers();
213
}
214
if self.printers_loading {
215
ui.spinner();
216
ui.label("Discovering printers…");
217
}
218
});
219
220
ui.checkbox(&mut self.use_manual_port, "Enter port or queue manually");
221
if self.use_manual_port {
222
ui.horizontal(|ui| {
223
ui.label("Port / queue:");
224
ui.text_edit_singleline(&mut self.manual_port);
225
});
226
ui.label("Examples: COM3, printer queue name (Windows), /dev/ttyUSB0 (Linux)");
227
} else if self.printers_loading && self.printers.is_empty() {
228
ui.label("Searching for USB, spooler, and serial printers…");
229
} else if self.printers.is_empty() {
230
ui.label(
231
"No printers found. Connect a USB POS printer, refresh, or enter a port/queue manually.",
232
);
233
} else {
234
for (i, printer) in self.printers.iter().enumerate() {
235
ui.selectable_value(&mut self.selected_printer, Some(i), &printer.display_name);
236
}
237
}
238
239
if let Some(err) = &self.error {
240
ui.colored_label(egui::Color32::RED, err);
241
}
242
243
let mut action = PrintDialogAction::None;
244
ui.horizontal(|ui| {
245
if ui.button(cancel_label).clicked() {
246
action = PrintDialogAction::Cancel;
247
}
248
if ui.button("Print").clicked() {
249
action = PrintDialogAction::Print;
250
}
251
});
252
action
253
}
254
}
255
256
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
257
pub enum PrintDialogAction {
258
None,
259
Cancel,
260
Print,
261
}
@@ -0,0 +1,261 @@1
//! Shared print dialog state and UI (full app and print-only launcher).
2
3
use std::collections::HashMap;
4
use std::path::PathBuf;
5
use std::sync::mpsc::{self, Receiver, TryRecvError};
6
7
use eframe::egui;
8
9
use posprint::dsl::parse;
10
use posprint::io::{PosFile, PosMetadata};
11
use posprint::params::collect_parameter_names;
12
use posprint::pipeline;
13
use posprint::print::{
14
list_printers, open_printer, open_printer_by_name, print_bytes, PrintError, PrinterDevice,
15
};
16
17
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
18
pub enum PrintExecuteResult {
19
StillOpen,
20
Printed,
21
}
22
23
pub struct PrintDialog {
24
pub param_inputs: HashMap<String, String>,
25
pub param_names: Vec<String>,
26
pub last_params: HashMap<String, String>,
27
pub printers: Vec<PrinterDevice>,
28
pub printers_loading: bool,
29
printers_rx: Option<Receiver<Result<Vec<PrinterDevice>, PrintError>>>,
30
pub selected_printer: Option<usize>,
31
pub manual_port: String,
32
pub use_manual_port: bool,
33
pub error: Option<String>,
34
}
35
36
impl Default for PrintDialog {
37
fn default() -> Self {
38
Self {
39
param_inputs: HashMap::new(),
40
param_names: Vec::new(),
41
last_params: HashMap::new(),
42
printers: Vec::new(),
43
printers_loading: false,
44
printers_rx: None,
45
selected_printer: None,
46
manual_port: String::new(),
47
use_manual_port: false,
48
error: None,
49
}
50
}
51
}
52
53
impl PrintDialog {
54
pub fn prepare(&mut self, body: &str) -> Result<(), String> {
55
self.error = None;
56
let doc = parse(body).map_err(|e| e.to_string())?;
57
self.param_names = collect_parameter_names(&doc);
58
self.param_inputs.clear();
59
for name in &self.param_names {
60
let value = self
61
.last_params
62
.get(name)
63
.cloned()
64
.unwrap_or_default();
65
self.param_inputs.insert(name.clone(), value);
66
}
67
self.start_printer_discovery();
68
Ok(())
69
}
70
71
pub fn start_printer_discovery(&mut self) {
72
self.printers_loading = true;
73
self.error = None;
74
let (tx, rx) = mpsc::channel();
75
self.printers_rx = Some(rx);
76
std::thread::spawn(move || {
77
let _ = tx.send(list_printers());
78
});
79
}
80
81
pub fn poll_printer_discovery(&mut self, ctx: &egui::Context) {
82
let Some(rx) = &self.printers_rx else {
83
return;
84
};
85
86
match rx.try_recv() {
87
Ok(result) => {
88
self.printers_rx = None;
89
self.printers_loading = false;
90
match result {
91
Ok(list) => {
92
self.printers = list;
93
if self.selected_printer.is_none() && !self.printers.is_empty() {
94
self.selected_printer = Some(0);
95
}
96
}
97
Err(e) => self.error = Some(format!("{e:?}")),
98
}
99
}
100
Err(TryRecvError::Empty) => {
101
ctx.request_repaint();
102
}
103
Err(TryRecvError::Disconnected) => {
104
self.printers_rx = None;
105
self.printers_loading = false;
106
}
107
}
108
}
109
110
pub fn refresh_printers(&mut self) {
111
self.start_printer_discovery();
112
}
113
114
pub fn apply_inputs_to_last_params(&mut self) {
115
self.last_params = self.param_inputs.clone();
116
}
117
118
pub fn execute_print(
119
&mut self,
120
body: &str,
121
metadata: &PosMetadata,
122
file_path: Option<&PathBuf>,
123
) -> PrintExecuteResult {
124
self.error = None;
125
if parse(body).is_err() {
126
self.error = Some("Template has parse errors".into());
127
return PrintExecuteResult::StillOpen;
128
}
129
130
for name in &self.param_names {
131
if !self.param_inputs.contains_key(name) {
132
self.error = Some(format!("Missing value for parameter {name}"));
133
return PrintExecuteResult::StillOpen;
134
}
135
}
136
137
self.last_params = self.param_inputs.clone();
138
139
let base_dir = file_path.and_then(|p| p.parent());
140
let file = PosFile {
141
version: 1,
142
metadata: metadata.clone(),
143
body: body.to_string(),
144
};
145
let bytes = match pipeline::encode_pos_file(&file, base_dir, &self.last_params) {
146
Ok(b) => b,
147
Err(e) => {
148
self.error = Some(e.to_string());
149
return PrintExecuteResult::StillOpen;
150
}
151
};
152
153
let transport_result = if self.use_manual_port {
154
let name = self.manual_port.trim();
155
if name.is_empty() {
156
self.error = Some("Select a printer or enter a port/queue name".into());
157
return PrintExecuteResult::StillOpen;
158
}
159
open_printer_by_name(name)
160
} else if let Some(target) = self.selected_printer_target() {
161
open_printer(target)
162
} else {
163
self.error = Some("Select a printer".into());
164
return PrintExecuteResult::StillOpen;
165
};
166
167
match transport_result {
168
Ok(mut transport) => match print_bytes(transport.as_mut(), &bytes) {
169
Ok(()) => PrintExecuteResult::Printed,
170
Err(e) => {
171
self.error = Some(format!("{e:?}"));
172
PrintExecuteResult::StillOpen
173
}
174
},
175
Err(e) => {
176
self.error = Some(format!("{e:?}"));
177
PrintExecuteResult::StillOpen
178
}
179
}
180
}
181
182
fn selected_printer_target(&self) -> Option<&posprint::print::PrinterTarget> {
183
if self.use_manual_port {
184
return None;
185
}
186
self.selected_printer
187
.and_then(|i| self.printers.get(i))
188
.map(|p| &p.target)
189
}
190
191
pub fn show_ui(&mut self, ui: &mut egui::Ui, cancel_label: &str) -> PrintDialogAction {
192
ui.heading("Parameters");
193
if self.param_names.is_empty() {
194
ui.label("No parameters in this template.");
195
} else {
196
for name in self.param_names.clone() {
197
ui.horizontal(|ui| {
198
ui.label(format!("{name}:"));
199
let entry = self.param_inputs.entry(name).or_insert_with(String::new);
200
ui.text_edit_singleline(entry);
201
});
202
}
203
}
204
205
ui.separator();
206
ui.heading("Printer");
207
ui.horizontal(|ui| {
208
if ui
209
.add_enabled(!self.printers_loading, egui::Button::new("Refresh"))
210
.clicked()
211
{
212
self.refresh_printers();
213
}
214
if self.printers_loading {
215
ui.spinner();
216
ui.label("Discovering printers…");
217
}
218
});
219
220
ui.checkbox(&mut self.use_manual_port, "Enter port or queue manually");
221
if self.use_manual_port {
222
ui.horizontal(|ui| {
223
ui.label("Port / queue:");
224
ui.text_edit_singleline(&mut self.manual_port);
225
});
226
ui.label("Examples: COM3, printer queue name (Windows), /dev/ttyUSB0 (Linux)");
227
} else if self.printers_loading && self.printers.is_empty() {
228
ui.label("Searching for USB, spooler, and serial printers…");
229
} else if self.printers.is_empty() {
230
ui.label(
231
"No printers found. Connect a USB POS printer, refresh, or enter a port/queue manually.",
232
);
233
} else {
234
for (i, printer) in self.printers.iter().enumerate() {
235
ui.selectable_value(&mut self.selected_printer, Some(i), &printer.display_name);
236
}
237
}
238
239
if let Some(err) = &self.error {
240
ui.colored_label(egui::Color32::RED, err);
241
}
242
243
let mut action = PrintDialogAction::None;
244
ui.horizontal(|ui| {
245
if ui.button(cancel_label).clicked() {
246
action = PrintDialogAction::Cancel;
247
}
248
if ui.button("Print").clicked() {
249
action = PrintDialogAction::Print;
250
}
251
});
252
action
253
}
254
}
255
256
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
257
pub enum PrintDialogAction {
258
None,
259
Cancel,
260
Print,
261
}
@@ -0,0 +1,106 @@
1
//! Minimal UI: print dialog only, then exit.
2
3
use std::path::PathBuf;
4
5
use eframe::egui;
6
7
use posprint::io::{PosFile, PosMetadata};
8
9
use crate::print_dialog::{PrintDialog, PrintDialogAction, PrintExecuteResult};
10
11
pub struct PrintOnlyApp {
12
body: String,
13
metadata: PosMetadata,
14
file_path: PathBuf,
15
dialog: PrintDialog,
16
fatal_error: Option<String>,
17
exit_requested: bool,
18
}
19
20
impl PrintOnlyApp {
21
pub fn new(path: PathBuf) -> Self {
22
let mut app = Self {
23
body: String::new(),
24
metadata: PosMetadata::default(),
25
file_path: path.clone(),
26
dialog: PrintDialog::default(),
27
fatal_error: None,
28
exit_requested: false,
29
};
30
31
match PosFile::load_from_path(&path) {
32
Ok(file) => {
33
app.body = file.body;
34
app.metadata = file.metadata;
35
if let Err(e) = app.dialog.prepare(&app.body) {
36
app.fatal_error = Some(e);
37
}
38
}
39
Err(e) => app.fatal_error = Some(format!("Could not open file: {e:?}")),
40
}
41
42
app
43
}
44
45
fn title(&self) -> String {
46
let name = self
47
.file_path
48
.file_name()
49
.map(|s| s.to_string_lossy().to_string())
50
.unwrap_or_else(|| "Print".into());
51
format!("Print — {name}")
52
}
53
54
fn request_exit(&mut self) {
55
self.exit_requested = true;
56
}
57
}
58
59
impl eframe::App for PrintOnlyApp {
60
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
61
if self.exit_requested {
62
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
63
return;
64
}
65
66
self.dialog.poll_printer_discovery(ctx);
67
ctx.send_viewport_cmd(egui::ViewportCommand::Title(self.title()));
68
69
if let Some(err) = self.fatal_error.clone() {
70
egui::CentralPanel::default().show(ctx, |ui| {
71
ui.heading("Print");
72
ui.separator();
73
ui.colored_label(egui::Color32::RED, err);
74
if ui.button("Close").clicked() {
75
self.request_exit();
76
}
77
});
78
return;
79
}
80
81
let mut window_open = true;
82
egui::Window::new("Print")
83
.collapsible(false)
84
.resizable(false)
85
.open(&mut window_open)
86
.anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
87
.show(ctx, |ui| {
88
match self.dialog.show_ui(ui, "Cancel") {
89
PrintDialogAction::Cancel => self.request_exit(),
90
PrintDialogAction::Print => {
91
if self.dialog.execute_print(&self.body, &self.metadata, Some(&self.file_path))
92
== PrintExecuteResult::Printed
93
{
94
self.request_exit();
95
}
96
}
97
PrintDialogAction::None => {}
98
}
99
});
100
101
if !window_open {
102
self.dialog.apply_inputs_to_last_params();
103
self.request_exit();
104
}
105
}
106
}
@@ -0,0 +1,106 @@1
//! Minimal UI: print dialog only, then exit.
2
3
use std::path::PathBuf;
4
5
use eframe::egui;
6
7
use posprint::io::{PosFile, PosMetadata};
8
9
use crate::print_dialog::{PrintDialog, PrintDialogAction, PrintExecuteResult};
10
11
pub struct PrintOnlyApp {
12
body: String,
13
metadata: PosMetadata,
14
file_path: PathBuf,
15
dialog: PrintDialog,
16
fatal_error: Option<String>,
17
exit_requested: bool,
18
}
19
20
impl PrintOnlyApp {
21
pub fn new(path: PathBuf) -> Self {
22
let mut app = Self {
23
body: String::new(),
24
metadata: PosMetadata::default(),
25
file_path: path.clone(),
26
dialog: PrintDialog::default(),
27
fatal_error: None,
28
exit_requested: false,
29
};
30
31
match PosFile::load_from_path(&path) {
32
Ok(file) => {
33
app.body = file.body;
34
app.metadata = file.metadata;
35
if let Err(e) = app.dialog.prepare(&app.body) {
36
app.fatal_error = Some(e);
37
}
38
}
39
Err(e) => app.fatal_error = Some(format!("Could not open file: {e:?}")),
40
}
41
42
app
43
}
44
45
fn title(&self) -> String {
46
let name = self
47
.file_path
48
.file_name()
49
.map(|s| s.to_string_lossy().to_string())
50
.unwrap_or_else(|| "Print".into());
51
format!("Print — {name}")
52
}
53
54
fn request_exit(&mut self) {
55
self.exit_requested = true;
56
}
57
}
58
59
impl eframe::App for PrintOnlyApp {
60
fn update(&mut self, ctx: &egui::Context, _frame: &mut eframe::Frame) {
61
if self.exit_requested {
62
ctx.send_viewport_cmd(egui::ViewportCommand::Close);
63
return;
64
}
65
66
self.dialog.poll_printer_discovery(ctx);
67
ctx.send_viewport_cmd(egui::ViewportCommand::Title(self.title()));
68
69
if let Some(err) = self.fatal_error.clone() {
70
egui::CentralPanel::default().show(ctx, |ui| {
71
ui.heading("Print");
72
ui.separator();
73
ui.colored_label(egui::Color32::RED, err);
74
if ui.button("Close").clicked() {
75
self.request_exit();
76
}
77
});
78
return;
79
}
80
81
let mut window_open = true;
82
egui::Window::new("Print")
83
.collapsible(false)
84
.resizable(false)
85
.open(&mut window_open)
86
.anchor(egui::Align2::CENTER_CENTER, [0.0, 0.0])
87
.show(ctx, |ui| {
88
match self.dialog.show_ui(ui, "Cancel") {
89
PrintDialogAction::Cancel => self.request_exit(),
90
PrintDialogAction::Print => {
91
if self.dialog.execute_print(&self.body, &self.metadata, Some(&self.file_path))
92
== PrintExecuteResult::Printed
93
{
94
self.request_exit();
95
}
96
}
97
PrintDialogAction::None => {}
98
}
99
});
100
101
if !window_open {
102
self.dialog.apply_inputs_to_last_params();
103
self.request_exit();
104
}
105
}
106
}
@@ -134,6 +134,12 @@ mod tests {
134
134
assert_eq!(img.height(), 60);
135
135
}
136
136
137
#[test]
138
fn code128_rejects_url_like_data() {
139
let err = render_barcode(BarcodeSymbology::Code128, "https://example.com", 60).unwrap_err();
140
assert!(err.to_string().contains("invalid"));
141
}
142
137
143
#[test]
138
144
fn renders_qr_raster_with_version() {
139
145
let img = render_qr("https://example.com", Some(5), QrEcc::M, 4).unwrap();
@@ -134,6 +134,12 @@ mod tests {134
assert_eq!(img.height(), 60);
134
assert_eq!(img.height(), 60);
135
}
135
}
136
136
137
#[test]
138
fn code128_rejects_url_like_data() {
139
let err = render_barcode(BarcodeSymbology::Code128, "https://example.com", 60).unwrap_err();
140
assert!(err.to_string().contains("invalid"));
141
}
142
137
#[test]
143
#[test]
138
fn renders_qr_raster_with_version() {
144
fn renders_qr_raster_with_version() {
139
let img = render_qr("https://example.com", Some(5), QrEcc::M, 4).unwrap();
145
let img = render_qr("https://example.com", Some(5), QrEcc::M, 4).unwrap();
@@ -0,0 +1,64 @@
1
//! Register a Explorer / file-manager "Print" action for `.pos` templates.
2
3
/// Install or refresh shell integration (best-effort; ignores errors).
4
pub fn ensure_print_context_menu() {
5
#[cfg(windows)]
6
windows::register_print_context_menu();
7
}
8
9
#[cfg(windows)]
10
mod windows {
11
use std::path::Path;
12
13
pub fn register_print_context_menu() {
14
let Ok(exe) = std::env::current_exe() else {
15
return;
16
};
17
let Some(cmd) = print_command_for_exe(&exe) else {
18
return;
19
};
20
let _ = write_user_context_menu(&cmd);
21
}
22
23
pub fn print_command_for_exe(exe: &Path) -> Option<String> {
24
let exe = exe.to_string_lossy();
25
if exe.is_empty() {
26
return None;
27
}
28
Some(format!("\"{exe}\" --print \"%1\""))
29
}
30
31
fn write_user_context_menu(command: &str) -> Result<(), String> {
32
use winreg::enums::HKEY_CURRENT_USER;
33
use winreg::RegKey;
34
35
const SHELL_KEY: &str = r"Software\Classes\.pos\shell\PosprintPrint";
36
const COMMAND_KEY: &str = r"Software\Classes\.pos\shell\PosprintPrint\command";
37
38
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
39
let (shell, _) = hkcu
40
.create_subkey(SHELL_KEY)
41
.map_err(|e| e.to_string())?;
42
shell
43
.set_value("", &"Print")
44
.map_err(|e| e.to_string())?;
45
46
let (cmd, _) = hkcu
47
.create_subkey(COMMAND_KEY)
48
.map_err(|e| e.to_string())?;
49
cmd.set_value("", &command)
50
.map_err(|e| e.to_string())?;
51
Ok(())
52
}
53
54
#[cfg(test)]
55
mod tests {
56
use super::*;
57
58
#[test]
59
fn builds_print_command() {
60
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""#);
62
}
63
}
64
}
@@ -0,0 +1,64 @@1
//! Register a Explorer / file-manager "Print" action for `.pos` templates.
2
3
/// Install or refresh shell integration (best-effort; ignores errors).
4
pub fn ensure_print_context_menu() {
5
#[cfg(windows)]
6
windows::register_print_context_menu();
7
}
8
9
#[cfg(windows)]
10
mod windows {
11
use std::path::Path;
12
13
pub fn register_print_context_menu() {
14
let Ok(exe) = std::env::current_exe() else {
15
return;
16
};
17
let Some(cmd) = print_command_for_exe(&exe) else {
18
return;
19
};
20
let _ = write_user_context_menu(&cmd);
21
}
22
23
pub fn print_command_for_exe(exe: &Path) -> Option<String> {
24
let exe = exe.to_string_lossy();
25
if exe.is_empty() {
26
return None;
27
}
28
Some(format!("\"{exe}\" --print \"%1\""))
29
}
30
31
fn write_user_context_menu(command: &str) -> Result<(), String> {
32
use winreg::enums::HKEY_CURRENT_USER;
33
use winreg::RegKey;
34
35
const SHELL_KEY: &str = r"Software\Classes\.pos\shell\PosprintPrint";
36
const COMMAND_KEY: &str = r"Software\Classes\.pos\shell\PosprintPrint\command";
37
38
let hkcu = RegKey::predef(HKEY_CURRENT_USER);
39
let (shell, _) = hkcu
40
.create_subkey(SHELL_KEY)
41
.map_err(|e| e.to_string())?;
42
shell
43
.set_value("", &"Print")
44
.map_err(|e| e.to_string())?;
45
46
let (cmd, _) = hkcu
47
.create_subkey(COMMAND_KEY)
48
.map_err(|e| e.to_string())?;
49
cmd.set_value("", &command)
50
.map_err(|e| e.to_string())?;
51
Ok(())
52
}
53
54
#[cfg(test)]
55
mod tests {
56
use super::*;
57
58
#[test]
59
fn builds_print_command() {
60
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""#);
62
}
63
}
64
}
@@ -0,0 +1,123 @@
1
use crate::io::PosMetadata;
2
3
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4
pub enum TextWrapStyle {
5
Normal,
6
Heading1,
7
Heading2,
8
}
9
10
/// Character columns available for a text style on the target printer.
11
pub fn wrap_cols(metadata: &PosMetadata, style: TextWrapStyle) -> usize {
12
let base = metadata.chars_per_line().max(1) as usize;
13
match style {
14
TextWrapStyle::Heading1 => (base / 2).max(1),
15
TextWrapStyle::Normal | TextWrapStyle::Heading2 => base,
16
}
17
}
18
19
/// Word-wrap `text` to at most `max_cols` characters per line.
20
/// Explicit newlines in `text` start a new wrapped paragraph.
21
pub fn wrap_text(text: &str, max_cols: usize) -> Vec<String> {
22
if max_cols == 0 {
23
return vec![text.to_string()];
24
}
25
26
let mut lines = Vec::new();
27
for paragraph in text.split('\n') {
28
lines.extend(wrap_line(paragraph, max_cols));
29
}
30
if lines.is_empty() {
31
lines.push(String::new());
32
}
33
lines
34
}
35
36
fn wrap_line(line: &str, max_cols: usize) -> Vec<String> {
37
if line.is_empty() {
38
return vec![String::new()];
39
}
40
41
let mut lines = Vec::new();
42
let mut current = String::new();
43
44
for word in line.split_whitespace() {
45
let word_len = word.chars().count();
46
if current.is_empty() {
47
if word_len <= max_cols {
48
current.push_str(word);
49
} else {
50
lines.extend(split_long_word(word, max_cols));
51
}
52
} else {
53
let current_len = current.chars().count();
54
if current_len + 1 + word_len <= max_cols {
55
current.push(' ');
56
current.push_str(word);
57
} else {
58
lines.push(std::mem::take(&mut current));
59
if word_len <= max_cols {
60
current.push_str(word);
61
} else {
62
lines.extend(split_long_word(word, max_cols));
63
}
64
}
65
}
66
}
67
68
if !current.is_empty() {
69
lines.push(current);
70
}
71
72
if lines.is_empty() {
73
lines.push(String::new());
74
}
75
lines
76
}
77
78
fn split_long_word(word: &str, max_cols: usize) -> Vec<String> {
79
let mut chunks = Vec::new();
80
let mut chunk = String::new();
81
for ch in word.chars() {
82
if chunk.chars().count() >= max_cols {
83
chunks.push(std::mem::take(&mut chunk));
84
}
85
chunk.push(ch);
86
}
87
if !chunk.is_empty() {
88
chunks.push(chunk);
89
}
90
chunks
91
}
92
93
#[cfg(test)]
94
mod tests {
95
use super::*;
96
97
fn meta_53mm() -> PosMetadata {
98
PosMetadata {
99
page_width_mm: 53.0,
100
..Default::default()
101
}
102
}
103
104
#[test]
105
fn heading1_wraps_at_half_line_width() {
106
let cols = wrap_cols(&meta_53mm(), TextWrapStyle::Heading1);
107
assert_eq!(cols, 16);
108
let lines = wrap_text("Proof of Transfer", cols);
109
assert_eq!(lines, vec!["Proof of", "Transfer"]);
110
}
111
112
#[test]
113
fn preserves_explicit_newlines() {
114
let lines = wrap_text("Line one\nLine two", 32);
115
assert_eq!(lines, vec!["Line one", "Line two"]);
116
}
117
118
#[test]
119
fn normal_text_wraps_at_full_width() {
120
let cols = wrap_cols(&meta_53mm(), TextWrapStyle::Normal);
121
assert_eq!(cols, 32);
122
}
123
}
@@ -0,0 +1,123 @@1
use crate::io::PosMetadata;
2
3
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
4
pub enum TextWrapStyle {
5
Normal,
6
Heading1,
7
Heading2,
8
}
9
10
/// Character columns available for a text style on the target printer.
11
pub fn wrap_cols(metadata: &PosMetadata, style: TextWrapStyle) -> usize {
12
let base = metadata.chars_per_line().max(1) as usize;
13
match style {
14
TextWrapStyle::Heading1 => (base / 2).max(1),
15
TextWrapStyle::Normal | TextWrapStyle::Heading2 => base,
16
}
17
}
18
19
/// Word-wrap `text` to at most `max_cols` characters per line.
20
/// Explicit newlines in `text` start a new wrapped paragraph.
21
pub fn wrap_text(text: &str, max_cols: usize) -> Vec<String> {
22
if max_cols == 0 {
23
return vec![text.to_string()];
24
}
25
26
let mut lines = Vec::new();
27
for paragraph in text.split('\n') {
28
lines.extend(wrap_line(paragraph, max_cols));
29
}
30
if lines.is_empty() {
31
lines.push(String::new());
32
}
33
lines
34
}
35
36
fn wrap_line(line: &str, max_cols: usize) -> Vec<String> {
37
if line.is_empty() {
38
return vec![String::new()];
39
}
40
41
let mut lines = Vec::new();
42
let mut current = String::new();
43
44
for word in line.split_whitespace() {
45
let word_len = word.chars().count();
46
if current.is_empty() {
47
if word_len <= max_cols {
48
current.push_str(word);
49
} else {
50
lines.extend(split_long_word(word, max_cols));
51
}
52
} else {
53
let current_len = current.chars().count();
54
if current_len + 1 + word_len <= max_cols {
55
current.push(' ');
56
current.push_str(word);
57
} else {
58
lines.push(std::mem::take(&mut current));
59
if word_len <= max_cols {
60
current.push_str(word);
61
} else {
62
lines.extend(split_long_word(word, max_cols));
63
}
64
}
65
}
66
}
67
68
if !current.is_empty() {
69
lines.push(current);
70
}
71
72
if lines.is_empty() {
73
lines.push(String::new());
74
}
75
lines
76
}
77
78
fn split_long_word(word: &str, max_cols: usize) -> Vec<String> {
79
let mut chunks = Vec::new();
80
let mut chunk = String::new();
81
for ch in word.chars() {
82
if chunk.chars().count() >= max_cols {
83
chunks.push(std::mem::take(&mut chunk));
84
}
85
chunk.push(ch);
86
}
87
if !chunk.is_empty() {
88
chunks.push(chunk);
89
}
90
chunks
91
}
92
93
#[cfg(test)]
94
mod tests {
95
use super::*;
96
97
fn meta_53mm() -> PosMetadata {
98
PosMetadata {
99
page_width_mm: 53.0,
100
..Default::default()
101
}
102
}
103
104
#[test]
105
fn heading1_wraps_at_half_line_width() {
106
let cols = wrap_cols(&meta_53mm(), TextWrapStyle::Heading1);
107
assert_eq!(cols, 16);
108
let lines = wrap_text("Proof of Transfer", cols);
109
assert_eq!(lines, vec!["Proof of", "Transfer"]);
110
}
111
112
#[test]
113
fn preserves_explicit_newlines() {
114
let lines = wrap_text("Line one\nLine two", 32);
115
assert_eq!(lines, vec!["Line one", "Line two"]);
116
}
117
118
#[test]
119
fn normal_text_wraps_at_full_width() {
120
let cols = wrap_cols(&meta_53mm(), TextWrapStyle::Normal);
121
assert_eq!(cols, 32);
122
}
123
}
@@ -0,0 +1,59 @@
1
//! Simple undo/redo stack for editor text.
2
3
const DEFAULT_LIMIT: usize = 100;
4
5
pub struct TextUndo {
6
undo: Vec<String>,
7
redo: Vec<String>,
8
limit: usize,
9
}
10
11
impl Default for TextUndo {
12
fn default() -> Self {
13
Self {
14
undo: Vec::new(),
15
redo: Vec::new(),
16
limit: DEFAULT_LIMIT,
17
}
18
}
19
}
20
21
impl TextUndo {
22
pub fn record(&mut self, before: String) {
23
if self.undo.last() == Some(&before) {
24
return;
25
}
26
self.undo.push(before);
27
if self.undo.len() > self.limit {
28
self.undo.remove(0);
29
}
30
self.redo.clear();
31
}
32
33
pub fn undo(&mut self, current: &str) -> Option<String> {
34
let prev = self.undo.pop()?;
35
self.redo.push(current.to_string());
36
Some(prev)
37
}
38
39
pub fn redo(&mut self, current: &str) -> Option<String> {
40
let next = self.redo.pop()?;
41
self.undo.push(current.to_string());
42
Some(next)
43
}
44
}
45
46
#[cfg(test)]
47
mod tests {
48
use super::*;
49
50
#[test]
51
fn undo_redo_roundtrip() {
52
let mut stack = TextUndo::default();
53
stack.record("a".into());
54
let u = stack.undo("b").unwrap();
55
assert_eq!(u, "a");
56
let r = stack.redo("a").unwrap();
57
assert_eq!(r, "b");
58
}
59
}
@@ -0,0 +1,59 @@1
//! Simple undo/redo stack for editor text.
2
3
const DEFAULT_LIMIT: usize = 100;
4
5
pub struct TextUndo {
6
undo: Vec<String>,
7
redo: Vec<String>,
8
limit: usize,
9
}
10
11
impl Default for TextUndo {
12
fn default() -> Self {
13
Self {
14
undo: Vec::new(),
15
redo: Vec::new(),
16
limit: DEFAULT_LIMIT,
17
}
18
}
19
}
20
21
impl TextUndo {
22
pub fn record(&mut self, before: String) {
23
if self.undo.last() == Some(&before) {
24
return;
25
}
26
self.undo.push(before);
27
if self.undo.len() > self.limit {
28
self.undo.remove(0);
29
}
30
self.redo.clear();
31
}
32
33
pub fn undo(&mut self, current: &str) -> Option<String> {
34
let prev = self.undo.pop()?;
35
self.redo.push(current.to_string());
36
Some(prev)
37
}
38
39
pub fn redo(&mut self, current: &str) -> Option<String> {
40
let next = self.redo.pop()?;
41
self.undo.push(current.to_string());
42
Some(next)
43
}
44
}
45
46
#[cfg(test)]
47
mod tests {
48
use super::*;
49
50
#[test]
51
fn undo_redo_roundtrip() {
52
let mut stack = TextUndo::default();
53
stack.record("a".into());
54
let u = stack.undo("b").unwrap();
55
assert_eq!(u, "a");
56
let r = stack.redo("a").unwrap();
57
assert_eq!(r, "b");
58
}
59
}