Experimental: TSPL/TSPL2 label printers (auto-detect, label format per model) + experimental CI release
- protocol.rs: detect ESC/POS vs TSPL from IEEE 1284 device ID (CMD:), TSC USB vendor, queue name; ESC/POS default - tspl.rs: render the unchanged ESC/POS output to a bitmap and send TSPL SIZE/GAP/DIRECTION/REFERENCE/CLS/BITMAP/PRINT - label_format.rs: label format per printer model in label_formats.json (config.json unchanged) - print dialog: label section only for TSPL printers (own form, tooltips, NL/EN/DE/FR) - CLI print uses the saved label format for TSPL printers - CI: experimental/tspl2 only builds Linux + Windows and publishes one release experimental-tspl2 (no AUR)
@@ -2852,11 +2852,13 @@ checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3"
2852
2852
name = "posprint"
2853
2853
version = "0.5.7"
2854
2854
dependencies = [
2855
"ab_glyph",
2855
2856
"barcoders",
2856
2857
"base64",
2857
2858
"chrono",
2858
2859
"clap",
2859
2860
"eframe",
2861
"epaint_default_fonts",
2860
2862
"flate2",
2861
2863
"ico",
2862
2864
"image",
@@ -2852,11 +2852,13 @@ checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3"2852
name = "posprint"2852
name = "posprint"2853
version = "0.5.7"2853
version = "0.5.7"2854
dependencies = [2854
dependencies = [2855
"ab_glyph",2855
"barcoders",2856
"barcoders",2856
"base64",2857
"base64",2857
"chrono",2858
"chrono",2858
"clap",2859
"clap",2859
"eframe",2860
"eframe",2861
"epaint_default_fonts",2860
"flate2",2862
"flate2",2861
"ico",2863
"ico",2862
"image",2864
"image",@@ -27,6 +27,8 @@ flate2 = "1"
27
27
base64 = "0.22"
28
28
ureq = { version = "2", default-features = false, features = ["native-tls"] }
29
29
native-tls = "0.2"
30
ab_glyph = "0.2"
31
epaint_default_fonts = "0.31"
30
32
31
33
[dev-dependencies]
32
34
tempfile = "3"
@@ -27,6 +27,8 @@ flate2 = "1"27
base64 = "0.22"
27
base64 = "0.22"
28
ureq = { version = "2", default-features = false, features = ["native-tls"] }
28
ureq = { version = "2", default-features = false, features = ["native-tls"] }
29
native-tls = "0.2"
29
native-tls = "0.2"
30
ab_glyph = "0.2"
31
epaint_default_fonts = "0.31"
30
32
31
[dev-dependencies]
33
[dev-dependencies]
32
tempfile = "3"
34
tempfile = "3"
@@ -31,6 +31,8 @@ workflow:
31
31
when: never
32
32
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
33
33
- if: $CI_COMMIT_BRANCH == "master"
34
# Temporary experimental branch (TSPL2 label printers), see .experimental.
35
- if: $CI_COMMIT_BRANCH == "experimental/tspl2"
34
36
- if: $CI_PIPELINE_SOURCE == "web"
35
37
- if: $CI_PIPELINE_SOURCE == "api"
36
38
@@ -220,3 +222,72 @@ publish:aur:
220
222
- if [ "$(cat artifacts/released.txt)" = "skip" ]; then echo "No new release in this pipeline; AUR unchanged."; exit 0; fi
221
223
- cp dist/x86_64-bin.tar.gz "dist/posprint-$(cat artifacts/version.txt)-x86_64.tar.gz"
222
224
- bash scripts/publish-aur.sh "$(cat artifacts/version.txt)"
225
226
# --- Experimental branch experimental/tspl2 only --------------------------
227
# Windows + Linux test builds published as ONE BlueGit release with the fixed
228
# tag `experimental-tspl2` (replaced on every run, never a version tag).
229
# Never runs on master or merge requests; no AUR, no secrets except the job
230
# token (and the optional EXPERIMENTAL_RELEASE_TOKEN to replace the release).
231
.experimental:
232
rules:
233
- if: $CI_PIPELINE_SOURCE == "merge_request_event"
234
when: never
235
- if: $CI_COMMIT_BRANCH == "experimental/tspl2"
236
237
exp:version:
238
extends: .experimental
239
stage: test
240
image: bluegit/base
241
needs: []
242
script:
243
- bash scripts/ci/experimental-version.sh
244
artifacts:
245
paths: [artifacts/version.txt]
246
expire_in: 14d
247
248
exp:build:linux:
249
extends: [.rust, .experimental]
250
stage: build
251
needs: [exp:version, test]
252
cache:
253
key: cargo-exp-linux
254
paths: [target/, cargo-home/]
255
script:
256
- bash scripts/ci/set-version.sh
257
- cargo build --release --locked
258
- bash scripts/ci/experimental-package-linux.sh
259
artifacts:
260
paths: [dist/posprint-experimental-linux-x86_64.tar.gz]
261
expire_in: 30d
262
263
exp:build:windows:
264
extends: [.rust, .experimental]
265
stage: build
266
needs: [exp:version, test]
267
cache:
268
key: cargo-exp-windows
269
paths: [target/, cargo-home/]
270
before_script:
271
- export CARGO_HOME="$CI_PROJECT_DIR/cargo-home"
272
- export PATH="$CARGO_HOME/bin:$PATH"
273
- apt-get update -qq
274
- apt-get install -y -qq gcc-mingw-w64-x86-64 binutils-mingw-w64-x86-64
275
- rustup target add x86_64-pc-windows-gnu
276
- ln -sf /usr/bin/x86_64-w64-mingw32-windres /usr/local/bin/windres
277
script:
278
- bash scripts/ci/set-version.sh
279
- cargo build --release --locked --target x86_64-pc-windows-gnu
280
- mkdir -p dist
281
- cp target/x86_64-pc-windows-gnu/release/posprint.exe dist/posprint-experimental-windows-x86_64.exe
282
artifacts:
283
paths: [dist/posprint-experimental-windows-x86_64.exe]
284
expire_in: 30d
285
286
exp:release:
287
extends: .experimental
288
stage: release
289
image: bluegit/base
290
needs: [exp:version, exp:build:linux, exp:build:windows]
291
resource_group: experimental-release
292
script:
293
- bash scripts/ci/experimental-release.sh
@@ -31,6 +31,8 @@ workflow:31
when: never31
when: never32
- if: $CI_PIPELINE_SOURCE == "merge_request_event"32
- if: $CI_PIPELINE_SOURCE == "merge_request_event"33
- if: $CI_COMMIT_BRANCH == "master"33
- if: $CI_COMMIT_BRANCH == "master"34
# Temporary experimental branch (TSPL2 label printers), see .experimental.35
- if: $CI_COMMIT_BRANCH == "experimental/tspl2"34
- if: $CI_PIPELINE_SOURCE == "web"36
- if: $CI_PIPELINE_SOURCE == "web"35
- if: $CI_PIPELINE_SOURCE == "api"37
- if: $CI_PIPELINE_SOURCE == "api"36
38
@@ -220,3 +222,72 @@ publish:aur:220
- if [ "$(cat artifacts/released.txt)" = "skip" ]; then echo "No new release in this pipeline; AUR unchanged."; exit 0; fi222
- if [ "$(cat artifacts/released.txt)" = "skip" ]; then echo "No new release in this pipeline; AUR unchanged."; exit 0; fi221
- cp dist/x86_64-bin.tar.gz "dist/posprint-$(cat artifacts/version.txt)-x86_64.tar.gz"223
- cp dist/x86_64-bin.tar.gz "dist/posprint-$(cat artifacts/version.txt)-x86_64.tar.gz"222
- bash scripts/publish-aur.sh "$(cat artifacts/version.txt)"224
- bash scripts/publish-aur.sh "$(cat artifacts/version.txt)"225
226
# --- Experimental branch experimental/tspl2 only --------------------------227
# Windows + Linux test builds published as ONE BlueGit release with the fixed228
# tag `experimental-tspl2` (replaced on every run, never a version tag).229
# Never runs on master or merge requests; no AUR, no secrets except the job230
# token (and the optional EXPERIMENTAL_RELEASE_TOKEN to replace the release).231
.experimental:232
rules:233
- if: $CI_PIPELINE_SOURCE == "merge_request_event"234
when: never235
- if: $CI_COMMIT_BRANCH == "experimental/tspl2"236
237
exp:version:238
extends: .experimental239
stage: test240
image: bluegit/base241
needs: []242
script:243
- bash scripts/ci/experimental-version.sh244
artifacts:245
paths: [artifacts/version.txt]246
expire_in: 14d247
248
exp:build:linux:249
extends: [.rust, .experimental]250
stage: build251
needs: [exp:version, test]252
cache:253
key: cargo-exp-linux254
paths: [target/, cargo-home/]255
script:256
- bash scripts/ci/set-version.sh257
- cargo build --release --locked258
- bash scripts/ci/experimental-package-linux.sh259
artifacts:260
paths: [dist/posprint-experimental-linux-x86_64.tar.gz]261
expire_in: 30d262
263
exp:build:windows:264
extends: [.rust, .experimental]265
stage: build266
needs: [exp:version, test]267
cache:268
key: cargo-exp-windows269
paths: [target/, cargo-home/]270
before_script:271
- export CARGO_HOME="$CI_PROJECT_DIR/cargo-home"272
- export PATH="$CARGO_HOME/bin:$PATH"273
- apt-get update -qq274
- apt-get install -y -qq gcc-mingw-w64-x86-64 binutils-mingw-w64-x86-64275
- rustup target add x86_64-pc-windows-gnu276
- ln -sf /usr/bin/x86_64-w64-mingw32-windres /usr/local/bin/windres277
script:278
- bash scripts/ci/set-version.sh279
- cargo build --release --locked --target x86_64-pc-windows-gnu280
- mkdir -p dist281
- cp target/x86_64-pc-windows-gnu/release/posprint.exe dist/posprint-experimental-windows-x86_64.exe282
artifacts:283
paths: [dist/posprint-experimental-windows-x86_64.exe]284
expire_in: 30d285
286
exp:release:287
extends: .experimental288
stage: release289
image: bluegit/base290
needs: [exp:version, exp:build:linux, exp:build:windows]291
resource_group: experimental-release292
script:293
- bash scripts/ci/experimental-release.sh@@ -0,0 +1,46 @@
1
# Label printers (TSPL/TSPL2) — experimental
2
3
Branch `experimental/tspl2`. Receipt printers (ESC/POS) behave exactly as before;
4
this only adds a second output language for label printers such as the
5
Altec ATP-300 Pro (USB 1203:0231, `MFG:Altec;CMD:TSPL2;MDL:ATP-300 Pro;`).
6
7
## Protocol detection (automatic)
8
9
1. The printer's IEEE 1284 device ID (`CMD:` field): read from Linux sysfs
10
(`ieee1284_id`) or with the USB printer-class `GET_DEVICE_ID` request.
11
`TSPL*` → TSPL. If ESC/POS is also listed, ESC/POS is used.
12
2. No device ID but USB vendor 0x1203 (TSC/Altec) → TSPL.
13
3. Windows queue name containing `TSPL`, `Altec ATP` or `TSC` → TSPL.
14
4. Otherwise ESC/POS (unchanged default).
15
16
## Label format
17
18
The print dialog shows a *Label printer* section only for TSPL printers. The
19
first time a model is used it asks width, height, gap/black mark/continuous,
20
resolution and rotation, pre-filled from the printer when it answers
21
`GETSETTING$("CONFIG","TSPL","PAPER WIDTH" / "PAPER SIZE" / "GAP SIZE")` and
22
`GETSETTING$("SYSTEM","INFORMATION","DPI")` over bidirectional USB (values are
23
only used when the reply has an explicit unit). The format is stored per model
24
in `label_formats.json` next to `config.json`. "Let the printer measure the
25
labels first" sends `GAPDETECT x,y` / `BLINEDETECT x,y` once.
26
27
## Output
28
29
The page is encoded with the unchanged ESC/POS encoder, rendered to a bitmap
30
(Font A 12×24 grid, alignment, double size, bold, raster images, barcodes, QR),
31
scaled to the label resolution (8 → 12 dots/mm at 300 dpi, shrunk to fit the
32
label width), centred, split over labels (`@cut` = next label, long pages over
33
several labels) and sent as:
34
35
```
36
SIZE w mm,h mm
37
GAP g mm,0 mm (BLINE g mm,0 mm / GAP 0,0)
38
DIRECTION 0,0
39
REFERENCE 0,0
40
CLS
41
BITMAP x,0,wbytes,h,0,<1-bit data, 0 = black>
42
PRINT 1,1
43
```
44
45
`cargo run --example tspl_preview -- file.pos out 100 50 3 300` writes PNG
46
previews and the `.prn` job without a printer.
@@ -0,0 +1,46 @@1
# Label printers (TSPL/TSPL2) — experimental2
3
Branch `experimental/tspl2`. Receipt printers (ESC/POS) behave exactly as before;4
this only adds a second output language for label printers such as the5
Altec ATP-300 Pro (USB 1203:0231, `MFG:Altec;CMD:TSPL2;MDL:ATP-300 Pro;`).6
7
## Protocol detection (automatic)8
9
1. The printer's IEEE 1284 device ID (`CMD:` field): read from Linux sysfs10
(`ieee1284_id`) or with the USB printer-class `GET_DEVICE_ID` request.11
`TSPL*` → TSPL. If ESC/POS is also listed, ESC/POS is used.12
2. No device ID but USB vendor 0x1203 (TSC/Altec) → TSPL.13
3. Windows queue name containing `TSPL`, `Altec ATP` or `TSC` → TSPL.14
4. Otherwise ESC/POS (unchanged default).15
16
## Label format17
18
The print dialog shows a *Label printer* section only for TSPL printers. The19
first time a model is used it asks width, height, gap/black mark/continuous,20
resolution and rotation, pre-filled from the printer when it answers21
`GETSETTING$("CONFIG","TSPL","PAPER WIDTH" / "PAPER SIZE" / "GAP SIZE")` and22
`GETSETTING$("SYSTEM","INFORMATION","DPI")` over bidirectional USB (values are23
only used when the reply has an explicit unit). The format is stored per model24
in `label_formats.json` next to `config.json`. "Let the printer measure the25
labels first" sends `GAPDETECT x,y` / `BLINEDETECT x,y` once.26
27
## Output28
29
The page is encoded with the unchanged ESC/POS encoder, rendered to a bitmap30
(Font A 12×24 grid, alignment, double size, bold, raster images, barcodes, QR),31
scaled to the label resolution (8 → 12 dots/mm at 300 dpi, shrunk to fit the32
label width), centred, split over labels (`@cut` = next label, long pages over33
several labels) and sent as:34
35
```36
SIZE w mm,h mm37
GAP g mm,0 mm (BLINE g mm,0 mm / GAP 0,0)38
DIRECTION 0,039
REFERENCE 0,040
CLS41
BITMAP x,0,wbytes,h,0,<1-bit data, 0 = black>42
PRINT 1,143
```44
45
`cargo run --example tspl_preview -- file.pos out 100 50 3 300` writes PNG46
previews and the `.prn` job without a printer.@@ -0,0 +1,42 @@
1
//! Render a .pos file as TSPL labels without a printer.
2
//!
3
//! cargo run --example tspl_preview -- file.pos out-prefix [width_mm height_mm gap_mm dpi]
4
//! Writes out-prefix-N.png (one per label page) and out-prefix.prn (TSPL job).
5
6
use std::collections::HashMap;
7
use std::path::Path;
8
9
use posprint::io::PosFile;
10
use posprint::label_format::LabelFormat;
11
use posprint::pipeline::{encode_pos_file, encode_pos_file_tspl};
12
use posprint::tspl::{page_scale, render_escpos, TsplOptions};
13
14
fn main() {
15
let args: Vec<String> = std::env::args().collect();
16
if args.len() < 3 {
17
eprintln!("usage: tspl_preview file.pos out-prefix [width_mm height_mm gap_mm dpi]");
18
std::process::exit(2);
19
}
20
let path = Path::new(&args[1]);
21
let file = PosFile::load_from_path(path).expect("load");
22
let num = |i: usize, d: f32| args.get(i).and_then(|v| v.parse().ok()).unwrap_or(d);
23
let format = LabelFormat {
24
width_mm: num(3, 100.0),
25
height_mm: num(4, 50.0),
26
gap_mm: num(5, 3.0),
27
dpi: num(6, 300.0) as u16,
28
..Default::default()
29
};
30
let params: HashMap<String, String> = std::env::var("POSPRINT_PARAMS")
31
.ok()
32
.and_then(|p| serde_json::from_str(&std::fs::read_to_string(p).ok()?).ok())
33
.unwrap_or_default();
34
let esc = encode_pos_file(&file, path.parent(), ¶ms).expect("encode");
35
let src_w = file.metadata.printable_dots() as u32;
36
for (i, page) in render_escpos(&esc, src_w, page_scale(src_w, &format)).iter().enumerate() {
37
page.save(format!("{}-{}.png", args[2], i + 1)).expect("png");
38
}
39
let job = encode_pos_file_tspl(&file, path.parent(), ¶ms, &format, TsplOptions::default())
40
.expect("tspl");
41
std::fs::write(format!("{}.prn", args[2]), job).expect("prn");
42
}
@@ -0,0 +1,42 @@1
//! Render a .pos file as TSPL labels without a printer.2
//!3
//! cargo run --example tspl_preview -- file.pos out-prefix [width_mm height_mm gap_mm dpi]4
//! Writes out-prefix-N.png (one per label page) and out-prefix.prn (TSPL job).5
6
use std::collections::HashMap;7
use std::path::Path;8
9
use posprint::io::PosFile;10
use posprint::label_format::LabelFormat;11
use posprint::pipeline::{encode_pos_file, encode_pos_file_tspl};12
use posprint::tspl::{page_scale, render_escpos, TsplOptions};13
14
fn main() {15
let args: Vec<String> = std::env::args().collect();16
if args.len() < 3 {17
eprintln!("usage: tspl_preview file.pos out-prefix [width_mm height_mm gap_mm dpi]");18
std::process::exit(2);19
}20
let path = Path::new(&args[1]);21
let file = PosFile::load_from_path(path).expect("load");22
let num = |i: usize, d: f32| args.get(i).and_then(|v| v.parse().ok()).unwrap_or(d);23
let format = LabelFormat {24
width_mm: num(3, 100.0),25
height_mm: num(4, 50.0),26
gap_mm: num(5, 3.0),27
dpi: num(6, 300.0) as u16,28
..Default::default()29
};30
let params: HashMap<String, String> = std::env::var("POSPRINT_PARAMS")31
.ok()32
.and_then(|p| serde_json::from_str(&std::fs::read_to_string(p).ok()?).ok())33
.unwrap_or_default();34
let esc = encode_pos_file(&file, path.parent(), ¶ms).expect("encode");35
let src_w = file.metadata.printable_dots() as u32;36
for (i, page) in render_escpos(&esc, src_w, page_scale(src_w, &format)).iter().enumerate() {37
page.save(format!("{}-{}.png", args[2], i + 1)).expect("png");38
}39
let job = encode_pos_file_tspl(&file, path.parent(), ¶ms, &format, TsplOptions::default())40
.expect("tspl");41
std::fs::write(format!("{}.prn", args[2]), job).expect("prn");42
}@@ -0,0 +1,23 @@
1
#!/usr/bin/env bash
2
# Pack the experimental Linux binary as one tarball (fixed artifact path).
3
set -euo pipefail
4
cd "$(dirname "$0")/../.."
5
v="$(cat artifacts/version.txt)"
6
bin="target/release/posprint"
7
test -x "$bin"
8
stage="$(mktemp -d)"
9
dir="$stage/posprint-experimental-tspl2"
10
mkdir -p "$dir"
11
cp "$bin" "$dir/posprint"
12
cp pos-logo.png "$dir/posprint.png"
13
cat > "$dir/README-EXPERIMENTAL.txt" <<TXT
14
Posprint ${v} - EXPERIMENTAL (branch experimental/tspl2)
15
16
Test build with TSPL/TSPL2 label-printer support. Not a stable release,
17
not published to AUR. Start with ./posprint
18
TXT
19
mkdir -p dist
20
tar -C "$stage" -czf dist/posprint-experimental-linux-x86_64.tar.gz posprint-experimental-tspl2
21
rm -rf "$stage"
22
test -s dist/posprint-experimental-linux-x86_64.tar.gz
23
tar -tzf dist/posprint-experimental-linux-x86_64.tar.gz
@@ -0,0 +1,23 @@1
#!/usr/bin/env bash2
# Pack the experimental Linux binary as one tarball (fixed artifact path).3
set -euo pipefail4
cd "$(dirname "$0")/../.."5
v="$(cat artifacts/version.txt)"6
bin="target/release/posprint"7
test -x "$bin"8
stage="$(mktemp -d)"9
dir="$stage/posprint-experimental-tspl2"10
mkdir -p "$dir"11
cp "$bin" "$dir/posprint"12
cp pos-logo.png "$dir/posprint.png"13
cat > "$dir/README-EXPERIMENTAL.txt" <<TXT14
Posprint ${v} - EXPERIMENTAL (branch experimental/tspl2)15
16
Test build with TSPL/TSPL2 label-printer support. Not a stable release,17
not published to AUR. Start with ./posprint18
TXT19
mkdir -p dist20
tar -C "$stage" -czf dist/posprint-experimental-linux-x86_64.tar.gz posprint-experimental-tspl221
rm -rf "$stage"22
test -s dist/posprint-experimental-linux-x86_64.tar.gz23
tar -tzf dist/posprint-experimental-linux-x86_64.tar.gz@@ -0,0 +1,51 @@
1
#!/usr/bin/env bash
2
# Publish the single "Experimental" BlueGit release for experimental/tspl2.
3
#
4
# - Only on branch experimental/tspl2; fixed tag experimental-tspl2 (never X.Y.Z).
5
# - There is always at most one such release: an existing one is deleted
6
# (with its tag and assets) before the new one is created.
7
# - Uses CI_JOB_TOKEN to create. BlueGit only lets user tokens delete releases,
8
# so replacing needs EXPERIMENTAL_RELEASE_TOKEN; without it the job fails
9
# when the release already exists (it never creates a second one).
10
# - No AUR, no other secrets.
11
set -euo pipefail
12
: "${CI_API_URL:?}" "${CI_JOB_TOKEN:?}" "${CI_COMMIT_SHA:?}" "${CI_PROJECT_PATH:?}"
13
cd "$(dirname "$0")/../.."
14
TAG="experimental-tspl2"
15
BRANCH="experimental/tspl2"
16
[[ "${CI_COMMIT_BRANCH:-}" == "$BRANCH" ]] || { echo "Refusing: experimental release only from $BRANCH (got '${CI_COMMIT_BRANCH:-}')" >&2; exit 1; }
17
[[ ! "$TAG" =~ ^v?[0-9]+\.[0-9]+\.[0-9]+$ ]] || { echo "Refusing: version-like tag" >&2; exit 1; }
18
v="$(cat artifacts/version.txt)"
19
[[ "$v" == *-tspl2.* ]] || { echo "Refusing: not an experimental version: $v" >&2; exit 1; }
20
for f in dist/posprint-experimental-linux-x86_64.tar.gz dist/posprint-experimental-windows-x86_64.exe; do
21
test -s "$f" || { echo "Missing artifact $f" >&2; exit 1; }
22
done
23
24
remote="${CI_PROJECT_URL:-${CI_API_URL%/api/v1}/$CI_PROJECT_PATH}.git"
25
exists=0
26
if [[ -n "$(git ls-remote --tags "$remote" "refs/tags/$TAG" 2>/dev/null || true)" ]]; then exists=1; fi
27
if [[ -n "$(git ls-remote --tags origin "refs/tags/$TAG" 2>/dev/null || true)" ]]; then exists=1; fi
28
29
if [[ $exists == 1 ]]; then
30
if [[ -z "${EXPERIMENTAL_RELEASE_TOKEN:-}" ]]; then
31
echo "Release $TAG already exists and EXPERIMENTAL_RELEASE_TOKEN is not set; not creating a second release." >&2
32
exit 1
33
fi
34
echo "Replacing existing release $TAG"
35
code="$(curl -sS -o /dev/null -w '%{http_code}' -X DELETE \
36
"$CI_API_URL/projects/$CI_PROJECT_PATH/releases/$TAG?delete_tag=true" \
37
-H "Authorization: Bearer $EXPERIMENTAL_RELEASE_TOKEN")" || code=000
38
[[ "$code" == 2* || "$code" == 404 ]] || { echo "Delete returned HTTP $code" >&2; exit 1; }
39
fi
40
41
asset() { printf '{"job":"%s","path":"%s","name":"%s"}' "$1" "$2" "$3"; }
42
assets="$(asset exp:build:linux dist/posprint-experimental-linux-x86_64.tar.gz posprint-experimental-linux-x86_64.tar.gz),$(asset exp:build:windows dist/posprint-experimental-windows-x86_64.exe posprint-experimental-windows-x86_64.exe)"
43
short="${CI_COMMIT_SHA:0:8}"
44
desc="EXPERIMENTAL / PRERELEASE - niet stabiel, niet in AUR.\n\nVersie ${v} van branch ${BRANCH} (commit ${short}).\nTSPL/TSPL2-labelprinters (getest op opmaak, nog niet fysiek): protocol wordt automatisch herkend; labelformaat per printermodel.\n\n* Linux x86_64: posprint-experimental-linux-x86_64.tar.gz\n* Windows x86_64: posprint-experimental-windows-x86_64.exe\n\nDeze release wordt bij elke pipeline op ${BRANCH} vervangen."
45
body="$(printf '{"tag":"%s","commit":"%s","name":"%s","body":"%s","assets":[%s]}' "$TAG" "$CI_COMMIT_SHA" "Experimental: TSPL2 labelprinters (${v})" "$desc" "$assets")"
46
echo "Experimental release $TAG ($v) on $CI_COMMIT_SHA"
47
resp="$(mktemp)"
48
code="$(curl -sS -o "$resp" -w '%{http_code}' -X POST "$CI_API_URL/repos/$CI_PROJECT_PATH/releases" \
49
-H "Authorization: Bearer $CI_JOB_TOKEN" -H "Content-Type: application/json" -d "$body")" || code=000
50
cat "$resp"; echo
51
[[ "$code" == 2* ]] || { echo "Release API returned HTTP $code" >&2; exit 1; }
@@ -0,0 +1,51 @@1
#!/usr/bin/env bash2
# Publish the single "Experimental" BlueGit release for experimental/tspl2.3
#4
# - Only on branch experimental/tspl2; fixed tag experimental-tspl2 (never X.Y.Z).5
# - There is always at most one such release: an existing one is deleted6
# (with its tag and assets) before the new one is created.7
# - Uses CI_JOB_TOKEN to create. BlueGit only lets user tokens delete releases,8
# so replacing needs EXPERIMENTAL_RELEASE_TOKEN; without it the job fails9
# when the release already exists (it never creates a second one).10
# - No AUR, no other secrets.11
set -euo pipefail12
: "${CI_API_URL:?}" "${CI_JOB_TOKEN:?}" "${CI_COMMIT_SHA:?}" "${CI_PROJECT_PATH:?}"13
cd "$(dirname "$0")/../.."14
TAG="experimental-tspl2"15
BRANCH="experimental/tspl2"16
[[ "${CI_COMMIT_BRANCH:-}" == "$BRANCH" ]] || { echo "Refusing: experimental release only from $BRANCH (got '${CI_COMMIT_BRANCH:-}')" >&2; exit 1; }17
[[ ! "$TAG" =~ ^v?[0-9]+\.[0-9]+\.[0-9]+$ ]] || { echo "Refusing: version-like tag" >&2; exit 1; }18
v="$(cat artifacts/version.txt)"19
[[ "$v" == *-tspl2.* ]] || { echo "Refusing: not an experimental version: $v" >&2; exit 1; }20
for f in dist/posprint-experimental-linux-x86_64.tar.gz dist/posprint-experimental-windows-x86_64.exe; do21
test -s "$f" || { echo "Missing artifact $f" >&2; exit 1; }22
done23
24
remote="${CI_PROJECT_URL:-${CI_API_URL%/api/v1}/$CI_PROJECT_PATH}.git"25
exists=026
if [[ -n "$(git ls-remote --tags "$remote" "refs/tags/$TAG" 2>/dev/null || true)" ]]; then exists=1; fi27
if [[ -n "$(git ls-remote --tags origin "refs/tags/$TAG" 2>/dev/null || true)" ]]; then exists=1; fi28
29
if [[ $exists == 1 ]]; then30
if [[ -z "${EXPERIMENTAL_RELEASE_TOKEN:-}" ]]; then31
echo "Release $TAG already exists and EXPERIMENTAL_RELEASE_TOKEN is not set; not creating a second release." >&232
exit 133
fi34
echo "Replacing existing release $TAG"35
code="$(curl -sS -o /dev/null -w '%{http_code}' -X DELETE \36
"$CI_API_URL/projects/$CI_PROJECT_PATH/releases/$TAG?delete_tag=true" \37
-H "Authorization: Bearer $EXPERIMENTAL_RELEASE_TOKEN")" || code=00038
[[ "$code" == 2* || "$code" == 404 ]] || { echo "Delete returned HTTP $code" >&2; exit 1; }39
fi40
41
asset() { printf '{"job":"%s","path":"%s","name":"%s"}' "$1" "$2" "$3"; }42
assets="$(asset exp:build:linux dist/posprint-experimental-linux-x86_64.tar.gz posprint-experimental-linux-x86_64.tar.gz),$(asset exp:build:windows dist/posprint-experimental-windows-x86_64.exe posprint-experimental-windows-x86_64.exe)"43
short="${CI_COMMIT_SHA:0:8}"44
desc="EXPERIMENTAL / PRERELEASE - niet stabiel, niet in AUR.\n\nVersie ${v} van branch ${BRANCH} (commit ${short}).\nTSPL/TSPL2-labelprinters (getest op opmaak, nog niet fysiek): protocol wordt automatisch herkend; labelformaat per printermodel.\n\n* Linux x86_64: posprint-experimental-linux-x86_64.tar.gz\n* Windows x86_64: posprint-experimental-windows-x86_64.exe\n\nDeze release wordt bij elke pipeline op ${BRANCH} vervangen."45
body="$(printf '{"tag":"%s","commit":"%s","name":"%s","body":"%s","assets":[%s]}' "$TAG" "$CI_COMMIT_SHA" "Experimental: TSPL2 labelprinters (${v})" "$desc" "$assets")"46
echo "Experimental release $TAG ($v) on $CI_COMMIT_SHA"47
resp="$(mktemp)"48
code="$(curl -sS -o "$resp" -w '%{http_code}' -X POST "$CI_API_URL/repos/$CI_PROJECT_PATH/releases" \49
-H "Authorization: Bearer $CI_JOB_TOKEN" -H "Content-Type: application/json" -d "$body")" || code=00050
cat "$resp"; echo51
[[ "$code" == 2* ]] || { echo "Release API returned HTTP $code" >&2; exit 1; }@@ -0,0 +1,11 @@
1
#!/usr/bin/env bash
2
# Version for experimental/tspl2 builds: <Cargo.toml version>-tspl2.<pipeline id>.
3
# Never a bare X.Y.Z, so it can never collide with a stable release or AUR.
4
set -euo pipefail
5
cd "$(dirname "$0")/../.."
6
base="$(grep -m1 '^version = ' Cargo.toml | sed -E 's/.*"([^"]+)"/\1/')"
7
base="${base%%-*}"
8
mkdir -p artifacts
9
v="${base}-tspl2.${CI_PIPELINE_ID:-0}"
10
[[ "$v" =~ ^[0-9]+\.[0-9]+\.[0-9]+-tspl2\.[0-9]+$ ]] || { echo "Invalid experimental version: $v" >&2; exit 1; }
11
echo "$v" | tee artifacts/version.txt
@@ -0,0 +1,11 @@1
#!/usr/bin/env bash2
# Version for experimental/tspl2 builds: <Cargo.toml version>-tspl2.<pipeline id>.3
# Never a bare X.Y.Z, so it can never collide with a stable release or AUR.4
set -euo pipefail5
cd "$(dirname "$0")/../.."6
base="$(grep -m1 '^version = ' Cargo.toml | sed -E 's/.*"([^"]+)"/\1/')"7
base="${base%%-*}"8
mkdir -p artifacts9
v="${base}-tspl2.${CI_PIPELINE_ID:-0}"10
[[ "$v" =~ ^[0-9]+\.[0-9]+\.[0-9]+-tspl2\.[0-9]+$ ]] || { echo "Invalid experimental version: $v" >&2; exit 1; }11
echo "$v" | tee artifacts/version.txt@@ -0,0 +1,313 @@
1
//! Translations for UI texts added with label-printer (TSPL) support.
2
//! Languages: English, Dutch, German, French (from the OS locale).
3
4
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
5
pub enum Lang {
6
En,
7
Nl,
8
De,
9
Fr,
10
}
11
12
impl Lang {
13
pub fn from_locale(locale: &str) -> Self {
14
let l = locale.trim().to_ascii_lowercase();
15
if l.starts_with("nl") {
16
Self::Nl
17
} else if l.starts_with("de") {
18
Self::De
19
} else if l.starts_with("fr") {
20
Self::Fr
21
} else {
22
Self::En
23
}
24
}
25
26
/// Current UI language (`POSPRINT_LANG`, then the OS locale).
27
pub fn current() -> Self {
28
if let Ok(v) = std::env::var("POSPRINT_LANG") {
29
if !v.trim().is_empty() {
30
return Self::from_locale(&v);
31
}
32
}
33
for var in ["LC_ALL", "LC_MESSAGES", "LANG", "LANGUAGE"] {
34
if let Ok(v) = std::env::var(var) {
35
if !v.trim().is_empty() && v != "C" && v != "POSIX" {
36
return Self::from_locale(&v);
37
}
38
}
39
}
40
#[cfg(windows)]
41
if let Some(l) = windows_locale() {
42
return Self::from_locale(&l);
43
}
44
Self::En
45
}
46
}
47
48
#[cfg(windows)]
49
fn windows_locale() -> Option<String> {
50
#[link(name = "kernel32")]
51
extern "system" {
52
fn GetUserDefaultLocaleName(name: *mut u16, len: i32) -> i32;
53
}
54
let mut buf = [0u16; 85];
55
// SAFETY: buffer length passed matches the buffer.
56
let n = unsafe { GetUserDefaultLocaleName(buf.as_mut_ptr(), buf.len() as i32) };
57
if n <= 1 {
58
return None;
59
}
60
Some(String::from_utf16_lossy(&buf[..(n as usize - 1)]))
61
}
62
63
/// All keys with [en, nl, de, fr].
64
pub const TEXTS: &[(&str, [&str; 4])] = &[
65
("label.title", ["Label printer", "Labelprinter", "Etikettendrucker", "Imprimante d'étiquettes"]),
66
("label.detected", [
67
"Detected protocol: {}",
68
"Herkend protocol: {}",
69
"Erkanntes Protokoll: {}",
70
"Protocole détecté : {}",
71
]),
72
("label.source.device_id", [
73
"Read from the printer's own identification (IEEE 1284 device ID).",
74
"Uitgelezen uit de eigen identificatie van de printer (IEEE 1284-apparaat-ID).",
75
"Aus der Kennung des Druckers gelesen (IEEE-1284-Geräte-ID).",
76
"Lu depuis l'identification de l'imprimante (ID de périphérique IEEE 1284).",
77
]),
78
("label.source.usb_vendor", [
79
"Recognised from the USB vendor (TSC/Altec label printers).",
80
"Herkend aan de USB-fabrikant (TSC/Altec-labelprinters).",
81
"Am USB-Hersteller erkannt (TSC/Altec-Etikettendrucker).",
82
"Reconnu par le fabricant USB (imprimantes d'étiquettes TSC/Altec).",
83
]),
84
("label.source.queue_name", [
85
"Recognised from the printer queue name.",
86
"Herkend aan de naam van de printerwachtrij.",
87
"Am Namen der Druckerwarteschlange erkannt.",
88
"Reconnu par le nom de la file d'impression.",
89
]),
90
("label.format", ["Label format", "Labelformaat", "Etikettenformat", "Format d'étiquette"]),
91
("label.format_missing", [
92
"Enter the label format for this printer. It is saved for this model, so next time it is filled in automatically.",
93
"Vul het labelformaat voor deze printer in. Het wordt per model bewaard, zodat het de volgende keer meteen goed staat.",
94
"Geben Sie das Etikettenformat für diesen Drucker ein. Es wird pro Modell gespeichert und beim nächsten Mal automatisch verwendet.",
95
"Saisissez le format d'étiquette pour cette imprimante. Il est enregistré par modèle et sera rempli automatiquement la prochaine fois.",
96
]),
97
("label.from_printer", [
98
"Values read from the printer have been filled in; please check them.",
99
"Waarden die uit de printer zijn gelezen zijn ingevuld; controleer ze even.",
100
"Aus dem Drucker gelesene Werte wurden eingetragen; bitte prüfen.",
101
"Les valeurs lues dans l'imprimante ont été saisies ; veuillez les vérifier.",
102
]),
103
("label.width", ["Width (mm)", "Breedte (mm)", "Breite (mm)", "Largeur (mm)"]),
104
("label.width.tip", [
105
"Width of one label, without the backing paper.",
106
"Breedte van één label, zonder het dragerpapier.",
107
"Breite eines Etiketts, ohne Trägerpapier.",
108
"Largeur d'une étiquette, sans le support.",
109
]),
110
("label.height", ["Height (mm)", "Hoogte (mm)", "Höhe (mm)", "Hauteur (mm)"]),
111
("label.height.tip", [
112
"Length of one label in the feed direction, without the gap. Longer pages are spread over several labels.",
113
"Lengte van één label in de doorvoerrichting, zonder de tussenruimte. Langere pagina's worden over meerdere labels verdeeld.",
114
"Länge eines Etiketts in Vorschubrichtung, ohne Lücke. Längere Seiten werden auf mehrere Etiketten verteilt.",
115
"Longueur d'une étiquette dans le sens d'avance, sans l'espace. Les pages plus longues sont réparties sur plusieurs étiquettes.",
116
]),
117
("label.gap", ["Gap / mark (mm)", "Tussenruimte / markering (mm)", "Lücke / Marke (mm)", "Espace / repère (mm)"]),
118
("label.gap.tip", [
119
"Space between two labels, or the height of the black mark. Usually 2–3 mm.",
120
"Ruimte tussen twee labels, of de hoogte van de zwarte markering. Meestal 2–3 mm.",
121
"Abstand zwischen zwei Etiketten oder Höhe der schwarzen Marke. Meist 2–3 mm.",
122
"Espace entre deux étiquettes, ou hauteur du repère noir. Généralement 2–3 mm.",
123
]),
124
("label.media", ["Media", "Materiaal", "Material", "Support"]),
125
("label.media.tip", [
126
"How the printer finds the start of each label (same as the sensor setting on the printer).",
127
"Hoe de printer het begin van elk label vindt (gelijk aan de sensorinstelling op de printer).",
128
"Wie der Drucker den Anfang jedes Etiketts findet (wie die Sensoreinstellung am Drucker).",
129
"Comment l'imprimante trouve le début de chaque étiquette (comme le réglage du capteur).",
130
]),
131
("label.media.gap", ["Labels with gap", "Labels met tussenruimte", "Etiketten mit Lücke", "Étiquettes avec espace"]),
132
("label.media.black_mark", ["Black mark", "Zwarte markering", "Schwarze Marke", "Repère noir"]),
133
("label.media.continuous", ["Continuous", "Doorlopend", "Endlos", "Continu"]),
134
("label.dpi", ["Resolution (dpi)", "Resolutie (dpi)", "Auflösung (dpi)", "Résolution (ppp)"]),
135
("label.dpi.tip", [
136
"Print-head resolution. The ATP-300 Pro has 300 dpi.",
137
"Resolutie van de printkop. De ATP-300 Pro heeft 300 dpi.",
138
"Auflösung des Druckkopfs. Der ATP-300 Pro hat 300 dpi.",
139
"Résolution de la tête d'impression. L'ATP-300 Pro a 300 ppp.",
140
]),
141
("label.rotate", ["Rotate 180°", "180° draaien", "Um 180° drehen", "Pivoter de 180°"]),
142
("label.rotate.tip", [
143
"Prints upside down (TSPL DIRECTION 1), if labels come out the wrong way round.",
144
"Drukt ondersteboven af (TSPL DIRECTION 1), als de labels verkeerd om uit de printer komen.",
145
"Druckt kopfüber (TSPL DIRECTION 1), falls die Etiketten falsch herum herauskommen.",
146
"Imprime à l'envers (TSPL DIRECTION 1) si les étiquettes sortent dans le mauvais sens.",
147
]),
148
("label.calibrate", [
149
"Let the printer measure the labels first",
150
"Laat de printer eerst de labels meten",
151
"Drucker zuerst die Etiketten messen lassen",
152
"Laisser l'imprimante mesurer d'abord les étiquettes",
153
]),
154
("label.calibrate.tip", [
155
"Sends GAPDETECT/BLINEDETECT before printing: the printer feeds a few labels to calibrate its sensor. Useful for new media or after 'Please calibrate printer'.",
156
"Stuurt GAPDETECT/BLINEDETECT vóór het afdrukken: de printer voert een paar labels door om zijn sensor te kalibreren. Handig bij nieuw materiaal of na 'Please calibrate printer'.",
157
"Sendet vor dem Druck GAPDETECT/BLINEDETECT: Der Drucker zieht einige Etiketten ein, um seinen Sensor zu kalibrieren. Nützlich bei neuem Material oder nach 'Please calibrate printer'.",
158
"Envoie GAPDETECT/BLINEDETECT avant l'impression : l'imprimante fait avancer quelques étiquettes pour calibrer son capteur. Utile pour un nouveau support ou après « Please calibrate printer ».",
159
]),
160
("label.save_print", ["Save and print", "Opslaan en afdrukken", "Speichern und drucken", "Enregistrer et imprimer"]),
161
("label.save_print.tip", [
162
"Saves this label format for this printer model and prints.",
163
"Bewaart dit labelformaat voor dit printermodel en drukt af.",
164
"Speichert dieses Etikettenformat für dieses Druckermodell und druckt.",
165
"Enregistre ce format pour ce modèle d'imprimante et imprime.",
166
]),
167
("label.change", ["Change label format", "Labelformaat wijzigen", "Etikettenformat ändern", "Modifier le format"]),
168
("label.change.tip", [
169
"Change the saved label format for this printer model.",
170
"Wijzig het bewaarde labelformaat voor dit printermodel.",
171
"Gespeichertes Etikettenformat für dieses Modell ändern.",
172
"Modifier le format enregistré pour ce modèle d'imprimante.",
173
]),
174
("label.cancel", ["Cancel", "Annuleren", "Abbrechen", "Annuler"]),
175
("label.cancel.tip", [
176
"Close the label format without saving.",
177
"Sluit het labelformaat zonder op te slaan.",
178
"Etikettenformat ohne Speichern schließen.",
179
"Fermer le format sans enregistrer.",
180
]),
181
("label.err.width", [
182
"Width must be between 10 and 120 mm.",
183
"De breedte moet tussen 10 en 120 mm liggen.",
184
"Die Breite muss zwischen 10 und 120 mm liegen.",
185
"La largeur doit être comprise entre 10 et 120 mm.",
186
]),
187
("label.err.height", [
188
"Height must be between 5 and 1000 mm.",
189
"De hoogte moet tussen 5 en 1000 mm liggen.",
190
"Die Höhe muss zwischen 5 und 1000 mm liegen.",
191
"La hauteur doit être comprise entre 5 et 1000 mm.",
192
]),
193
("label.err.gap", [
194
"Gap must be between 0 and 25.4 mm.",
195
"De tussenruimte moet tussen 0 en 25,4 mm liggen.",
196
"Die Lücke muss zwischen 0 und 25,4 mm liegen.",
197
"L'espace doit être compris entre 0 et 25,4 mm.",
198
]),
199
("label.err.dpi", [
200
"Resolution must be 203, 300 or 600 dpi.",
201
"De resolutie moet 203, 300 of 600 dpi zijn.",
202
"Die Auflösung muss 203, 300 oder 600 dpi sein.",
203
"La résolution doit être de 203, 300 ou 600 ppp.",
204
]),
205
("label.err.number", [
206
"Enter a number for {}.",
207
"Vul een getal in bij {}.",
208
"Geben Sie eine Zahl für {} ein.",
209
"Saisissez un nombre pour {}.",
210
]),
211
("label.err.save", [
212
"The label format could not be saved: {}",
213
"Het labelformaat kon niet worden opgeslagen: {}",
214
"Das Etikettenformat konnte nicht gespeichert werden: {}",
215
"Le format d'étiquette n'a pas pu être enregistré : {}",
216
]),
217
("label.err.missing_cli", [
218
"No label format saved for label printer '{}'. Print once from the Posprint window to set it.",
219
"Geen labelformaat bewaard voor labelprinter '{}'. Druk één keer af vanuit het Posprint-venster om het in te stellen.",
220
"Kein Etikettenformat für Etikettendrucker '{}' gespeichert. Drucken Sie einmal aus dem Posprint-Fenster, um es festzulegen.",
221
"Aucun format enregistré pour l'imprimante d'étiquettes « {} ». Imprimez une fois depuis la fenêtre Posprint pour le définir.",
222
]),
223
("label.status.head_open", [
224
"The printer reports: cover/print head open.",
225
"De printer meldt: klep/printkop open.",
226
"Der Drucker meldet: Abdeckung/Druckkopf offen.",
227
"L'imprimante signale : capot/tête ouverte.",
228
]),
229
("label.status.paper_jam", [
230
"The printer reports: paper jam.",
231
"De printer meldt: papierstoring.",
232
"Der Drucker meldet: Papierstau.",
233
"L'imprimante signale : bourrage papier.",
234
]),
235
("label.status.out_of_paper", [
236
"The printer reports: out of labels (or not calibrated).",
237
"De printer meldt: labels op (of niet gekalibreerd).",
238
"Der Drucker meldet: keine Etiketten (oder nicht kalibriert).",
239
"L'imprimante signale : plus d'étiquettes (ou non calibrée).",
240
]),
241
("label.status.out_of_ribbon", [
242
"The printer reports: out of ribbon.",
243
"De printer meldt: lint op.",
244
"Der Drucker meldet: Farbband leer.",
245
"L'imprimante signale : ruban épuisé.",
246
]),
247
("label.status.paused", [
248
"The printer is paused.",
249
"De printer staat op pauze.",
250
"Der Drucker ist angehalten.",
251
"L'imprimante est en pause.",
252
]),
253
("label.status.other", [
254
"The printer reports an error.",
255
"De printer meldt een fout.",
256
"Der Drucker meldet einen Fehler.",
257
"L'imprimante signale une erreur.",
258
]),
259
];
260
261
pub fn tr_in(lang: Lang, key: &str) -> &'static str {
262
let idx = match lang {
263
Lang::En => 0,
264
Lang::Nl => 1,
265
Lang::De => 2,
266
Lang::Fr => 3,
267
};
268
TEXTS
269
.iter()
270
.find(|(k, _)| *k == key)
271
.map(|(_, v)| v[idx])
272
.unwrap_or("?")
273
}
274
275
pub fn tr(key: &str) -> &'static str {
276
tr_in(Lang::current(), key)
277
}
278
279
/// `tr` with the single `{}` placeholder filled.
280
pub fn trf(key: &str, arg: &str) -> String {
281
tr(key).replacen("{}", arg, 1)
282
}
283
284
#[cfg(test)]
285
mod tests {
286
use super::*;
287
288
#[test]
289
fn every_key_has_four_languages() {
290
let mut seen = std::collections::HashSet::new();
291
for (k, v) in TEXTS {
292
assert!(seen.insert(*k), "duplicate key {k}");
293
for (i, t) in v.iter().enumerate() {
294
assert!(!t.trim().is_empty(), "{k}[{i}] empty");
295
}
296
let n = v[0].matches("{}").count();
297
assert!(v.iter().all(|t| t.matches("{}").count() == n), "{k} placeholder mismatch");
298
// Not just copied English.
299
assert!(v[1] != v[0] || v[0].len() < 12, "{k} nl untranslated");
300
}
301
}
302
303
#[test]
304
fn locale_mapping() {
305
assert_eq!(Lang::from_locale("nl_NL.UTF-8"), Lang::Nl);
306
assert_eq!(Lang::from_locale("de-DE"), Lang::De);
307
assert_eq!(Lang::from_locale("fr_BE"), Lang::Fr);
308
assert_eq!(Lang::from_locale("en_GB"), Lang::En);
309
assert_eq!(Lang::from_locale("ja"), Lang::En);
310
assert_eq!(tr_in(Lang::Nl, "label.width"), "Breedte (mm)");
311
assert_eq!(tr_in(Lang::En, "nope"), "?");
312
}
313
}
@@ -0,0 +1,313 @@1
//! Translations for UI texts added with label-printer (TSPL) support.2
//! Languages: English, Dutch, German, French (from the OS locale).3
4
#[derive(Debug, Clone, Copy, PartialEq, Eq)]5
pub enum Lang {6
En,7
Nl,8
De,9
Fr,10
}11
12
impl Lang {13
pub fn from_locale(locale: &str) -> Self {14
let l = locale.trim().to_ascii_lowercase();15
if l.starts_with("nl") {16
Self::Nl17
} else if l.starts_with("de") {18
Self::De19
} else if l.starts_with("fr") {20
Self::Fr21
} else {22
Self::En23
}24
}25
26
/// Current UI language (`POSPRINT_LANG`, then the OS locale).27
pub fn current() -> Self {28
if let Ok(v) = std::env::var("POSPRINT_LANG") {29
if !v.trim().is_empty() {30
return Self::from_locale(&v);31
}32
}33
for var in ["LC_ALL", "LC_MESSAGES", "LANG", "LANGUAGE"] {34
if let Ok(v) = std::env::var(var) {35
if !v.trim().is_empty() && v != "C" && v != "POSIX" {36
return Self::from_locale(&v);37
}38
}39
}40
#[cfg(windows)]41
if let Some(l) = windows_locale() {42
return Self::from_locale(&l);43
}44
Self::En45
}46
}47
48
#[cfg(windows)]49
fn windows_locale() -> Option<String> {50
#[link(name = "kernel32")]51
extern "system" {52
fn GetUserDefaultLocaleName(name: *mut u16, len: i32) -> i32;53
}54
let mut buf = [0u16; 85];55
// SAFETY: buffer length passed matches the buffer.56
let n = unsafe { GetUserDefaultLocaleName(buf.as_mut_ptr(), buf.len() as i32) };57
if n <= 1 {58
return None;59
}60
Some(String::from_utf16_lossy(&buf[..(n as usize - 1)]))61
}62
63
/// All keys with [en, nl, de, fr].64
pub const TEXTS: &[(&str, [&str; 4])] = &[65
("label.title", ["Label printer", "Labelprinter", "Etikettendrucker", "Imprimante d'étiquettes"]),66
("label.detected", [67
"Detected protocol: {}",68
"Herkend protocol: {}",69
"Erkanntes Protokoll: {}",70
"Protocole détecté : {}",71
]),72
("label.source.device_id", [73
"Read from the printer's own identification (IEEE 1284 device ID).",74
"Uitgelezen uit de eigen identificatie van de printer (IEEE 1284-apparaat-ID).",75
"Aus der Kennung des Druckers gelesen (IEEE-1284-Geräte-ID).",76
"Lu depuis l'identification de l'imprimante (ID de périphérique IEEE 1284).",77
]),78
("label.source.usb_vendor", [79
"Recognised from the USB vendor (TSC/Altec label printers).",80
"Herkend aan de USB-fabrikant (TSC/Altec-labelprinters).",81
"Am USB-Hersteller erkannt (TSC/Altec-Etikettendrucker).",82
"Reconnu par le fabricant USB (imprimantes d'étiquettes TSC/Altec).",83
]),84
("label.source.queue_name", [85
"Recognised from the printer queue name.",86
"Herkend aan de naam van de printerwachtrij.",87
"Am Namen der Druckerwarteschlange erkannt.",88
"Reconnu par le nom de la file d'impression.",89
]),90
("label.format", ["Label format", "Labelformaat", "Etikettenformat", "Format d'étiquette"]),91
("label.format_missing", [92
"Enter the label format for this printer. It is saved for this model, so next time it is filled in automatically.",93
"Vul het labelformaat voor deze printer in. Het wordt per model bewaard, zodat het de volgende keer meteen goed staat.",94
"Geben Sie das Etikettenformat für diesen Drucker ein. Es wird pro Modell gespeichert und beim nächsten Mal automatisch verwendet.",95
"Saisissez le format d'étiquette pour cette imprimante. Il est enregistré par modèle et sera rempli automatiquement la prochaine fois.",96
]),97
("label.from_printer", [98
"Values read from the printer have been filled in; please check them.",99
"Waarden die uit de printer zijn gelezen zijn ingevuld; controleer ze even.",100
"Aus dem Drucker gelesene Werte wurden eingetragen; bitte prüfen.",101
"Les valeurs lues dans l'imprimante ont été saisies ; veuillez les vérifier.",102
]),103
("label.width", ["Width (mm)", "Breedte (mm)", "Breite (mm)", "Largeur (mm)"]),104
("label.width.tip", [105
"Width of one label, without the backing paper.",106
"Breedte van één label, zonder het dragerpapier.",107
"Breite eines Etiketts, ohne Trägerpapier.",108
"Largeur d'une étiquette, sans le support.",109
]),110
("label.height", ["Height (mm)", "Hoogte (mm)", "Höhe (mm)", "Hauteur (mm)"]),111
("label.height.tip", [112
"Length of one label in the feed direction, without the gap. Longer pages are spread over several labels.",113
"Lengte van één label in de doorvoerrichting, zonder de tussenruimte. Langere pagina's worden over meerdere labels verdeeld.",114
"Länge eines Etiketts in Vorschubrichtung, ohne Lücke. Längere Seiten werden auf mehrere Etiketten verteilt.",115
"Longueur d'une étiquette dans le sens d'avance, sans l'espace. Les pages plus longues sont réparties sur plusieurs étiquettes.",116
]),117
("label.gap", ["Gap / mark (mm)", "Tussenruimte / markering (mm)", "Lücke / Marke (mm)", "Espace / repère (mm)"]),118
("label.gap.tip", [119
"Space between two labels, or the height of the black mark. Usually 2–3 mm.",120
"Ruimte tussen twee labels, of de hoogte van de zwarte markering. Meestal 2–3 mm.",121
"Abstand zwischen zwei Etiketten oder Höhe der schwarzen Marke. Meist 2–3 mm.",122
"Espace entre deux étiquettes, ou hauteur du repère noir. Généralement 2–3 mm.",123
]),124
("label.media", ["Media", "Materiaal", "Material", "Support"]),125
("label.media.tip", [126
"How the printer finds the start of each label (same as the sensor setting on the printer).",127
"Hoe de printer het begin van elk label vindt (gelijk aan de sensorinstelling op de printer).",128
"Wie der Drucker den Anfang jedes Etiketts findet (wie die Sensoreinstellung am Drucker).",129
"Comment l'imprimante trouve le début de chaque étiquette (comme le réglage du capteur).",130
]),131
("label.media.gap", ["Labels with gap", "Labels met tussenruimte", "Etiketten mit Lücke", "Étiquettes avec espace"]),132
("label.media.black_mark", ["Black mark", "Zwarte markering", "Schwarze Marke", "Repère noir"]),133
("label.media.continuous", ["Continuous", "Doorlopend", "Endlos", "Continu"]),134
("label.dpi", ["Resolution (dpi)", "Resolutie (dpi)", "Auflösung (dpi)", "Résolution (ppp)"]),135
("label.dpi.tip", [136
"Print-head resolution. The ATP-300 Pro has 300 dpi.",137
"Resolutie van de printkop. De ATP-300 Pro heeft 300 dpi.",138
"Auflösung des Druckkopfs. Der ATP-300 Pro hat 300 dpi.",139
"Résolution de la tête d'impression. L'ATP-300 Pro a 300 ppp.",140
]),141
("label.rotate", ["Rotate 180°", "180° draaien", "Um 180° drehen", "Pivoter de 180°"]),142
("label.rotate.tip", [143
"Prints upside down (TSPL DIRECTION 1), if labels come out the wrong way round.",144
"Drukt ondersteboven af (TSPL DIRECTION 1), als de labels verkeerd om uit de printer komen.",145
"Druckt kopfüber (TSPL DIRECTION 1), falls die Etiketten falsch herum herauskommen.",146
"Imprime à l'envers (TSPL DIRECTION 1) si les étiquettes sortent dans le mauvais sens.",147
]),148
("label.calibrate", [149
"Let the printer measure the labels first",150
"Laat de printer eerst de labels meten",151
"Drucker zuerst die Etiketten messen lassen",152
"Laisser l'imprimante mesurer d'abord les étiquettes",153
]),154
("label.calibrate.tip", [155
"Sends GAPDETECT/BLINEDETECT before printing: the printer feeds a few labels to calibrate its sensor. Useful for new media or after 'Please calibrate printer'.",156
"Stuurt GAPDETECT/BLINEDETECT vóór het afdrukken: de printer voert een paar labels door om zijn sensor te kalibreren. Handig bij nieuw materiaal of na 'Please calibrate printer'.",157
"Sendet vor dem Druck GAPDETECT/BLINEDETECT: Der Drucker zieht einige Etiketten ein, um seinen Sensor zu kalibrieren. Nützlich bei neuem Material oder nach 'Please calibrate printer'.",158
"Envoie GAPDETECT/BLINEDETECT avant l'impression : l'imprimante fait avancer quelques étiquettes pour calibrer son capteur. Utile pour un nouveau support ou après « Please calibrate printer ».",159
]),160
("label.save_print", ["Save and print", "Opslaan en afdrukken", "Speichern und drucken", "Enregistrer et imprimer"]),161
("label.save_print.tip", [162
"Saves this label format for this printer model and prints.",163
"Bewaart dit labelformaat voor dit printermodel en drukt af.",164
"Speichert dieses Etikettenformat für dieses Druckermodell und druckt.",165
"Enregistre ce format pour ce modèle d'imprimante et imprime.",166
]),167
("label.change", ["Change label format", "Labelformaat wijzigen", "Etikettenformat ändern", "Modifier le format"]),168
("label.change.tip", [169
"Change the saved label format for this printer model.",170
"Wijzig het bewaarde labelformaat voor dit printermodel.",171
"Gespeichertes Etikettenformat für dieses Modell ändern.",172
"Modifier le format enregistré pour ce modèle d'imprimante.",173
]),174
("label.cancel", ["Cancel", "Annuleren", "Abbrechen", "Annuler"]),175
("label.cancel.tip", [176
"Close the label format without saving.",177
"Sluit het labelformaat zonder op te slaan.",178
"Etikettenformat ohne Speichern schließen.",179
"Fermer le format sans enregistrer.",180
]),181
("label.err.width", [182
"Width must be between 10 and 120 mm.",183
"De breedte moet tussen 10 en 120 mm liggen.",184
"Die Breite muss zwischen 10 und 120 mm liegen.",185
"La largeur doit être comprise entre 10 et 120 mm.",186
]),187
("label.err.height", [188
"Height must be between 5 and 1000 mm.",189
"De hoogte moet tussen 5 en 1000 mm liggen.",190
"Die Höhe muss zwischen 5 und 1000 mm liegen.",191
"La hauteur doit être comprise entre 5 et 1000 mm.",192
]),193
("label.err.gap", [194
"Gap must be between 0 and 25.4 mm.",195
"De tussenruimte moet tussen 0 en 25,4 mm liggen.",196
"Die Lücke muss zwischen 0 und 25,4 mm liegen.",197
"L'espace doit être compris entre 0 et 25,4 mm.",198
]),199
("label.err.dpi", [200
"Resolution must be 203, 300 or 600 dpi.",201
"De resolutie moet 203, 300 of 600 dpi zijn.",202
"Die Auflösung muss 203, 300 oder 600 dpi sein.",203
"La résolution doit être de 203, 300 ou 600 ppp.",204
]),205
("label.err.number", [206
"Enter a number for {}.",207
"Vul een getal in bij {}.",208
"Geben Sie eine Zahl für {} ein.",209
"Saisissez un nombre pour {}.",210
]),211
("label.err.save", [212
"The label format could not be saved: {}",213
"Het labelformaat kon niet worden opgeslagen: {}",214
"Das Etikettenformat konnte nicht gespeichert werden: {}",215
"Le format d'étiquette n'a pas pu être enregistré : {}",216
]),217
("label.err.missing_cli", [218
"No label format saved for label printer '{}'. Print once from the Posprint window to set it.",219
"Geen labelformaat bewaard voor labelprinter '{}'. Druk één keer af vanuit het Posprint-venster om het in te stellen.",220
"Kein Etikettenformat für Etikettendrucker '{}' gespeichert. Drucken Sie einmal aus dem Posprint-Fenster, um es festzulegen.",221
"Aucun format enregistré pour l'imprimante d'étiquettes « {} ». Imprimez une fois depuis la fenêtre Posprint pour le définir.",222
]),223
("label.status.head_open", [224
"The printer reports: cover/print head open.",225
"De printer meldt: klep/printkop open.",226
"Der Drucker meldet: Abdeckung/Druckkopf offen.",227
"L'imprimante signale : capot/tête ouverte.",228
]),229
("label.status.paper_jam", [230
"The printer reports: paper jam.",231
"De printer meldt: papierstoring.",232
"Der Drucker meldet: Papierstau.",233
"L'imprimante signale : bourrage papier.",234
]),235
("label.status.out_of_paper", [236
"The printer reports: out of labels (or not calibrated).",237
"De printer meldt: labels op (of niet gekalibreerd).",238
"Der Drucker meldet: keine Etiketten (oder nicht kalibriert).",239
"L'imprimante signale : plus d'étiquettes (ou non calibrée).",240
]),241
("label.status.out_of_ribbon", [242
"The printer reports: out of ribbon.",243
"De printer meldt: lint op.",244
"Der Drucker meldet: Farbband leer.",245
"L'imprimante signale : ruban épuisé.",246
]),247
("label.status.paused", [248
"The printer is paused.",249
"De printer staat op pauze.",250
"Der Drucker ist angehalten.",251
"L'imprimante est en pause.",252
]),253
("label.status.other", [254
"The printer reports an error.",255
"De printer meldt een fout.",256
"Der Drucker meldet einen Fehler.",257
"L'imprimante signale une erreur.",258
]),259
];260
261
pub fn tr_in(lang: Lang, key: &str) -> &'static str {262
let idx = match lang {263
Lang::En => 0,264
Lang::Nl => 1,265
Lang::De => 2,266
Lang::Fr => 3,267
};268
TEXTS269
.iter()270
.find(|(k, _)| *k == key)271
.map(|(_, v)| v[idx])272
.unwrap_or("?")273
}274
275
pub fn tr(key: &str) -> &'static str {276
tr_in(Lang::current(), key)277
}278
279
/// `tr` with the single `{}` placeholder filled.280
pub fn trf(key: &str, arg: &str) -> String {281
tr(key).replacen("{}", arg, 1)282
}283
284
#[cfg(test)]285
mod tests {286
use super::*;287
288
#[test]289
fn every_key_has_four_languages() {290
let mut seen = std::collections::HashSet::new();291
for (k, v) in TEXTS {292
assert!(seen.insert(*k), "duplicate key {k}");293
for (i, t) in v.iter().enumerate() {294
assert!(!t.trim().is_empty(), "{k}[{i}] empty");295
}296
let n = v[0].matches("{}").count();297
assert!(v.iter().all(|t| t.matches("{}").count() == n), "{k} placeholder mismatch");298
// Not just copied English.299
assert!(v[1] != v[0] || v[0].len() < 12, "{k} nl untranslated");300
}301
}302
303
#[test]304
fn locale_mapping() {305
assert_eq!(Lang::from_locale("nl_NL.UTF-8"), Lang::Nl);306
assert_eq!(Lang::from_locale("de-DE"), Lang::De);307
assert_eq!(Lang::from_locale("fr_BE"), Lang::Fr);308
assert_eq!(Lang::from_locale("en_GB"), Lang::En);309
assert_eq!(Lang::from_locale("ja"), Lang::En);310
assert_eq!(tr_in(Lang::Nl, "label.width"), "Breedte (mm)");311
assert_eq!(tr_in(Lang::En, "nope"), "?");312
}313
}@@ -0,0 +1,223 @@
1
//! Label formats for TSPL label printers, remembered per printer model in a
2
//! separate file (`label_formats.json` next to `config.json`) so the existing
3
//! config file format does not change.
4
5
use std::collections::BTreeMap;
6
use std::fs;
7
use std::path::{Path, PathBuf};
8
9
use serde::{Deserialize, Serialize};
10
11
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]
12
#[serde(rename_all = "snake_case")]
13
pub enum MediaKind {
14
/// Labels separated by a gap or notch (gap sensor).
15
#[default]
16
Gap,
17
/// Black mark on the back (black-mark sensor).
18
BlackMark,
19
/// Continuous media, no separation.
20
Continuous,
21
}
22
23
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
24
pub struct LabelFormat {
25
pub width_mm: f32,
26
pub height_mm: f32,
27
/// Gap or black-mark height in mm (ignored for continuous media).
28
#[serde(default = "default_gap")]
29
pub gap_mm: f32,
30
#[serde(default)]
31
pub media: MediaKind,
32
/// Print-head resolution (203 or 300 dpi; 600 for 600-dpi models).
33
#[serde(default = "default_dpi")]
34
pub dpi: u16,
35
/// Print rotated 180° (TSPL `DIRECTION 1`).
36
#[serde(default)]
37
pub rotate_180: bool,
38
}
39
40
fn default_gap() -> f32 {
41
3.0
42
}
43
fn default_dpi() -> u16 {
44
203
45
}
46
47
impl Default for LabelFormat {
48
fn default() -> Self {
49
Self {
50
width_mm: 100.0,
51
height_mm: 50.0,
52
gap_mm: default_gap(),
53
media: MediaKind::Gap,
54
dpi: default_dpi(),
55
rotate_180: false,
56
}
57
}
58
}
59
60
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
61
pub enum FormatError {
62
Width,
63
Height,
64
Gap,
65
Dpi,
66
}
67
68
impl LabelFormat {
69
/// Defaults for a model; the resolution is guessed from the model name
70
/// (e.g. `ATP-300 Pro` → 300 dpi). Shown pre-filled in the print dialog.
71
pub fn suggested_for_model(model: Option<&str>) -> Self {
72
let mut f = Self::default();
73
if let Some(m) = model {
74
let m = m.to_ascii_lowercase();
75
if m.contains("-300") || m.contains(" 300") || m.contains("344") || m.contains("346") {
76
f.dpi = 300;
77
} else if m.contains("-600") || m.contains(" 600") {
78
f.dpi = 600;
79
}
80
if m.contains("atp-300") || m.contains("atp-600") {
81
f.width_mm = 100.0;
82
}
83
}
84
f
85
}
86
87
pub fn validate(&self) -> Result<(), FormatError> {
88
if !(self.width_mm.is_finite() && (10.0..=120.0).contains(&self.width_mm)) {
89
return Err(FormatError::Width);
90
}
91
if !(self.height_mm.is_finite() && (5.0..=1000.0).contains(&self.height_mm)) {
92
return Err(FormatError::Height);
93
}
94
if self.media != MediaKind::Continuous
95
&& !(self.gap_mm.is_finite() && (0.0..=25.4).contains(&self.gap_mm))
96
{
97
return Err(FormatError::Gap);
98
}
99
if ![203u16, 300, 600].contains(&self.dpi) {
100
return Err(FormatError::Dpi);
101
}
102
Ok(())
103
}
104
105
/// Dots per mm as used by TSPL (manual: 200 DPI = 8 dots/mm, 300 DPI = 12 dots/mm).
106
pub fn dots_per_mm(&self) -> u32 {
107
match self.dpi {
108
300 => 12,
109
600 => 24,
110
_ => 8,
111
}
112
}
113
}
114
115
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]
116
pub struct LabelFormatStore {
117
#[serde(default)]
118
pub formats: BTreeMap<String, LabelFormat>,
119
}
120
121
impl LabelFormatStore {
122
pub fn load() -> Self {
123
Self::load_from_path(&store_path())
124
}
125
126
pub fn load_from_path(path: &Path) -> Self {
127
fs::read_to_string(path)
128
.ok()
129
.and_then(|t| serde_json::from_str::<Self>(&t).ok())
130
.unwrap_or_default()
131
}
132
133
pub fn save(&self) -> Result<(), String> {
134
self.save_to_path(&store_path())
135
}
136
137
pub fn save_to_path(&self, path: &Path) -> Result<(), String> {
138
if let Some(parent) = path.parent() {
139
fs::create_dir_all(parent).map_err(|e| e.to_string())?;
140
}
141
let json = serde_json::to_string_pretty(self).map_err(|e| e.to_string())?;
142
fs::write(path, json).map_err(|e| e.to_string())
143
}
144
145
pub fn get(&self, model_key: &str) -> Option<&LabelFormat> {
146
self.formats.get(model_key.trim())
147
}
148
149
pub fn set(&mut self, model_key: &str, format: LabelFormat) {
150
let key = model_key.trim();
151
if !key.is_empty() {
152
self.formats.insert(key.to_string(), format);
153
}
154
}
155
}
156
157
/// `label_formats.json` next to the app config file.
158
pub fn store_path() -> PathBuf {
159
let cfg = crate::config::config_path();
160
cfg.parent()
161
.map(|p| p.join("label_formats.json"))
162
.unwrap_or_else(|| PathBuf::from("label_formats.json"))
163
}
164
165
#[cfg(test)]
166
mod tests {
167
use super::*;
168
169
#[test]
170
fn roundtrip_per_model() {
171
let dir = tempfile::tempdir().unwrap();
172
let path = dir.path().join("posprint").join("label_formats.json");
173
let mut store = LabelFormatStore::default();
174
let f = LabelFormat { width_mm: 50.0, height_mm: 30.0, gap_mm: 2.0, media: MediaKind::Gap, dpi: 300, rotate_180: false };
175
store.set("Altec ATP-300 Pro", f.clone());
176
store.set(" ", LabelFormat::default());
177
store.save_to_path(&path).unwrap();
178
let loaded = LabelFormatStore::load_from_path(&path);
179
assert_eq!(loaded.get("Altec ATP-300 Pro"), Some(&f));
180
assert_eq!(loaded.formats.len(), 1);
181
assert!(loaded.get("Other").is_none());
182
}
183
184
#[test]
185
fn corrupt_or_missing_file_is_empty() {
186
let dir = tempfile::tempdir().unwrap();
187
let path = dir.path().join("label_formats.json");
188
assert!(LabelFormatStore::load_from_path(&path).formats.is_empty());
189
fs::write(&path, "{not json").unwrap();
190
assert!(LabelFormatStore::load_from_path(&path).formats.is_empty());
191
}
192
193
#[test]
194
fn suggests_300_dpi_for_atp_300() {
195
assert_eq!(LabelFormat::suggested_for_model(Some("Altec ATP-300 Pro")).dpi, 300);
196
assert_eq!(LabelFormat::suggested_for_model(Some("TSC TE200")).dpi, 203);
197
assert_eq!(LabelFormat::suggested_for_model(None).dots_per_mm(), 8);
198
}
199
200
#[test]
201
fn validation() {
202
assert!(LabelFormat::default().validate().is_ok());
203
let mut f = LabelFormat::default();
204
f.width_mm = 0.0;
205
assert_eq!(f.validate(), Err(FormatError::Width));
206
f = LabelFormat::default();
207
f.height_mm = f32::NAN;
208
assert_eq!(f.validate(), Err(FormatError::Height));
209
f = LabelFormat::default();
210
f.gap_mm = 40.0;
211
assert_eq!(f.validate(), Err(FormatError::Gap));
212
f.media = MediaKind::Continuous;
213
assert!(f.validate().is_ok());
214
f.dpi = 150;
215
assert_eq!(f.validate(), Err(FormatError::Dpi));
216
}
217
218
#[test]
219
fn store_file_is_separate_from_config() {
220
assert_eq!(store_path().file_name().unwrap(), "label_formats.json");
221
assert_eq!(store_path().parent(), crate::config::config_path().parent());
222
}
223
}
@@ -0,0 +1,223 @@1
//! Label formats for TSPL label printers, remembered per printer model in a2
//! separate file (`label_formats.json` next to `config.json`) so the existing3
//! config file format does not change.4
5
use std::collections::BTreeMap;6
use std::fs;7
use std::path::{Path, PathBuf};8
9
use serde::{Deserialize, Serialize};10
11
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize, Default)]12
#[serde(rename_all = "snake_case")]13
pub enum MediaKind {14
/// Labels separated by a gap or notch (gap sensor).15
#[default]16
Gap,17
/// Black mark on the back (black-mark sensor).18
BlackMark,19
/// Continuous media, no separation.20
Continuous,21
}22
23
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]24
pub struct LabelFormat {25
pub width_mm: f32,26
pub height_mm: f32,27
/// Gap or black-mark height in mm (ignored for continuous media).28
#[serde(default = "default_gap")]29
pub gap_mm: f32,30
#[serde(default)]31
pub media: MediaKind,32
/// Print-head resolution (203 or 300 dpi; 600 for 600-dpi models).33
#[serde(default = "default_dpi")]34
pub dpi: u16,35
/// Print rotated 180° (TSPL `DIRECTION 1`).36
#[serde(default)]37
pub rotate_180: bool,38
}39
40
fn default_gap() -> f32 {41
3.042
}43
fn default_dpi() -> u16 {44
20345
}46
47
impl Default for LabelFormat {48
fn default() -> Self {49
Self {50
width_mm: 100.0,51
height_mm: 50.0,52
gap_mm: default_gap(),53
media: MediaKind::Gap,54
dpi: default_dpi(),55
rotate_180: false,56
}57
}58
}59
60
#[derive(Debug, Clone, Copy, PartialEq, Eq)]61
pub enum FormatError {62
Width,63
Height,64
Gap,65
Dpi,66
}67
68
impl LabelFormat {69
/// Defaults for a model; the resolution is guessed from the model name70
/// (e.g. `ATP-300 Pro` → 300 dpi). Shown pre-filled in the print dialog.71
pub fn suggested_for_model(model: Option<&str>) -> Self {72
let mut f = Self::default();73
if let Some(m) = model {74
let m = m.to_ascii_lowercase();75
if m.contains("-300") || m.contains(" 300") || m.contains("344") || m.contains("346") {76
f.dpi = 300;77
} else if m.contains("-600") || m.contains(" 600") {78
f.dpi = 600;79
}80
if m.contains("atp-300") || m.contains("atp-600") {81
f.width_mm = 100.0;82
}83
}84
f85
}86
87
pub fn validate(&self) -> Result<(), FormatError> {88
if !(self.width_mm.is_finite() && (10.0..=120.0).contains(&self.width_mm)) {89
return Err(FormatError::Width);90
}91
if !(self.height_mm.is_finite() && (5.0..=1000.0).contains(&self.height_mm)) {92
return Err(FormatError::Height);93
}94
if self.media != MediaKind::Continuous95
&& !(self.gap_mm.is_finite() && (0.0..=25.4).contains(&self.gap_mm))96
{97
return Err(FormatError::Gap);98
}99
if ![203u16, 300, 600].contains(&self.dpi) {100
return Err(FormatError::Dpi);101
}102
Ok(())103
}104
105
/// Dots per mm as used by TSPL (manual: 200 DPI = 8 dots/mm, 300 DPI = 12 dots/mm).106
pub fn dots_per_mm(&self) -> u32 {107
match self.dpi {108
300 => 12,109
600 => 24,110
_ => 8,111
}112
}113
}114
115
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize, Default)]116
pub struct LabelFormatStore {117
#[serde(default)]118
pub formats: BTreeMap<String, LabelFormat>,119
}120
121
impl LabelFormatStore {122
pub fn load() -> Self {123
Self::load_from_path(&store_path())124
}125
126
pub fn load_from_path(path: &Path) -> Self {127
fs::read_to_string(path)128
.ok()129
.and_then(|t| serde_json::from_str::<Self>(&t).ok())130
.unwrap_or_default()131
}132
133
pub fn save(&self) -> Result<(), String> {134
self.save_to_path(&store_path())135
}136
137
pub fn save_to_path(&self, path: &Path) -> Result<(), String> {138
if let Some(parent) = path.parent() {139
fs::create_dir_all(parent).map_err(|e| e.to_string())?;140
}141
let json = serde_json::to_string_pretty(self).map_err(|e| e.to_string())?;142
fs::write(path, json).map_err(|e| e.to_string())143
}144
145
pub fn get(&self, model_key: &str) -> Option<&LabelFormat> {146
self.formats.get(model_key.trim())147
}148
149
pub fn set(&mut self, model_key: &str, format: LabelFormat) {150
let key = model_key.trim();151
if !key.is_empty() {152
self.formats.insert(key.to_string(), format);153
}154
}155
}156
157
/// `label_formats.json` next to the app config file.158
pub fn store_path() -> PathBuf {159
let cfg = crate::config::config_path();160
cfg.parent()161
.map(|p| p.join("label_formats.json"))162
.unwrap_or_else(|| PathBuf::from("label_formats.json"))163
}164
165
#[cfg(test)]166
mod tests {167
use super::*;168
169
#[test]170
fn roundtrip_per_model() {171
let dir = tempfile::tempdir().unwrap();172
let path = dir.path().join("posprint").join("label_formats.json");173
let mut store = LabelFormatStore::default();174
let f = LabelFormat { width_mm: 50.0, height_mm: 30.0, gap_mm: 2.0, media: MediaKind::Gap, dpi: 300, rotate_180: false };175
store.set("Altec ATP-300 Pro", f.clone());176
store.set(" ", LabelFormat::default());177
store.save_to_path(&path).unwrap();178
let loaded = LabelFormatStore::load_from_path(&path);179
assert_eq!(loaded.get("Altec ATP-300 Pro"), Some(&f));180
assert_eq!(loaded.formats.len(), 1);181
assert!(loaded.get("Other").is_none());182
}183
184
#[test]185
fn corrupt_or_missing_file_is_empty() {186
let dir = tempfile::tempdir().unwrap();187
let path = dir.path().join("label_formats.json");188
assert!(LabelFormatStore::load_from_path(&path).formats.is_empty());189
fs::write(&path, "{not json").unwrap();190
assert!(LabelFormatStore::load_from_path(&path).formats.is_empty());191
}192
193
#[test]194
fn suggests_300_dpi_for_atp_300() {195
assert_eq!(LabelFormat::suggested_for_model(Some("Altec ATP-300 Pro")).dpi, 300);196
assert_eq!(LabelFormat::suggested_for_model(Some("TSC TE200")).dpi, 203);197
assert_eq!(LabelFormat::suggested_for_model(None).dots_per_mm(), 8);198
}199
200
#[test]201
fn validation() {202
assert!(LabelFormat::default().validate().is_ok());203
let mut f = LabelFormat::default();204
f.width_mm = 0.0;205
assert_eq!(f.validate(), Err(FormatError::Width));206
f = LabelFormat::default();207
f.height_mm = f32::NAN;208
assert_eq!(f.validate(), Err(FormatError::Height));209
f = LabelFormat::default();210
f.gap_mm = 40.0;211
assert_eq!(f.validate(), Err(FormatError::Gap));212
f.media = MediaKind::Continuous;213
assert!(f.validate().is_ok());214
f.dpi = 150;215
assert_eq!(f.validate(), Err(FormatError::Dpi));216
}217
218
#[test]219
fn store_file_is_separate_from_config() {220
assert_eq!(store_path().file_name().unwrap(), "label_formats.json");221
assert_eq!(store_path().parent(), crate::config::config_path().parent());222
}223
}@@ -7,14 +7,18 @@ pub mod editor_assist;
7
7
pub mod escpos;
8
8
pub mod help_view;
9
9
pub mod image_load;
10
pub mod i18n;
10
11
pub mod io;
12
pub mod label_format;
11
13
pub mod params;
12
14
pub mod pipeline;
13
15
pub mod preview;
14
16
pub mod print;
17
pub mod protocol;
15
18
pub mod protocol_url;
16
19
pub mod raster;
17
20
pub mod text_wrap;
21
pub mod tspl;
18
22
pub mod undo;
19
23
20
24
#[cfg(windows)]
@@ -7,14 +7,18 @@ pub mod editor_assist;7
pub mod escpos;
7
pub mod escpos;
8
pub mod help_view;
8
pub mod help_view;
9
pub mod image_load;
9
pub mod image_load;
10
pub mod i18n;
10
pub mod io;
11
pub mod io;
12
pub mod label_format;
11
pub mod params;
13
pub mod params;
12
pub mod pipeline;
14
pub mod pipeline;
13
pub mod preview;
15
pub mod preview;
14
pub mod print;
16
pub mod print;
17
pub mod protocol;
15
pub mod protocol_url;
18
pub mod protocol_url;
16
pub mod raster;
19
pub mod raster;
17
pub mod text_wrap;
20
pub mod text_wrap;
21
pub mod tspl;
18
pub mod undo;
22
pub mod undo;
19
23
20
#[cfg(windows)]
24
#[cfg(windows)]
@@ -7,7 +7,10 @@ use crate::io::{LoadError, PosFile};
7
7
use crate::params::{
8
8
collect_parameters, invalid_bool_parameters, substitute_document, ParamKind,
9
9
};
10
use crate::print::{open_printer_by_name, print_bytes, PrintError};
10
use crate::label_format::{LabelFormat, LabelFormatStore};
11
use crate::print::{open_printer_by_name, print_bytes, PrintError, PrinterTarget};
12
use crate::protocol::{Detection, PrinterProtocol};
13
use crate::tspl::{self, TsplOptions};
11
14
12
15
#[derive(Debug)]
13
16
pub enum PipelineError {
@@ -17,6 +20,8 @@ pub enum PipelineError {
17
20
InvalidBoolParams(Vec<String>),
18
21
Encode(EscPosError),
19
22
Print(PrintError),
23
/// TSPL label printer without a saved label format (model key).
24
LabelFormatMissing(String),
20
25
}
21
26
22
27
impl std::fmt::Display for PipelineError {
@@ -34,6 +39,9 @@ impl std::fmt::Display for PipelineError {
34
39
),
35
40
Self::Encode(e) => write!(f, "{e:?}"),
36
41
Self::Print(e) => write!(f, "{e:?}"),
42
Self::LabelFormatMissing(model) => {
43
write!(f, "{}", crate::i18n::trf("label.err.missing_cli", model))
44
}
37
45
}
38
46
}
39
47
}
@@ -79,6 +87,78 @@ pub fn encode_pos_file(
79
87
Ok(bytes.to_vec())
80
88
}
81
89
90
/// Encode for a TSPL label printer: the unchanged ESC/POS encoding is rendered
91
/// to a bitmap and sent as TSPL `BITMAP` labels (see [`crate::tspl`]).
92
pub fn encode_pos_file_tspl(
93
file: &PosFile,
94
base_dir: Option<&Path>,
95
params: &HashMap<String, String>,
96
format: &LabelFormat,
97
opts: TsplOptions,
98
) -> Result<Vec<u8>, PipelineError> {
99
let escpos = encode_pos_file(file, base_dir, params)?;
100
Ok(tspl::escpos_to_tspl(
101
&escpos,
102
file.metadata.printable_dots() as u32,
103
format,
104
opts,
105
))
106
}
107
108
/// Resolve a printer name like `open_printer_by_name` does and detect its protocol.
109
pub fn detect_by_name(name: &str) -> Option<(PrinterTarget, Detection)> {
110
let name = name.trim();
111
if name.is_empty() {
112
return None;
113
}
114
let printers = crate::print::list_printers().ok()?;
115
let matched = crate::print::find_matching_printer(&printers, name)?;
116
let d = crate::print::detect_printer(&matched.target);
117
Some((matched.target.clone(), d))
118
}
119
120
/// Suggested label format for a TSPL printer: model defaults, refined with
121
/// values the printer reports itself (GETSETTING$, bidirectional USB only).
122
/// Returns `(format, read_from_printer)`.
123
pub fn suggest_label_format(target: &PrinterTarget, detection: &Detection) -> (LabelFormat, bool) {
124
let mut f = LabelFormat::suggested_for_model(detection.model_name.as_deref());
125
let ask = |q: &str| {
126
crate::print::query_printer(target, q.as_bytes())
127
.map(|r| String::from_utf8_lossy(&r).to_string())
128
};
129
let Some(dpi_reply) = ask(tspl::QUERY_DPI) else {
130
return (f, false);
131
};
132
let mut from_printer = false;
133
if let Some(dpi) = tspl::parse_dpi(&dpi_reply) {
134
f.dpi = dpi;
135
from_printer = true;
136
}
137
let dpmm = Some(f.dots_per_mm());
138
if let Some(w) = ask(tspl::QUERY_PAPER_WIDTH).and_then(|r| tspl::parse_length_mm(&r, dpmm)) {
139
f.width_mm = (w * 10.0).round() / 10.0;
140
from_printer = true;
141
}
142
if let Some(h) = ask(tspl::QUERY_PAPER_SIZE).and_then(|r| tspl::parse_length_mm(&r, dpmm)) {
143
f.height_mm = (h * 10.0).round() / 10.0;
144
from_printer = true;
145
}
146
if let Some(g) = ask(tspl::QUERY_GAP_SIZE).and_then(|r| tspl::parse_length_mm(&r, dpmm)) {
147
f.gap_mm = (g * 10.0).round() / 10.0;
148
from_printer = true;
149
}
150
if f.validate().is_err() {
151
return (LabelFormat::suggested_for_model(detection.model_name.as_deref()), false);
152
}
153
(f, from_printer)
154
}
155
156
/// TSPL `<ESC>!?` status (manual p.82); `None` when unknown or ready.
157
pub fn tspl_status_problem(target: &PrinterTarget) -> Option<tspl::StatusProblem> {
158
let reply = crate::print::query_printer(target, tspl::STATUS_QUERY)?;
159
tspl::status_problem(*reply.first()?)
160
}
161
82
162
pub fn print_pos_file(
83
163
path: &Path,
84
164
printer_port: &str,
@@ -86,7 +166,17 @@ pub fn print_pos_file(
86
166
) -> Result<(), PipelineError> {
87
167
let file = PosFile::load_from_path(path).map_err(PipelineError::Load)?;
88
168
let base_dir = path.parent();
89
let bytes = encode_pos_file(&file, base_dir, params)?;
169
let bytes = match detect_by_name(printer_port) {
170
Some((_, d)) if d.protocol == PrinterProtocol::Tspl => {
171
let store = LabelFormatStore::load();
172
let format = store
173
.get(&d.model_key)
174
.cloned()
175
.ok_or_else(|| PipelineError::LabelFormatMissing(d.model_key.clone()))?;
176
encode_pos_file_tspl(&file, base_dir, params, &format, TsplOptions::default())?
177
}
178
_ => encode_pos_file(&file, base_dir, params)?,
179
};
90
180
let mut transport = open_printer_by_name(printer_port).map_err(PipelineError::Print)?;
91
181
print_bytes(&mut transport, &bytes).map_err(PipelineError::Print)
92
182
}
@@ -113,6 +203,20 @@ mod tests {
113
203
assert!(bytes.windows(4).any(|w| w == [0x1D, b'v', 0x30, 0x00]));
114
204
}
115
205
206
#[test]
207
fn tspl_encoding_reuses_escpos_layout() {
208
let file = PosFile::new("Hi ${Name}\n@cut\n");
209
let mut params = HashMap::new();
210
params.insert("Name".into(), "Ada".into());
211
let f = LabelFormat { dpi: 300, width_mm: 50.0, height_mm: 30.0, ..Default::default() };
212
let job = encode_pos_file_tspl(&file, None, ¶ms, &f, TsplOptions::default()).unwrap();
213
assert!(job.starts_with(b"SIZE 50 mm,30 mm\r\nGAP 3 mm,0 mm\r\n"));
214
assert!(job.ends_with(b"\r\nPRINT 1,1\r\n"));
215
// Missing params still fail like ESC/POS.
216
let err = encode_pos_file_tspl(&file, None, &HashMap::new(), &f, TsplOptions::default());
217
assert!(matches!(err, Err(PipelineError::MissingParams(_))));
218
}
219
116
220
#[test]
117
221
fn encodes_when_all_params_present() {
118
222
let file = PosFile::new("Hi ${Name}");
@@ -7,7 +7,10 @@ use crate::io::{LoadError, PosFile};7
use crate::params::{
7
use crate::params::{
8
collect_parameters, invalid_bool_parameters, substitute_document, ParamKind,
8
collect_parameters, invalid_bool_parameters, substitute_document, ParamKind,
9
};
9
};
10
use crate::print::{open_printer_by_name, print_bytes, PrintError};
10
use crate::label_format::{LabelFormat, LabelFormatStore};
11
use crate::print::{open_printer_by_name, print_bytes, PrintError, PrinterTarget};
12
use crate::protocol::{Detection, PrinterProtocol};
13
use crate::tspl::{self, TsplOptions};
11
14
12
#[derive(Debug)]
15
#[derive(Debug)]
13
pub enum PipelineError {
16
pub enum PipelineError {
@@ -17,6 +20,8 @@ pub enum PipelineError {17
InvalidBoolParams(Vec<String>),
20
InvalidBoolParams(Vec<String>),
18
Encode(EscPosError),
21
Encode(EscPosError),
19
Print(PrintError),
22
Print(PrintError),
23
/// TSPL label printer without a saved label format (model key).
24
LabelFormatMissing(String),
20
}
25
}
21
26
22
impl std::fmt::Display for PipelineError {
27
impl std::fmt::Display for PipelineError {
@@ -34,6 +39,9 @@ impl std::fmt::Display for PipelineError {34
),
39
),
35
Self::Encode(e) => write!(f, "{e:?}"),
40
Self::Encode(e) => write!(f, "{e:?}"),
36
Self::Print(e) => write!(f, "{e:?}"),
41
Self::Print(e) => write!(f, "{e:?}"),
42
Self::LabelFormatMissing(model) => {
43
write!(f, "{}", crate::i18n::trf("label.err.missing_cli", model))
44
}
37
}
45
}
38
}
46
}
39
}
47
}
@@ -79,6 +87,78 @@ pub fn encode_pos_file(79
Ok(bytes.to_vec())
87
Ok(bytes.to_vec())
80
}
88
}
81
89
90
/// Encode for a TSPL label printer: the unchanged ESC/POS encoding is rendered
91
/// to a bitmap and sent as TSPL `BITMAP` labels (see [`crate::tspl`]).
92
pub fn encode_pos_file_tspl(
93
file: &PosFile,
94
base_dir: Option<&Path>,
95
params: &HashMap<String, String>,
96
format: &LabelFormat,
97
opts: TsplOptions,
98
) -> Result<Vec<u8>, PipelineError> {
99
let escpos = encode_pos_file(file, base_dir, params)?;
100
Ok(tspl::escpos_to_tspl(
101
&escpos,
102
file.metadata.printable_dots() as u32,
103
format,
104
opts,
105
))
106
}
107
108
/// Resolve a printer name like `open_printer_by_name` does and detect its protocol.
109
pub fn detect_by_name(name: &str) -> Option<(PrinterTarget, Detection)> {
110
let name = name.trim();
111
if name.is_empty() {
112
return None;
113
}
114
let printers = crate::print::list_printers().ok()?;
115
let matched = crate::print::find_matching_printer(&printers, name)?;
116
let d = crate::print::detect_printer(&matched.target);
117
Some((matched.target.clone(), d))
118
}
119
120
/// Suggested label format for a TSPL printer: model defaults, refined with
121
/// values the printer reports itself (GETSETTING$, bidirectional USB only).
122
/// Returns `(format, read_from_printer)`.
123
pub fn suggest_label_format(target: &PrinterTarget, detection: &Detection) -> (LabelFormat, bool) {
124
let mut f = LabelFormat::suggested_for_model(detection.model_name.as_deref());
125
let ask = |q: &str| {
126
crate::print::query_printer(target, q.as_bytes())
127
.map(|r| String::from_utf8_lossy(&r).to_string())
128
};
129
let Some(dpi_reply) = ask(tspl::QUERY_DPI) else {
130
return (f, false);
131
};
132
let mut from_printer = false;
133
if let Some(dpi) = tspl::parse_dpi(&dpi_reply) {
134
f.dpi = dpi;
135
from_printer = true;
136
}
137
let dpmm = Some(f.dots_per_mm());
138
if let Some(w) = ask(tspl::QUERY_PAPER_WIDTH).and_then(|r| tspl::parse_length_mm(&r, dpmm)) {
139
f.width_mm = (w * 10.0).round() / 10.0;
140
from_printer = true;
141
}
142
if let Some(h) = ask(tspl::QUERY_PAPER_SIZE).and_then(|r| tspl::parse_length_mm(&r, dpmm)) {
143
f.height_mm = (h * 10.0).round() / 10.0;
144
from_printer = true;
145
}
146
if let Some(g) = ask(tspl::QUERY_GAP_SIZE).and_then(|r| tspl::parse_length_mm(&r, dpmm)) {
147
f.gap_mm = (g * 10.0).round() / 10.0;
148
from_printer = true;
149
}
150
if f.validate().is_err() {
151
return (LabelFormat::suggested_for_model(detection.model_name.as_deref()), false);
152
}
153
(f, from_printer)
154
}
155
156
/// TSPL `<ESC>!?` status (manual p.82); `None` when unknown or ready.
157
pub fn tspl_status_problem(target: &PrinterTarget) -> Option<tspl::StatusProblem> {
158
let reply = crate::print::query_printer(target, tspl::STATUS_QUERY)?;
159
tspl::status_problem(*reply.first()?)
160
}
161
82
pub fn print_pos_file(
162
pub fn print_pos_file(
83
path: &Path,
163
path: &Path,
84
printer_port: &str,
164
printer_port: &str,
@@ -86,7 +166,17 @@ pub fn print_pos_file(86
) -> Result<(), PipelineError> {
166
) -> Result<(), PipelineError> {
87
let file = PosFile::load_from_path(path).map_err(PipelineError::Load)?;
167
let file = PosFile::load_from_path(path).map_err(PipelineError::Load)?;
88
let base_dir = path.parent();
168
let base_dir = path.parent();
89
let bytes = encode_pos_file(&file, base_dir, params)?;
169
let bytes = match detect_by_name(printer_port) {
170
Some((_, d)) if d.protocol == PrinterProtocol::Tspl => {
171
let store = LabelFormatStore::load();
172
let format = store
173
.get(&d.model_key)
174
.cloned()
175
.ok_or_else(|| PipelineError::LabelFormatMissing(d.model_key.clone()))?;
176
encode_pos_file_tspl(&file, base_dir, params, &format, TsplOptions::default())?
177
}
178
_ => encode_pos_file(&file, base_dir, params)?,
179
};
90
let mut transport = open_printer_by_name(printer_port).map_err(PipelineError::Print)?;
180
let mut transport = open_printer_by_name(printer_port).map_err(PipelineError::Print)?;
91
print_bytes(&mut transport, &bytes).map_err(PipelineError::Print)
181
print_bytes(&mut transport, &bytes).map_err(PipelineError::Print)
92
}
182
}
@@ -113,6 +203,20 @@ mod tests {113
assert!(bytes.windows(4).any(|w| w == [0x1D, b'v', 0x30, 0x00]));
203
assert!(bytes.windows(4).any(|w| w == [0x1D, b'v', 0x30, 0x00]));
114
}
204
}
115
205
206
#[test]
207
fn tspl_encoding_reuses_escpos_layout() {
208
let file = PosFile::new("Hi ${Name}\n@cut\n");
209
let mut params = HashMap::new();
210
params.insert("Name".into(), "Ada".into());
211
let f = LabelFormat { dpi: 300, width_mm: 50.0, height_mm: 30.0, ..Default::default() };
212
let job = encode_pos_file_tspl(&file, None, ¶ms, &f, TsplOptions::default()).unwrap();
213
assert!(job.starts_with(b"SIZE 50 mm,30 mm\r\nGAP 3 mm,0 mm\r\n"));
214
assert!(job.ends_with(b"\r\nPRINT 1,1\r\n"));
215
// Missing params still fail like ESC/POS.
216
let err = encode_pos_file_tspl(&file, None, &HashMap::new(), &f, TsplOptions::default());
217
assert!(matches!(err, Err(PipelineError::MissingParams(_))));
218
}
219
116
#[test]
220
#[test]
117
fn encodes_when_all_params_present() {
221
fn encodes_when_all_params_present() {
118
let file = PosFile::new("Hi ${Name}");
222
let file = PosFile::new("Hi ${Name}");
@@ -234,6 +234,37 @@ pub fn open_printer_by_name(name: &str) -> Result<Box<dyn PrinterTransport>, Pri
234
234
)))
235
235
}
236
236
237
/// IEEE 1284 device ID if the printer exposes one (USB direct only).
238
pub fn printer_device_id(target: &PrinterTarget) -> Option<String> {
239
match target {
240
PrinterTarget::UsbDirect { vid, pid, bus, address } => {
241
usb_direct::read_device_id(*vid, *pid, *bus, *address)
242
}
243
_ => None,
244
}
245
}
246
247
/// Detect the command language of a printer (ESC/POS unless clearly TSPL).
248
pub fn detect_printer(target: &PrinterTarget) -> crate::protocol::Detection {
249
let id = printer_device_id(target);
250
crate::protocol::detect(target, id.as_deref())
251
}
252
253
/// Ask a bidirectional USB printer something and return its raw reply.
254
pub fn query_printer(target: &PrinterTarget, request: &[u8]) -> Option<Vec<u8>> {
255
match target {
256
PrinterTarget::UsbDirect { vid, pid, bus, address } => usb_direct::query(
257
*vid,
258
*pid,
259
*bus,
260
*address,
261
request,
262
Duration::from_millis(800),
263
),
264
_ => None,
265
}
266
}
267
237
268
fn fmt_vid_pid(v: u16) -> String {
238
269
format!("{v:04x}")
239
270
}
@@ -234,6 +234,37 @@ pub fn open_printer_by_name(name: &str) -> Result<Box<dyn PrinterTransport>, Pri234
)))
234
)))
235
}
235
}
236
236
237
/// IEEE 1284 device ID if the printer exposes one (USB direct only).
238
pub fn printer_device_id(target: &PrinterTarget) -> Option<String> {
239
match target {
240
PrinterTarget::UsbDirect { vid, pid, bus, address } => {
241
usb_direct::read_device_id(*vid, *pid, *bus, *address)
242
}
243
_ => None,
244
}
245
}
246
247
/// Detect the command language of a printer (ESC/POS unless clearly TSPL).
248
pub fn detect_printer(target: &PrinterTarget) -> crate::protocol::Detection {
249
let id = printer_device_id(target);
250
crate::protocol::detect(target, id.as_deref())
251
}
252
253
/// Ask a bidirectional USB printer something and return its raw reply.
254
pub fn query_printer(target: &PrinterTarget, request: &[u8]) -> Option<Vec<u8>> {
255
match target {
256
PrinterTarget::UsbDirect { vid, pid, bus, address } => usb_direct::query(
257
*vid,
258
*pid,
259
*bus,
260
*address,
261
request,
262
Duration::from_millis(800),
263
),
264
_ => None,
265
}
266
}
267
237
fn fmt_vid_pid(v: u16) -> String {
268
fn fmt_vid_pid(v: u16) -> String {
238
format!("{v:04x}")
269
format!("{v:04x}")
239
}
270
}
@@ -83,6 +83,158 @@ fn read_product_string(device: &Device<Context>, desc: &rusb::DeviceDescriptor)
83
83
.ok()
84
84
}
85
85
86
/// IEEE 1284 device ID of a USB printer (`MFG:…;CMD:…;MDL:…;`).
87
///
88
/// Linux: read from sysfs (`ieee1284_id`, provided by the `usblp` driver) so the
89
/// kernel driver is never detached. Otherwise the printer-class
90
/// `GET_DEVICE_ID` control request is used, only when no kernel driver owns the
91
/// interface. Read-only: nothing is sent to the print path.
92
pub fn read_device_id(vid: u16, pid: u16, bus: u8, address: u8) -> Option<String> {
93
#[cfg(target_os = "linux")]
94
if let Some(id) = sysfs_device_id(bus, address) {
95
return Some(id);
96
}
97
let context = Context::new().ok()?;
98
let device = find_device(&context, vid, pid, bus, address)?;
99
let config = device
100
.active_config_descriptor()
101
.or_else(|_| device.config_descriptor(0))
102
.ok()?;
103
let config_index = 0u16;
104
let (iface, alt) = config.interfaces().find_map(|i| {
105
i.descriptors()
106
.find(|d| d.class_code() == USB_CLASS_PRINTER)
107
.map(|d| (d.interface_number(), d.setting_number()))
108
})?;
109
let handle = device.open().ok()?;
110
#[cfg(any(target_os = "linux", target_os = "macos"))]
111
if handle.kernel_driver_active(iface).unwrap_or(false) {
112
return None;
113
}
114
let claimed = handle.claim_interface(iface).is_ok();
115
let mut buf = [0u8; 1024];
116
let result = handle.read_control(
117
0xA1, // device-to-host, class, interface
118
0x00, // GET_DEVICE_ID
119
config_index,
120
(u16::from(iface) << 8) | u16::from(alt),
121
&mut buf,
122
Duration::from_millis(500),
123
);
124
if claimed {
125
let _ = handle.release_interface(iface);
126
}
127
let n = result.ok()?;
128
parse_device_id_reply(&buf[..n])
129
}
130
131
/// Reply = 2-byte big-endian length (including itself) + ID string.
132
pub fn parse_device_id_reply(buf: &[u8]) -> Option<String> {
133
if buf.len() < 2 {
134
return None;
135
}
136
let len = (usize::from(buf[0]) << 8 | usize::from(buf[1])).min(buf.len());
137
let body = if len >= 2 { &buf[2..len] } else { &buf[2..] };
138
let s = String::from_utf8_lossy(body).trim_matches(char::from(0)).trim().to_string();
139
if s.contains(':') {
140
Some(s)
141
} else {
142
None
143
}
144
}
145
146
#[cfg(target_os = "linux")]
147
fn sysfs_device_id(bus: u8, address: u8) -> Option<String> {
148
let root = std::path::Path::new("/sys/bus/usb/devices");
149
for entry in std::fs::read_dir(root).ok()?.flatten() {
150
let dev = entry.path();
151
let read_num = |name: &str| -> Option<u32> {
152
std::fs::read_to_string(dev.join(name)).ok()?.trim().parse().ok()
153
};
154
if read_num("busnum") != Some(u32::from(bus)) || read_num("devnum") != Some(u32::from(address)) {
155
continue;
156
}
157
for iface in std::fs::read_dir(&dev).ok()?.flatten() {
158
let p = iface.path().join("ieee1284_id");
159
if let Ok(id) = std::fs::read_to_string(&p) {
160
let id = id.trim().to_string();
161
if id.contains(':') {
162
return Some(id);
163
}
164
}
165
}
166
}
167
None
168
}
169
170
/// Send `request` and collect the reply from the bulk IN endpoint (bidirectional
171
/// printers). Used only for TSPL settings/status queries.
172
pub fn query(vid: u16, pid: u16, bus: u8, address: u8, request: &[u8], timeout: Duration) -> Option<Vec<u8>> {
173
let context = Context::new().ok()?;
174
let device = find_device(&context, vid, pid, bus, address)?;
175
let config = device
176
.active_config_descriptor()
177
.or_else(|_| device.config_descriptor(0))
178
.ok()?;
179
let mut found = None;
180
for interface in config.interfaces() {
181
for d in interface.descriptors() {
182
if d.class_code() != USB_CLASS_PRINTER {
183
continue;
184
}
185
let mut out_ep = None;
186
let mut in_ep = None;
187
for ep in d.endpoint_descriptors() {
188
if ep.transfer_type() != TransferType::Bulk {
189
continue;
190
}
191
match ep.direction() {
192
Direction::Out => out_ep = Some(ep.address()),
193
Direction::In => in_ep = Some(ep.address()),
194
}
195
}
196
if let (Some(o), Some(i)) = (out_ep, in_ep) {
197
found = Some((d.interface_number(), o, i));
198
}
199
}
200
}
201
let (iface, out_ep, in_ep) = found?;
202
let handle = device.open().ok()?;
203
#[cfg(any(target_os = "linux", target_os = "macos"))]
204
let reattach = if handle.kernel_driver_active(iface).unwrap_or(false) {
205
handle.detach_kernel_driver(iface).ok()?;
206
true
207
} else {
208
false
209
};
210
let mut reply = None;
211
if handle.claim_interface(iface).is_ok() {
212
if handle.write_bulk(out_ep, request, Duration::from_millis(500)).is_ok() {
213
let mut buf = [0u8; 512];
214
let mut got = Vec::new();
215
let deadline = std::time::Instant::now() + timeout;
216
while std::time::Instant::now() < deadline {
217
match handle.read_bulk(in_ep, &mut buf, Duration::from_millis(200)) {
218
Ok(n) if n > 0 => got.extend_from_slice(&buf[..n]),
219
Ok(_) => {}
220
Err(rusb::Error::Timeout) if !got.is_empty() => break,
221
Err(rusb::Error::Timeout) => {}
222
Err(_) => break,
223
}
224
}
225
if !got.is_empty() {
226
reply = Some(got);
227
}
228
}
229
let _ = handle.release_interface(iface);
230
}
231
#[cfg(any(target_os = "linux", target_os = "macos"))]
232
if reattach {
233
let _ = handle.attach_kernel_driver(iface);
234
}
235
reply
236
}
237
86
238
pub struct UsbDirectTransport {
87
239
handle: DeviceHandle<Context>,
88
240
endpoint: u8,
@@ -199,4 +351,18 @@ mod tests {
199
351
fn list_usb_devices_does_not_panic() {
200
352
let _ = list_usb_printer_devices();
201
353
}
354
355
#[test]
356
fn parses_get_device_id_reply() {
357
let id = b"MFG:Altec;CMD:TSPL2;MDL:ATP-300 Pro;CLS:PRINTER;";
358
let mut buf = vec![0u8, (id.len() + 2) as u8];
359
buf.extend_from_slice(id);
360
buf.extend_from_slice(&[0, 0, 0]);
361
assert_eq!(
362
parse_device_id_reply(&buf).as_deref(),
363
Some("MFG:Altec;CMD:TSPL2;MDL:ATP-300 Pro;CLS:PRINTER;")
364
);
365
assert_eq!(parse_device_id_reply(&[0]), None);
366
assert_eq!(parse_device_id_reply(&[0, 2]), None);
367
}
202
368
}
@@ -83,6 +83,158 @@ fn read_product_string(device: &Device<Context>, desc: &rusb::DeviceDescriptor)83
.ok()
83
.ok()
84
}
84
}
85
85
86
/// IEEE 1284 device ID of a USB printer (`MFG:…;CMD:…;MDL:…;`).
87
///
88
/// Linux: read from sysfs (`ieee1284_id`, provided by the `usblp` driver) so the
89
/// kernel driver is never detached. Otherwise the printer-class
90
/// `GET_DEVICE_ID` control request is used, only when no kernel driver owns the
91
/// interface. Read-only: nothing is sent to the print path.
92
pub fn read_device_id(vid: u16, pid: u16, bus: u8, address: u8) -> Option<String> {
93
#[cfg(target_os = "linux")]
94
if let Some(id) = sysfs_device_id(bus, address) {
95
return Some(id);
96
}
97
let context = Context::new().ok()?;
98
let device = find_device(&context, vid, pid, bus, address)?;
99
let config = device
100
.active_config_descriptor()
101
.or_else(|_| device.config_descriptor(0))
102
.ok()?;
103
let config_index = 0u16;
104
let (iface, alt) = config.interfaces().find_map(|i| {
105
i.descriptors()
106
.find(|d| d.class_code() == USB_CLASS_PRINTER)
107
.map(|d| (d.interface_number(), d.setting_number()))
108
})?;
109
let handle = device.open().ok()?;
110
#[cfg(any(target_os = "linux", target_os = "macos"))]
111
if handle.kernel_driver_active(iface).unwrap_or(false) {
112
return None;
113
}
114
let claimed = handle.claim_interface(iface).is_ok();
115
let mut buf = [0u8; 1024];
116
let result = handle.read_control(
117
0xA1, // device-to-host, class, interface
118
0x00, // GET_DEVICE_ID
119
config_index,
120
(u16::from(iface) << 8) | u16::from(alt),
121
&mut buf,
122
Duration::from_millis(500),
123
);
124
if claimed {
125
let _ = handle.release_interface(iface);
126
}
127
let n = result.ok()?;
128
parse_device_id_reply(&buf[..n])
129
}
130
131
/// Reply = 2-byte big-endian length (including itself) + ID string.
132
pub fn parse_device_id_reply(buf: &[u8]) -> Option<String> {
133
if buf.len() < 2 {
134
return None;
135
}
136
let len = (usize::from(buf[0]) << 8 | usize::from(buf[1])).min(buf.len());
137
let body = if len >= 2 { &buf[2..len] } else { &buf[2..] };
138
let s = String::from_utf8_lossy(body).trim_matches(char::from(0)).trim().to_string();
139
if s.contains(':') {
140
Some(s)
141
} else {
142
None
143
}
144
}
145
146
#[cfg(target_os = "linux")]
147
fn sysfs_device_id(bus: u8, address: u8) -> Option<String> {
148
let root = std::path::Path::new("/sys/bus/usb/devices");
149
for entry in std::fs::read_dir(root).ok()?.flatten() {
150
let dev = entry.path();
151
let read_num = |name: &str| -> Option<u32> {
152
std::fs::read_to_string(dev.join(name)).ok()?.trim().parse().ok()
153
};
154
if read_num("busnum") != Some(u32::from(bus)) || read_num("devnum") != Some(u32::from(address)) {
155
continue;
156
}
157
for iface in std::fs::read_dir(&dev).ok()?.flatten() {
158
let p = iface.path().join("ieee1284_id");
159
if let Ok(id) = std::fs::read_to_string(&p) {
160
let id = id.trim().to_string();
161
if id.contains(':') {
162
return Some(id);
163
}
164
}
165
}
166
}
167
None
168
}
169
170
/// Send `request` and collect the reply from the bulk IN endpoint (bidirectional
171
/// printers). Used only for TSPL settings/status queries.
172
pub fn query(vid: u16, pid: u16, bus: u8, address: u8, request: &[u8], timeout: Duration) -> Option<Vec<u8>> {
173
let context = Context::new().ok()?;
174
let device = find_device(&context, vid, pid, bus, address)?;
175
let config = device
176
.active_config_descriptor()
177
.or_else(|_| device.config_descriptor(0))
178
.ok()?;
179
let mut found = None;
180
for interface in config.interfaces() {
181
for d in interface.descriptors() {
182
if d.class_code() != USB_CLASS_PRINTER {
183
continue;
184
}
185
let mut out_ep = None;
186
let mut in_ep = None;
187
for ep in d.endpoint_descriptors() {
188
if ep.transfer_type() != TransferType::Bulk {
189
continue;
190
}
191
match ep.direction() {
192
Direction::Out => out_ep = Some(ep.address()),
193
Direction::In => in_ep = Some(ep.address()),
194
}
195
}
196
if let (Some(o), Some(i)) = (out_ep, in_ep) {
197
found = Some((d.interface_number(), o, i));
198
}
199
}
200
}
201
let (iface, out_ep, in_ep) = found?;
202
let handle = device.open().ok()?;
203
#[cfg(any(target_os = "linux", target_os = "macos"))]
204
let reattach = if handle.kernel_driver_active(iface).unwrap_or(false) {
205
handle.detach_kernel_driver(iface).ok()?;
206
true
207
} else {
208
false
209
};
210
let mut reply = None;
211
if handle.claim_interface(iface).is_ok() {
212
if handle.write_bulk(out_ep, request, Duration::from_millis(500)).is_ok() {
213
let mut buf = [0u8; 512];
214
let mut got = Vec::new();
215
let deadline = std::time::Instant::now() + timeout;
216
while std::time::Instant::now() < deadline {
217
match handle.read_bulk(in_ep, &mut buf, Duration::from_millis(200)) {
218
Ok(n) if n > 0 => got.extend_from_slice(&buf[..n]),
219
Ok(_) => {}
220
Err(rusb::Error::Timeout) if !got.is_empty() => break,
221
Err(rusb::Error::Timeout) => {}
222
Err(_) => break,
223
}
224
}
225
if !got.is_empty() {
226
reply = Some(got);
227
}
228
}
229
let _ = handle.release_interface(iface);
230
}
231
#[cfg(any(target_os = "linux", target_os = "macos"))]
232
if reattach {
233
let _ = handle.attach_kernel_driver(iface);
234
}
235
reply
236
}
237
86
pub struct UsbDirectTransport {
238
pub struct UsbDirectTransport {
87
handle: DeviceHandle<Context>,
239
handle: DeviceHandle<Context>,
88
endpoint: u8,
240
endpoint: u8,
@@ -199,4 +351,18 @@ mod tests {199
fn list_usb_devices_does_not_panic() {
351
fn list_usb_devices_does_not_panic() {
200
let _ = list_usb_printer_devices();
352
let _ = list_usb_printer_devices();
201
}
353
}
354
355
#[test]
356
fn parses_get_device_id_reply() {
357
let id = b"MFG:Altec;CMD:TSPL2;MDL:ATP-300 Pro;CLS:PRINTER;";
358
let mut buf = vec![0u8, (id.len() + 2) as u8];
359
buf.extend_from_slice(id);
360
buf.extend_from_slice(&[0, 0, 0]);
361
assert_eq!(
362
parse_device_id_reply(&buf).as_deref(),
363
Some("MFG:Altec;CMD:TSPL2;MDL:ATP-300 Pro;CLS:PRINTER;")
364
);
365
assert_eq!(parse_device_id_reply(&[0]), None);
366
assert_eq!(parse_device_id_reply(&[0, 2]), None);
367
}
202
}
368
}
@@ -15,6 +15,79 @@ use posprint::print::{
15
15
open_printer_by_name, print_bytes, printer_preference_key, PrintError, PrinterDevice,
16
16
};
17
17
use posprint::config::AppConfig;
18
use posprint::i18n::{tr, trf};
19
use posprint::label_format::{FormatError, LabelFormat, LabelFormatStore, MediaKind};
20
use posprint::print::{detect_printer, find_matching_printer, PrinterTarget};
21
use posprint::protocol::{Detection, DetectionSource, PrinterProtocol};
22
use posprint::tspl::TsplOptions;
23
24
/// Label-format form for TSPL label printers (only shown for those).
25
#[derive(Debug, Clone)]
26
pub struct LabelForm {
27
pub model_key: String,
28
pub width: String,
29
pub height: String,
30
pub gap: String,
31
pub media: MediaKind,
32
pub dpi: u16,
33
pub rotate_180: bool,
34
pub calibrate: bool,
35
pub from_printer: bool,
36
pub error: Option<String>,
37
}
38
39
impl LabelForm {
40
pub fn from_format(model_key: &str, f: &LabelFormat, calibrate: bool, from_printer: bool) -> Self {
41
let n = |v: f32| {
42
let s = format!("{v:.1}");
43
s.trim_end_matches('0').trim_end_matches('.').to_string()
44
};
45
Self {
46
model_key: model_key.to_string(),
47
width: n(f.width_mm),
48
height: n(f.height_mm),
49
gap: n(f.gap_mm),
50
media: f.media,
51
dpi: f.dpi,
52
rotate_180: f.rotate_180,
53
calibrate,
54
from_printer,
55
error: None,
56
}
57
}
58
59
/// Parse and validate; accepts `,` as decimal separator.
60
pub fn to_format(&self) -> Result<LabelFormat, String> {
61
let num = |s: &str, label: &str| -> Result<f32, String> {
62
s.trim()
63
.replace(',', ".")
64
.parse::<f32>()
65
.map_err(|_| trf("label.err.number", label))
66
};
67
let f = LabelFormat {
68
width_mm: num(&self.width, tr("label.width"))?,
69
height_mm: num(&self.height, tr("label.height"))?,
70
gap_mm: if self.media == MediaKind::Continuous {
71
num(&self.gap, tr("label.gap")).unwrap_or(0.0)
72
} else {
73
num(&self.gap, tr("label.gap"))?
74
},
75
media: self.media,
76
dpi: self.dpi,
77
rotate_180: self.rotate_180,
78
};
79
f.validate().map_err(|e| {
80
tr(match e {
81
FormatError::Width => "label.err.width",
82
FormatError::Height => "label.err.height",
83
FormatError::Gap => "label.err.gap",
84
FormatError::Dpi => "label.err.dpi",
85
})
86
.to_string()
87
})?;
88
Ok(f)
89
}
90
}
18
91
19
92
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20
93
pub enum PrintExecuteResult {
@@ -33,6 +106,12 @@ pub struct PrintDialog {
33
106
pub manual_port: String,
34
107
pub use_manual_port: bool,
35
108
pub error: Option<String>,
109
/// Detected protocol per printer id (filled in the background).
110
pub detections: HashMap<String, Detection>,
111
detect_rx: Option<Receiver<HashMap<String, Detection>>>,
112
/// Open label-format form (TSPL printers only).
113
pub label_form: Option<LabelForm>,
114
label_submit: bool,
36
115
}
37
116
38
117
impl Default for PrintDialog {
@@ -48,6 +127,10 @@ impl Default for PrintDialog {
48
127
manual_port: String::new(),
49
128
use_manual_port: false,
50
129
error: None,
130
detections: HashMap::new(),
131
detect_rx: None,
132
label_form: None,
133
label_submit: false,
51
134
}
52
135
}
53
136
}
@@ -100,6 +183,7 @@ impl PrintDialog {
100
183
match result {
101
184
Ok(list) => {
102
185
self.printers = list;
186
self.start_protocol_detection();
103
187
self.apply_preferred_printer(AppConfig::load().last_printer_key.as_deref());
104
188
}
105
189
Err(e) => self.error = Some(format!("{e:?}")),
@@ -115,6 +199,101 @@ impl PrintDialog {
115
199
}
116
200
}
117
201
202
fn start_protocol_detection(&mut self) {
203
let targets: Vec<(String, PrinterTarget)> = self
204
.printers
205
.iter()
206
.map(|p| (p.id.clone(), p.target.clone()))
207
.collect();
208
let (tx, rx) = mpsc::channel();
209
self.detect_rx = Some(rx);
210
std::thread::spawn(move || {
211
let map = targets
212
.into_iter()
213
.map(|(id, t)| (id, detect_printer(&t)))
214
.collect();
215
let _ = tx.send(map);
216
});
217
}
218
219
fn poll_protocol_detection(&mut self) {
220
if let Some(rx) = &self.detect_rx {
221
if let Ok(map) = rx.try_recv() {
222
self.detections = map;
223
self.detect_rx = None;
224
}
225
}
226
}
227
228
/// The printer that would be used, as discovered device (manual names are
229
/// matched against discovered printers like `open_printer_by_name`).
230
fn effective_device(&self) -> Option<&PrinterDevice> {
231
if self.use_manual_port {
232
find_matching_printer(&self.printers, self.manual_port.trim())
233
} else {
234
self.selected_printer.and_then(|i| self.printers.get(i))
235
}
236
}
237
238
/// Cached detection for the effective printer, if it is a TSPL printer.
239
fn cached_tspl(&self) -> Option<&Detection> {
240
let dev = self.effective_device()?;
241
self.detections
242
.get(&dev.id)
243
.filter(|d| d.protocol == PrinterProtocol::Tspl)
244
}
245
246
/// Fresh detection at print time (does not rely on the background thread).
247
fn tspl_for_print(&mut self) -> Option<(PrinterTarget, Detection)> {
248
let dev = self.effective_device()?.clone();
249
let d = match self.detections.get(&dev.id) {
250
Some(d) => d.clone(),
251
None => {
252
let d = detect_printer(&dev.target);
253
self.detections.insert(dev.id.clone(), d.clone());
254
d
255
}
256
};
257
(d.protocol == PrinterProtocol::Tspl).then_some((dev.target, d))
258
}
259
260
/// Label format to print with, or `None` when the form must be filled in first.
261
fn resolve_label_format(
262
&mut self,
263
target: &PrinterTarget,
264
d: &Detection,
265
) -> Option<(LabelFormat, TsplOptions)> {
266
if let Some(form) = self.label_form.as_mut().filter(|f| f.model_key == d.model_key) {
267
if !std::mem::take(&mut self.label_submit) {
268
return None;
269
}
270
match form.to_format() {
271
Ok(fmt) => {
272
let mut store = LabelFormatStore::load();
273
store.set(&d.model_key, fmt.clone());
274
if let Err(e) = store.save() {
275
form.error = Some(trf("label.err.save", &e));
276
return None;
277
}
278
let opts = TsplOptions { calibrate: form.calibrate };
279
self.label_form = None;
280
return Some((fmt, opts));
281
}
282
Err(e) => {
283
form.error = Some(e);
284
return None;
285
}
286
}
287
}
288
self.label_submit = false;
289
if let Some(fmt) = LabelFormatStore::load().get(&d.model_key) {
290
return Some((fmt.clone(), TsplOptions::default()));
291
}
292
let (fmt, from_printer) = pipeline::suggest_label_format(target, d);
293
self.label_form = Some(LabelForm::from_format(&d.model_key, &fmt, true, from_printer));
294
None
295
}
296
118
297
pub fn refresh_printers(&mut self) {
119
298
self.start_printer_discovery();
120
299
}
@@ -213,6 +392,24 @@ impl PrintDialog {
213
392
}
214
393
};
215
394
395
// Label printers (TSPL): same document, sent as TSPL bitmap labels.
396
// ESC/POS printers keep the bytes above unchanged.
397
let bytes = match self.tspl_for_print() {
398
Some((target, d)) => match self.resolve_label_format(&target, &d) {
399
Some((fmt, opts)) => {
400
match pipeline::encode_pos_file_tspl(&file, base_dir, &self.last_params, &fmt, opts) {
401
Ok(b) => b,
402
Err(e) => {
403
self.error = Some(e.to_string());
404
return PrintExecuteResult::StillOpen;
405
}
406
}
407
}
408
None => return PrintExecuteResult::StillOpen,
409
},
410
None => bytes,
411
};
412
216
413
let transport_result = if self.use_manual_port {
217
414
let name = self.manual_port.trim();
218
415
if name.is_empty() {
@@ -349,6 +546,11 @@ impl PrintDialog {
349
546
});
350
547
}
351
548
549
self.poll_protocol_detection();
550
if self.show_label_ui(ui) {
551
action = PrintDialogAction::Print;
552
}
553
352
554
if let Some(err) = &self.error {
353
555
ui.colored_label(egui::Color32::RED, err);
354
556
}
@@ -357,6 +559,129 @@ impl PrintDialog {
357
559
}
358
560
}
359
561
562
impl PrintDialog {
563
/// Label-printer section; only drawn for TSPL printers. Returns true when
564
/// "Save and print" was clicked.
565
fn show_label_ui(&mut self, ui: &mut egui::Ui) -> bool {
566
let Some(d) = self.cached_tspl().cloned().or_else(|| {
567
self.label_form.as_ref()?;
568
let dev = self.effective_device()?;
569
self.detections.get(&dev.id).cloned()
570
}) else {
571
return false;
572
};
573
if d.protocol != PrinterProtocol::Tspl {
574
return false;
575
}
576
let mut submit = false;
577
ui.separator();
578
ui.heading(tr("label.title"));
579
let source_tip = match d.source {
580
DetectionSource::DeviceId => tr("label.source.device_id"),
581
DetectionSource::UsbVendor => tr("label.source.usb_vendor"),
582
DetectionSource::QueueName => tr("label.source.queue_name"),
583
DetectionSource::Default => "",
584
};
585
let detected = trf("label.detected", d.protocol.label());
586
let text = match &d.model_name {
587
Some(m) => format!("{detected} — {m}"),
588
None => detected,
589
};
590
ui.label(text).on_hover_text(source_tip);
591
592
let stored = LabelFormatStore::load().get(&d.model_key).cloned();
593
let mut close_form = false;
594
if let Some(form) = self.label_form.as_mut().filter(|f| f.model_key == d.model_key) {
595
ui.label(tr("label.format_missing"));
596
if form.from_printer {
597
ui.label(tr("label.from_printer"));
598
}
599
egui::Grid::new("label_format_grid").num_columns(2).show(ui, |ui| {
600
ui.label(tr("label.width")).on_hover_text(tr("label.width.tip"));
601
ui.text_edit_singleline(&mut form.width).on_hover_text(tr("label.width.tip"));
602
ui.end_row();
603
ui.label(tr("label.height")).on_hover_text(tr("label.height.tip"));
604
ui.text_edit_singleline(&mut form.height).on_hover_text(tr("label.height.tip"));
605
ui.end_row();
606
ui.label(tr("label.media")).on_hover_text(tr("label.media.tip"));
607
ui.horizontal(|ui| {
608
ui.radio_value(&mut form.media, MediaKind::Gap, tr("label.media.gap"))
609
.on_hover_text(tr("label.media.tip"));
610
ui.radio_value(&mut form.media, MediaKind::BlackMark, tr("label.media.black_mark"))
611
.on_hover_text(tr("label.media.tip"));
612
ui.radio_value(&mut form.media, MediaKind::Continuous, tr("label.media.continuous"))
613
.on_hover_text(tr("label.media.tip"));
614
});
615
ui.end_row();
616
if form.media != MediaKind::Continuous {
617
ui.label(tr("label.gap")).on_hover_text(tr("label.gap.tip"));
618
ui.text_edit_singleline(&mut form.gap).on_hover_text(tr("label.gap.tip"));
619
ui.end_row();
620
}
621
ui.label(tr("label.dpi")).on_hover_text(tr("label.dpi.tip"));
622
ui.horizontal(|ui| {
623
for dpi in [203u16, 300, 600] {
624
ui.radio_value(&mut form.dpi, dpi, dpi.to_string())
625
.on_hover_text(tr("label.dpi.tip"));
626
}
627
});
628
ui.end_row();
629
});
630
ui.checkbox(&mut form.rotate_180, tr("label.rotate"))
631
.on_hover_text(tr("label.rotate.tip"));
632
if form.media != MediaKind::Continuous {
633
ui.checkbox(&mut form.calibrate, tr("label.calibrate"))
634
.on_hover_text(tr("label.calibrate.tip"));
635
}
636
ui.horizontal(|ui| {
637
if ui
638
.button(tr("label.save_print"))
639
.on_hover_text(tr("label.save_print.tip"))
640
.clicked()
641
{
642
submit = true;
643
}
644
if ui
645
.button(tr("label.cancel"))
646
.on_hover_text(tr("label.cancel.tip"))
647
.clicked()
648
{
649
close_form = true;
650
}
651
});
652
if let Some(err) = &form.error {
653
ui.colored_label(egui::Color32::RED, err);
654
}
655
} else if let Some(f) = stored {
656
ui.horizontal(|ui| {
657
ui.label(format!(
658
"{}: {} × {} mm, {} dpi",
659
tr("label.format"),
660
f.width_mm,
661
f.height_mm,
662
f.dpi
663
));
664
if ui
665
.button(tr("label.change"))
666
.on_hover_text(tr("label.change.tip"))
667
.clicked()
668
{
669
self.label_form = Some(LabelForm::from_format(&d.model_key, &f, false, false));
670
}
671
});
672
} else {
673
ui.label(tr("label.format_missing"));
674
}
675
if close_form {
676
self.label_form = None;
677
}
678
if submit {
679
self.label_submit = true;
680
}
681
submit
682
}
683
}
684
360
685
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
361
686
pub enum PrintDialogAction {
362
687
None,
@@ -400,6 +725,49 @@ mod tests {
400
725
assert_eq!(dialog.selected_printer, Some(0));
401
726
}
402
727
728
#[test]
729
fn label_form_parses_and_validates() {
730
let f = LabelFormat { width_mm: 50.0, height_mm: 30.0, dpi: 300, ..Default::default() };
731
let mut form = LabelForm::from_format("Altec ATP-300 Pro", &f, true, false);
732
assert_eq!(form.width, "50");
733
assert_eq!(form.to_format().unwrap(), f);
734
form.width = "50,5".into();
735
assert_eq!(form.to_format().unwrap().width_mm, 50.5);
736
form.width = "abc".into();
737
assert!(form.to_format().is_err());
738
form.width = "500".into();
739
assert!(form.to_format().is_err());
740
form.width = "50".into();
741
form.media = MediaKind::Continuous;
742
form.gap = String::new();
743
assert_eq!(form.to_format().unwrap().gap_mm, 0.0);
744
}
745
746
#[test]
747
fn escpos_printers_show_no_label_section() {
748
let mut dialog = PrintDialog::default();
749
dialog.printers = vec![PrinterDevice {
750
id: "a".into(),
751
display_name: "POS".into(),
752
target: PrinterTarget::Serial("COM1".into()),
753
}];
754
dialog.selected_printer = Some(0);
755
assert!(dialog.cached_tspl().is_none());
756
assert!(dialog.tspl_for_print().is_none(), "serial printers stay ESC/POS");
757
let tspl_target = PrinterTarget::UsbDirect { vid: 0x1203, pid: 0x0231, bus: 250, address: 250 };
758
dialog.printers.push(PrinterDevice {
759
id: "usb:250:250:1203:0231".into(),
760
display_name: "ATP".into(),
761
target: tspl_target.clone(),
762
});
763
dialog.detections.insert(
764
"usb:250:250:1203:0231".into(),
765
posprint::protocol::detect(&tspl_target, Some("MFG:Altec;CMD:TSPL2;MDL:ATP-300 Pro;")),
766
);
767
dialog.selected_printer = Some(1);
768
assert_eq!(dialog.cached_tspl().unwrap().model_key, "Altec ATP-300 Pro");
769
}
770
403
771
#[test]
404
772
fn restores_manual_preference() {
405
773
let mut dialog = PrintDialog::default();
@@ -15,6 +15,79 @@ use posprint::print::{15
open_printer_by_name, print_bytes, printer_preference_key, PrintError, PrinterDevice,
15
open_printer_by_name, print_bytes, printer_preference_key, PrintError, PrinterDevice,
16
};
16
};
17
use posprint::config::AppConfig;
17
use posprint::config::AppConfig;
18
use posprint::i18n::{tr, trf};
19
use posprint::label_format::{FormatError, LabelFormat, LabelFormatStore, MediaKind};
20
use posprint::print::{detect_printer, find_matching_printer, PrinterTarget};
21
use posprint::protocol::{Detection, DetectionSource, PrinterProtocol};
22
use posprint::tspl::TsplOptions;
23
24
/// Label-format form for TSPL label printers (only shown for those).
25
#[derive(Debug, Clone)]
26
pub struct LabelForm {
27
pub model_key: String,
28
pub width: String,
29
pub height: String,
30
pub gap: String,
31
pub media: MediaKind,
32
pub dpi: u16,
33
pub rotate_180: bool,
34
pub calibrate: bool,
35
pub from_printer: bool,
36
pub error: Option<String>,
37
}
38
39
impl LabelForm {
40
pub fn from_format(model_key: &str, f: &LabelFormat, calibrate: bool, from_printer: bool) -> Self {
41
let n = |v: f32| {
42
let s = format!("{v:.1}");
43
s.trim_end_matches('0').trim_end_matches('.').to_string()
44
};
45
Self {
46
model_key: model_key.to_string(),
47
width: n(f.width_mm),
48
height: n(f.height_mm),
49
gap: n(f.gap_mm),
50
media: f.media,
51
dpi: f.dpi,
52
rotate_180: f.rotate_180,
53
calibrate,
54
from_printer,
55
error: None,
56
}
57
}
58
59
/// Parse and validate; accepts `,` as decimal separator.
60
pub fn to_format(&self) -> Result<LabelFormat, String> {
61
let num = |s: &str, label: &str| -> Result<f32, String> {
62
s.trim()
63
.replace(',', ".")
64
.parse::<f32>()
65
.map_err(|_| trf("label.err.number", label))
66
};
67
let f = LabelFormat {
68
width_mm: num(&self.width, tr("label.width"))?,
69
height_mm: num(&self.height, tr("label.height"))?,
70
gap_mm: if self.media == MediaKind::Continuous {
71
num(&self.gap, tr("label.gap")).unwrap_or(0.0)
72
} else {
73
num(&self.gap, tr("label.gap"))?
74
},
75
media: self.media,
76
dpi: self.dpi,
77
rotate_180: self.rotate_180,
78
};
79
f.validate().map_err(|e| {
80
tr(match e {
81
FormatError::Width => "label.err.width",
82
FormatError::Height => "label.err.height",
83
FormatError::Gap => "label.err.gap",
84
FormatError::Dpi => "label.err.dpi",
85
})
86
.to_string()
87
})?;
88
Ok(f)
89
}
90
}
18
91
19
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
92
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20
pub enum PrintExecuteResult {
93
pub enum PrintExecuteResult {
@@ -33,6 +106,12 @@ pub struct PrintDialog {33
pub manual_port: String,
106
pub manual_port: String,
34
pub use_manual_port: bool,
107
pub use_manual_port: bool,
35
pub error: Option<String>,
108
pub error: Option<String>,
109
/// Detected protocol per printer id (filled in the background).
110
pub detections: HashMap<String, Detection>,
111
detect_rx: Option<Receiver<HashMap<String, Detection>>>,
112
/// Open label-format form (TSPL printers only).
113
pub label_form: Option<LabelForm>,
114
label_submit: bool,
36
}
115
}
37
116
38
impl Default for PrintDialog {
117
impl Default for PrintDialog {
@@ -48,6 +127,10 @@ impl Default for PrintDialog {48
manual_port: String::new(),
127
manual_port: String::new(),
49
use_manual_port: false,
128
use_manual_port: false,
50
error: None,
129
error: None,
130
detections: HashMap::new(),
131
detect_rx: None,
132
label_form: None,
133
label_submit: false,
51
}
134
}
52
}
135
}
53
}
136
}
@@ -100,6 +183,7 @@ impl PrintDialog {100
match result {
183
match result {
101
Ok(list) => {
184
Ok(list) => {
102
self.printers = list;
185
self.printers = list;
186
self.start_protocol_detection();
103
self.apply_preferred_printer(AppConfig::load().last_printer_key.as_deref());
187
self.apply_preferred_printer(AppConfig::load().last_printer_key.as_deref());
104
}
188
}
105
Err(e) => self.error = Some(format!("{e:?}")),
189
Err(e) => self.error = Some(format!("{e:?}")),
@@ -115,6 +199,101 @@ impl PrintDialog {115
}
199
}
116
}
200
}
117
201
202
fn start_protocol_detection(&mut self) {
203
let targets: Vec<(String, PrinterTarget)> = self
204
.printers
205
.iter()
206
.map(|p| (p.id.clone(), p.target.clone()))
207
.collect();
208
let (tx, rx) = mpsc::channel();
209
self.detect_rx = Some(rx);
210
std::thread::spawn(move || {
211
let map = targets
212
.into_iter()
213
.map(|(id, t)| (id, detect_printer(&t)))
214
.collect();
215
let _ = tx.send(map);
216
});
217
}
218
219
fn poll_protocol_detection(&mut self) {
220
if let Some(rx) = &self.detect_rx {
221
if let Ok(map) = rx.try_recv() {
222
self.detections = map;
223
self.detect_rx = None;
224
}
225
}
226
}
227
228
/// The printer that would be used, as discovered device (manual names are
229
/// matched against discovered printers like `open_printer_by_name`).
230
fn effective_device(&self) -> Option<&PrinterDevice> {
231
if self.use_manual_port {
232
find_matching_printer(&self.printers, self.manual_port.trim())
233
} else {
234
self.selected_printer.and_then(|i| self.printers.get(i))
235
}
236
}
237
238
/// Cached detection for the effective printer, if it is a TSPL printer.
239
fn cached_tspl(&self) -> Option<&Detection> {
240
let dev = self.effective_device()?;
241
self.detections
242
.get(&dev.id)
243
.filter(|d| d.protocol == PrinterProtocol::Tspl)
244
}
245
246
/// Fresh detection at print time (does not rely on the background thread).
247
fn tspl_for_print(&mut self) -> Option<(PrinterTarget, Detection)> {
248
let dev = self.effective_device()?.clone();
249
let d = match self.detections.get(&dev.id) {
250
Some(d) => d.clone(),
251
None => {
252
let d = detect_printer(&dev.target);
253
self.detections.insert(dev.id.clone(), d.clone());
254
d
255
}
256
};
257
(d.protocol == PrinterProtocol::Tspl).then_some((dev.target, d))
258
}
259
260
/// Label format to print with, or `None` when the form must be filled in first.
261
fn resolve_label_format(
262
&mut self,
263
target: &PrinterTarget,
264
d: &Detection,
265
) -> Option<(LabelFormat, TsplOptions)> {
266
if let Some(form) = self.label_form.as_mut().filter(|f| f.model_key == d.model_key) {
267
if !std::mem::take(&mut self.label_submit) {
268
return None;
269
}
270
match form.to_format() {
271
Ok(fmt) => {
272
let mut store = LabelFormatStore::load();
273
store.set(&d.model_key, fmt.clone());
274
if let Err(e) = store.save() {
275
form.error = Some(trf("label.err.save", &e));
276
return None;
277
}
278
let opts = TsplOptions { calibrate: form.calibrate };
279
self.label_form = None;
280
return Some((fmt, opts));
281
}
282
Err(e) => {
283
form.error = Some(e);
284
return None;
285
}
286
}
287
}
288
self.label_submit = false;
289
if let Some(fmt) = LabelFormatStore::load().get(&d.model_key) {
290
return Some((fmt.clone(), TsplOptions::default()));
291
}
292
let (fmt, from_printer) = pipeline::suggest_label_format(target, d);
293
self.label_form = Some(LabelForm::from_format(&d.model_key, &fmt, true, from_printer));
294
None
295
}
296
118
pub fn refresh_printers(&mut self) {
297
pub fn refresh_printers(&mut self) {
119
self.start_printer_discovery();
298
self.start_printer_discovery();
120
}
299
}
@@ -213,6 +392,24 @@ impl PrintDialog {213
}
392
}
214
};
393
};
215
394
395
// Label printers (TSPL): same document, sent as TSPL bitmap labels.
396
// ESC/POS printers keep the bytes above unchanged.
397
let bytes = match self.tspl_for_print() {
398
Some((target, d)) => match self.resolve_label_format(&target, &d) {
399
Some((fmt, opts)) => {
400
match pipeline::encode_pos_file_tspl(&file, base_dir, &self.last_params, &fmt, opts) {
401
Ok(b) => b,
402
Err(e) => {
403
self.error = Some(e.to_string());
404
return PrintExecuteResult::StillOpen;
405
}
406
}
407
}
408
None => return PrintExecuteResult::StillOpen,
409
},
410
None => bytes,
411
};
412
216
let transport_result = if self.use_manual_port {
413
let transport_result = if self.use_manual_port {
217
let name = self.manual_port.trim();
414
let name = self.manual_port.trim();
218
if name.is_empty() {
415
if name.is_empty() {
@@ -349,6 +546,11 @@ impl PrintDialog {349
});
546
});
350
}
547
}
351
548
549
self.poll_protocol_detection();
550
if self.show_label_ui(ui) {
551
action = PrintDialogAction::Print;
552
}
553
352
if let Some(err) = &self.error {
554
if let Some(err) = &self.error {
353
ui.colored_label(egui::Color32::RED, err);
555
ui.colored_label(egui::Color32::RED, err);
354
}
556
}
@@ -357,6 +559,129 @@ impl PrintDialog {357
}
559
}
358
}
560
}
359
561
562
impl PrintDialog {
563
/// Label-printer section; only drawn for TSPL printers. Returns true when
564
/// "Save and print" was clicked.
565
fn show_label_ui(&mut self, ui: &mut egui::Ui) -> bool {
566
let Some(d) = self.cached_tspl().cloned().or_else(|| {
567
self.label_form.as_ref()?;
568
let dev = self.effective_device()?;
569
self.detections.get(&dev.id).cloned()
570
}) else {
571
return false;
572
};
573
if d.protocol != PrinterProtocol::Tspl {
574
return false;
575
}
576
let mut submit = false;
577
ui.separator();
578
ui.heading(tr("label.title"));
579
let source_tip = match d.source {
580
DetectionSource::DeviceId => tr("label.source.device_id"),
581
DetectionSource::UsbVendor => tr("label.source.usb_vendor"),
582
DetectionSource::QueueName => tr("label.source.queue_name"),
583
DetectionSource::Default => "",
584
};
585
let detected = trf("label.detected", d.protocol.label());
586
let text = match &d.model_name {
587
Some(m) => format!("{detected} — {m}"),
588
None => detected,
589
};
590
ui.label(text).on_hover_text(source_tip);
591
592
let stored = LabelFormatStore::load().get(&d.model_key).cloned();
593
let mut close_form = false;
594
if let Some(form) = self.label_form.as_mut().filter(|f| f.model_key == d.model_key) {
595
ui.label(tr("label.format_missing"));
596
if form.from_printer {
597
ui.label(tr("label.from_printer"));
598
}
599
egui::Grid::new("label_format_grid").num_columns(2).show(ui, |ui| {
600
ui.label(tr("label.width")).on_hover_text(tr("label.width.tip"));
601
ui.text_edit_singleline(&mut form.width).on_hover_text(tr("label.width.tip"));
602
ui.end_row();
603
ui.label(tr("label.height")).on_hover_text(tr("label.height.tip"));
604
ui.text_edit_singleline(&mut form.height).on_hover_text(tr("label.height.tip"));
605
ui.end_row();
606
ui.label(tr("label.media")).on_hover_text(tr("label.media.tip"));
607
ui.horizontal(|ui| {
608
ui.radio_value(&mut form.media, MediaKind::Gap, tr("label.media.gap"))
609
.on_hover_text(tr("label.media.tip"));
610
ui.radio_value(&mut form.media, MediaKind::BlackMark, tr("label.media.black_mark"))
611
.on_hover_text(tr("label.media.tip"));
612
ui.radio_value(&mut form.media, MediaKind::Continuous, tr("label.media.continuous"))
613
.on_hover_text(tr("label.media.tip"));
614
});
615
ui.end_row();
616
if form.media != MediaKind::Continuous {
617
ui.label(tr("label.gap")).on_hover_text(tr("label.gap.tip"));
618
ui.text_edit_singleline(&mut form.gap).on_hover_text(tr("label.gap.tip"));
619
ui.end_row();
620
}
621
ui.label(tr("label.dpi")).on_hover_text(tr("label.dpi.tip"));
622
ui.horizontal(|ui| {
623
for dpi in [203u16, 300, 600] {
624
ui.radio_value(&mut form.dpi, dpi, dpi.to_string())
625
.on_hover_text(tr("label.dpi.tip"));
626
}
627
});
628
ui.end_row();
629
});
630
ui.checkbox(&mut form.rotate_180, tr("label.rotate"))
631
.on_hover_text(tr("label.rotate.tip"));
632
if form.media != MediaKind::Continuous {
633
ui.checkbox(&mut form.calibrate, tr("label.calibrate"))
634
.on_hover_text(tr("label.calibrate.tip"));
635
}
636
ui.horizontal(|ui| {
637
if ui
638
.button(tr("label.save_print"))
639
.on_hover_text(tr("label.save_print.tip"))
640
.clicked()
641
{
642
submit = true;
643
}
644
if ui
645
.button(tr("label.cancel"))
646
.on_hover_text(tr("label.cancel.tip"))
647
.clicked()
648
{
649
close_form = true;
650
}
651
});
652
if let Some(err) = &form.error {
653
ui.colored_label(egui::Color32::RED, err);
654
}
655
} else if let Some(f) = stored {
656
ui.horizontal(|ui| {
657
ui.label(format!(
658
"{}: {} × {} mm, {} dpi",
659
tr("label.format"),
660
f.width_mm,
661
f.height_mm,
662
f.dpi
663
));
664
if ui
665
.button(tr("label.change"))
666
.on_hover_text(tr("label.change.tip"))
667
.clicked()
668
{
669
self.label_form = Some(LabelForm::from_format(&d.model_key, &f, false, false));
670
}
671
});
672
} else {
673
ui.label(tr("label.format_missing"));
674
}
675
if close_form {
676
self.label_form = None;
677
}
678
if submit {
679
self.label_submit = true;
680
}
681
submit
682
}
683
}
684
360
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
685
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
361
pub enum PrintDialogAction {
686
pub enum PrintDialogAction {
362
None,
687
None,
@@ -400,6 +725,49 @@ mod tests {400
assert_eq!(dialog.selected_printer, Some(0));
725
assert_eq!(dialog.selected_printer, Some(0));
401
}
726
}
402
727
728
#[test]
729
fn label_form_parses_and_validates() {
730
let f = LabelFormat { width_mm: 50.0, height_mm: 30.0, dpi: 300, ..Default::default() };
731
let mut form = LabelForm::from_format("Altec ATP-300 Pro", &f, true, false);
732
assert_eq!(form.width, "50");
733
assert_eq!(form.to_format().unwrap(), f);
734
form.width = "50,5".into();
735
assert_eq!(form.to_format().unwrap().width_mm, 50.5);
736
form.width = "abc".into();
737
assert!(form.to_format().is_err());
738
form.width = "500".into();
739
assert!(form.to_format().is_err());
740
form.width = "50".into();
741
form.media = MediaKind::Continuous;
742
form.gap = String::new();
743
assert_eq!(form.to_format().unwrap().gap_mm, 0.0);
744
}
745
746
#[test]
747
fn escpos_printers_show_no_label_section() {
748
let mut dialog = PrintDialog::default();
749
dialog.printers = vec![PrinterDevice {
750
id: "a".into(),
751
display_name: "POS".into(),
752
target: PrinterTarget::Serial("COM1".into()),
753
}];
754
dialog.selected_printer = Some(0);
755
assert!(dialog.cached_tspl().is_none());
756
assert!(dialog.tspl_for_print().is_none(), "serial printers stay ESC/POS");
757
let tspl_target = PrinterTarget::UsbDirect { vid: 0x1203, pid: 0x0231, bus: 250, address: 250 };
758
dialog.printers.push(PrinterDevice {
759
id: "usb:250:250:1203:0231".into(),
760
display_name: "ATP".into(),
761
target: tspl_target.clone(),
762
});
763
dialog.detections.insert(
764
"usb:250:250:1203:0231".into(),
765
posprint::protocol::detect(&tspl_target, Some("MFG:Altec;CMD:TSPL2;MDL:ATP-300 Pro;")),
766
);
767
dialog.selected_printer = Some(1);
768
assert_eq!(dialog.cached_tspl().unwrap().model_key, "Altec ATP-300 Pro");
769
}
770
403
#[test]
771
#[test]
404
fn restores_manual_preference() {
772
fn restores_manual_preference() {
405
let mut dialog = PrintDialog::default();
773
let mut dialog = PrintDialog::default();
@@ -0,0 +1,235 @@
1
//! Printer command-language detection (ESC/POS vs. TSPL/TSPL2).
2
//!
3
//! Detection order (first hit wins):
4
//! 1. IEEE 1284 device ID (`CMD:` / `COMMAND SET:` field) read from the USB
5
//! printer-class `GET_DEVICE_ID` request (or Linux sysfs `ieee1284_id`).
6
//! `TSPL`, `TSPL2`, `TSPL-EZ` → TSPL. If ESC/POS is also listed, ESC/POS wins
7
//! (keeps existing behaviour for multi-language printers).
8
//! 2. USB vendor ID of TSC Auto ID Technology (0x1203; also used by Altec) → TSPL.
9
//! 3. Windows spooler queue name that clearly names a TSPL label printer.
10
//! 4. Otherwise ESC/POS — the existing default, so nothing changes for
11
//! receipt printers.
12
13
use crate::print::PrinterTarget;
14
15
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
16
pub enum PrinterProtocol {
17
EscPos,
18
Tspl,
19
}
20
21
impl PrinterProtocol {
22
pub fn label(self) -> &'static str {
23
match self {
24
Self::EscPos => "ESC/POS",
25
Self::Tspl => "TSPL/TSPL2",
26
}
27
}
28
}
29
30
/// How the protocol was decided (shown as tooltip, useful for support).
31
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
32
pub enum DetectionSource {
33
DeviceId,
34
UsbVendor,
35
QueueName,
36
Default,
37
}
38
39
#[derive(Debug, Clone, PartialEq, Eq, Default)]
40
pub struct DeviceIdInfo {
41
pub manufacturer: Option<String>,
42
pub model: Option<String>,
43
pub command_sets: Vec<String>,
44
pub raw: String,
45
}
46
47
#[derive(Debug, Clone, PartialEq, Eq)]
48
pub struct Detection {
49
pub protocol: PrinterProtocol,
50
pub source: DetectionSource,
51
/// Stable per-model key for remembering the label format, e.g. `Altec ATP-300 Pro`.
52
pub model_key: String,
53
/// Human-readable model, if known.
54
pub model_name: Option<String>,
55
}
56
57
/// TSC Auto ID Technology (Altec ATP printers report this vendor too).
58
pub const TSC_USB_VENDOR_ID: u16 = 0x1203;
59
60
/// Parse an IEEE 1284 device ID (`KEY:value;KEY:value;`). The optional
61
/// two-byte big-endian length prefix must already be stripped.
62
pub fn parse_ieee1284_id(raw: &str) -> DeviceIdInfo {
63
let mut info = DeviceIdInfo {
64
raw: raw.trim_matches(char::from(0)).trim().to_string(),
65
..Default::default()
66
};
67
for field in raw.split(';') {
68
let Some((key, value)) = field.split_once(':') else {
69
continue;
70
};
71
let key = key.trim().to_ascii_uppercase();
72
let value = value.trim().trim_matches(char::from(0)).trim();
73
if value.is_empty() {
74
continue;
75
}
76
match key.as_str() {
77
"MFG" | "MANUFACTURER" => info.manufacturer = Some(value.to_string()),
78
"MDL" | "MODEL" => info.model = Some(value.to_string()),
79
"CMD" | "COMMAND SET" | "COMMANDSET" => {
80
info.command_sets = value
81
.split(',')
82
.map(|s| s.trim().to_string())
83
.filter(|s| !s.is_empty())
84
.collect();
85
}
86
_ => {}
87
}
88
}
89
info
90
}
91
92
/// Protocol from the `CMD:` list, or `None` when nothing is recognised.
93
pub fn protocol_from_command_sets(sets: &[String]) -> Option<PrinterProtocol> {
94
let norm: Vec<String> = sets
95
.iter()
96
.map(|s| s.to_ascii_uppercase().replace([' ', '_'], ""))
97
.collect();
98
if norm
99
.iter()
100
.any(|s| s == "ESC/POS" || s == "ESCPOS" || s == "ESC/POSE" || s.starts_with("ESCPOS"))
101
{
102
return Some(PrinterProtocol::EscPos);
103
}
104
if norm.iter().any(|s| s.starts_with("TSPL")) {
105
return Some(PrinterProtocol::Tspl);
106
}
107
None
108
}
109
110
fn queue_name_says_tspl(name: &str) -> bool {
111
let n = name.to_ascii_lowercase();
112
n.contains("tspl") || n.contains("altec atp") || n.starts_with("tsc ") || n.contains(" tsc ")
113
}
114
115
/// Decide the protocol for a printer. `device_id` is the raw IEEE 1284 ID if it
116
/// could be read (USB direct only).
117
pub fn detect(target: &PrinterTarget, device_id: Option<&str>) -> Detection {
118
let info = device_id.map(parse_ieee1284_id);
119
let model_name = info.as_ref().and_then(|i| match (&i.manufacturer, &i.model) {
120
(Some(m), Some(d)) if d.to_ascii_lowercase().starts_with(&m.to_ascii_lowercase()) => {
121
Some(d.clone())
122
}
123
(Some(m), Some(d)) => Some(format!("{m} {d}")),
124
(None, Some(d)) => Some(d.clone()),
125
_ => None,
126
});
127
let fallback_key = match target {
128
PrinterTarget::UsbDirect { vid, pid, .. } => format!("usb:{vid:04x}:{pid:04x}"),
129
PrinterTarget::Serial(p) => format!("serial:{p}"),
130
PrinterTarget::WinSpooler(q) => format!("winspool:{q}"),
131
};
132
let model_key = model_name.clone().unwrap_or(fallback_key);
133
134
if let Some(p) = info.as_ref().and_then(|i| protocol_from_command_sets(&i.command_sets)) {
135
return Detection { protocol: p, source: DetectionSource::DeviceId, model_key, model_name };
136
}
137
if let PrinterTarget::UsbDirect { vid, .. } = target {
138
if *vid == TSC_USB_VENDOR_ID {
139
return Detection {
140
protocol: PrinterProtocol::Tspl,
141
source: DetectionSource::UsbVendor,
142
model_key,
143
model_name,
144
};
145
}
146
}
147
if let PrinterTarget::WinSpooler(q) = target {
148
if queue_name_says_tspl(q) {
149
return Detection {
150
protocol: PrinterProtocol::Tspl,
151
source: DetectionSource::QueueName,
152
model_key: q.trim().to_string(),
153
model_name: Some(q.trim().to_string()),
154
};
155
}
156
}
157
Detection { protocol: PrinterProtocol::EscPos, source: DetectionSource::Default, model_key, model_name }
158
}
159
160
#[cfg(test)]
161
mod tests {
162
use super::*;
163
164
const ALTEC: &str = "MFG:Altec;CMD:TSPL2;MDL:ATP-300 Pro;CLS:PRINTER;";
165
166
fn usb(vid: u16, pid: u16) -> PrinterTarget {
167
PrinterTarget::UsbDirect { vid, pid, bus: 3, address: 16 }
168
}
169
170
#[test]
171
fn parses_altec_device_id() {
172
let i = parse_ieee1284_id(ALTEC);
173
assert_eq!(i.manufacturer.as_deref(), Some("Altec"));
174
assert_eq!(i.model.as_deref(), Some("ATP-300 Pro"));
175
assert_eq!(i.command_sets, vec!["TSPL2".to_string()]);
176
}
177
178
#[test]
179
fn altec_is_tspl_with_model_key() {
180
let d = detect(&usb(0x1203, 0x0231), Some(ALTEC));
181
assert_eq!(d.protocol, PrinterProtocol::Tspl);
182
assert_eq!(d.source, DetectionSource::DeviceId);
183
assert_eq!(d.model_key, "Altec ATP-300 Pro");
184
}
185
186
#[test]
187
fn long_keys_and_variants() {
188
for id in [
189
"MANUFACTURER:TSC;COMMAND SET:TSPL;MODEL:TTP-244 Pro;",
190
"MFG:TSC;CMD:TSPL-EZ,ZPL2,EPL2;MDL:TE200;",
191
"mfg:x;cmd:tspl2;mdl:y;",
192
] {
193
assert_eq!(detect(&usb(1, 2), Some(id)).protocol, PrinterProtocol::Tspl, "{id}");
194
}
195
}
196
197
#[test]
198
fn escpos_and_unknown_stay_escpos() {
199
for id in [
200
"MFG:EPSON;CMD:ESC/POS;MDL:TM-T20;",
201
"MFG:Xprinter;CMD:ESCPOS,TSPL;MDL:XP-365B;", // multi-language: keep ESC/POS
202
"MFG:Foo;MDL:Bar;",
203
"",
204
"garbage without fields",
205
] {
206
let d = detect(&usb(0x0416, 0x5011), Some(id));
207
assert_eq!(d.protocol, PrinterProtocol::EscPos, "{id}");
208
}
209
let d = detect(&usb(0x0416, 0x5011), None);
210
assert_eq!(d.protocol, PrinterProtocol::EscPos);
211
assert_eq!(d.source, DetectionSource::Default);
212
assert_eq!(d.model_key, "usb:0416:5011");
213
}
214
215
#[test]
216
fn tsc_vendor_without_device_id_is_tspl() {
217
let d = detect(&usb(0x1203, 0x0231), None);
218
assert_eq!(d.protocol, PrinterProtocol::Tspl);
219
assert_eq!(d.source, DetectionSource::UsbVendor);
220
assert_eq!(d.model_key, "usb:1203:0231");
221
}
222
223
#[test]
224
fn serial_and_plain_queues_are_escpos() {
225
assert_eq!(detect(&PrinterTarget::Serial("COM3".into()), None).protocol, PrinterProtocol::EscPos);
226
assert_eq!(
227
detect(&PrinterTarget::WinSpooler("POS-58".into()), None).protocol,
228
PrinterProtocol::EscPos
229
);
230
assert_eq!(
231
detect(&PrinterTarget::WinSpooler("Altec ATP-300 Pro".into()), None).protocol,
232
PrinterProtocol::Tspl
233
);
234
}
235
}
@@ -0,0 +1,235 @@1
//! Printer command-language detection (ESC/POS vs. TSPL/TSPL2).2
//!3
//! Detection order (first hit wins):4
//! 1. IEEE 1284 device ID (`CMD:` / `COMMAND SET:` field) read from the USB5
//! printer-class `GET_DEVICE_ID` request (or Linux sysfs `ieee1284_id`).6
//! `TSPL`, `TSPL2`, `TSPL-EZ` → TSPL. If ESC/POS is also listed, ESC/POS wins7
//! (keeps existing behaviour for multi-language printers).8
//! 2. USB vendor ID of TSC Auto ID Technology (0x1203; also used by Altec) → TSPL.9
//! 3. Windows spooler queue name that clearly names a TSPL label printer.10
//! 4. Otherwise ESC/POS — the existing default, so nothing changes for11
//! receipt printers.12
13
use crate::print::PrinterTarget;14
15
#[derive(Debug, Clone, Copy, PartialEq, Eq)]16
pub enum PrinterProtocol {17
EscPos,18
Tspl,19
}20
21
impl PrinterProtocol {22
pub fn label(self) -> &'static str {23
match self {24
Self::EscPos => "ESC/POS",25
Self::Tspl => "TSPL/TSPL2",26
}27
}28
}29
30
/// How the protocol was decided (shown as tooltip, useful for support).31
#[derive(Debug, Clone, Copy, PartialEq, Eq)]32
pub enum DetectionSource {33
DeviceId,34
UsbVendor,35
QueueName,36
Default,37
}38
39
#[derive(Debug, Clone, PartialEq, Eq, Default)]40
pub struct DeviceIdInfo {41
pub manufacturer: Option<String>,42
pub model: Option<String>,43
pub command_sets: Vec<String>,44
pub raw: String,45
}46
47
#[derive(Debug, Clone, PartialEq, Eq)]48
pub struct Detection {49
pub protocol: PrinterProtocol,50
pub source: DetectionSource,51
/// Stable per-model key for remembering the label format, e.g. `Altec ATP-300 Pro`.52
pub model_key: String,53
/// Human-readable model, if known.54
pub model_name: Option<String>,55
}56
57
/// TSC Auto ID Technology (Altec ATP printers report this vendor too).58
pub const TSC_USB_VENDOR_ID: u16 = 0x1203;59
60
/// Parse an IEEE 1284 device ID (`KEY:value;KEY:value;`). The optional61
/// two-byte big-endian length prefix must already be stripped.62
pub fn parse_ieee1284_id(raw: &str) -> DeviceIdInfo {63
let mut info = DeviceIdInfo {64
raw: raw.trim_matches(char::from(0)).trim().to_string(),65
..Default::default()66
};67
for field in raw.split(';') {68
let Some((key, value)) = field.split_once(':') else {69
continue;70
};71
let key = key.trim().to_ascii_uppercase();72
let value = value.trim().trim_matches(char::from(0)).trim();73
if value.is_empty() {74
continue;75
}76
match key.as_str() {77
"MFG" | "MANUFACTURER" => info.manufacturer = Some(value.to_string()),78
"MDL" | "MODEL" => info.model = Some(value.to_string()),79
"CMD" | "COMMAND SET" | "COMMANDSET" => {80
info.command_sets = value81
.split(',')82
.map(|s| s.trim().to_string())83
.filter(|s| !s.is_empty())84
.collect();85
}86
_ => {}87
}88
}89
info90
}91
92
/// Protocol from the `CMD:` list, or `None` when nothing is recognised.93
pub fn protocol_from_command_sets(sets: &[String]) -> Option<PrinterProtocol> {94
let norm: Vec<String> = sets95
.iter()96
.map(|s| s.to_ascii_uppercase().replace([' ', '_'], ""))97
.collect();98
if norm99
.iter()100
.any(|s| s == "ESC/POS" || s == "ESCPOS" || s == "ESC/POSE" || s.starts_with("ESCPOS"))101
{102
return Some(PrinterProtocol::EscPos);103
}104
if norm.iter().any(|s| s.starts_with("TSPL")) {105
return Some(PrinterProtocol::Tspl);106
}107
None108
}109
110
fn queue_name_says_tspl(name: &str) -> bool {111
let n = name.to_ascii_lowercase();112
n.contains("tspl") || n.contains("altec atp") || n.starts_with("tsc ") || n.contains(" tsc ")113
}114
115
/// Decide the protocol for a printer. `device_id` is the raw IEEE 1284 ID if it116
/// could be read (USB direct only).117
pub fn detect(target: &PrinterTarget, device_id: Option<&str>) -> Detection {118
let info = device_id.map(parse_ieee1284_id);119
let model_name = info.as_ref().and_then(|i| match (&i.manufacturer, &i.model) {120
(Some(m), Some(d)) if d.to_ascii_lowercase().starts_with(&m.to_ascii_lowercase()) => {121
Some(d.clone())122
}123
(Some(m), Some(d)) => Some(format!("{m} {d}")),124
(None, Some(d)) => Some(d.clone()),125
_ => None,126
});127
let fallback_key = match target {128
PrinterTarget::UsbDirect { vid, pid, .. } => format!("usb:{vid:04x}:{pid:04x}"),129
PrinterTarget::Serial(p) => format!("serial:{p}"),130
PrinterTarget::WinSpooler(q) => format!("winspool:{q}"),131
};132
let model_key = model_name.clone().unwrap_or(fallback_key);133
134
if let Some(p) = info.as_ref().and_then(|i| protocol_from_command_sets(&i.command_sets)) {135
return Detection { protocol: p, source: DetectionSource::DeviceId, model_key, model_name };136
}137
if let PrinterTarget::UsbDirect { vid, .. } = target {138
if *vid == TSC_USB_VENDOR_ID {139
return Detection {140
protocol: PrinterProtocol::Tspl,141
source: DetectionSource::UsbVendor,142
model_key,143
model_name,144
};145
}146
}147
if let PrinterTarget::WinSpooler(q) = target {148
if queue_name_says_tspl(q) {149
return Detection {150
protocol: PrinterProtocol::Tspl,151
source: DetectionSource::QueueName,152
model_key: q.trim().to_string(),153
model_name: Some(q.trim().to_string()),154
};155
}156
}157
Detection { protocol: PrinterProtocol::EscPos, source: DetectionSource::Default, model_key, model_name }158
}159
160
#[cfg(test)]161
mod tests {162
use super::*;163
164
const ALTEC: &str = "MFG:Altec;CMD:TSPL2;MDL:ATP-300 Pro;CLS:PRINTER;";165
166
fn usb(vid: u16, pid: u16) -> PrinterTarget {167
PrinterTarget::UsbDirect { vid, pid, bus: 3, address: 16 }168
}169
170
#[test]171
fn parses_altec_device_id() {172
let i = parse_ieee1284_id(ALTEC);173
assert_eq!(i.manufacturer.as_deref(), Some("Altec"));174
assert_eq!(i.model.as_deref(), Some("ATP-300 Pro"));175
assert_eq!(i.command_sets, vec!["TSPL2".to_string()]);176
}177
178
#[test]179
fn altec_is_tspl_with_model_key() {180
let d = detect(&usb(0x1203, 0x0231), Some(ALTEC));181
assert_eq!(d.protocol, PrinterProtocol::Tspl);182
assert_eq!(d.source, DetectionSource::DeviceId);183
assert_eq!(d.model_key, "Altec ATP-300 Pro");184
}185
186
#[test]187
fn long_keys_and_variants() {188
for id in [189
"MANUFACTURER:TSC;COMMAND SET:TSPL;MODEL:TTP-244 Pro;",190
"MFG:TSC;CMD:TSPL-EZ,ZPL2,EPL2;MDL:TE200;",191
"mfg:x;cmd:tspl2;mdl:y;",192
] {193
assert_eq!(detect(&usb(1, 2), Some(id)).protocol, PrinterProtocol::Tspl, "{id}");194
}195
}196
197
#[test]198
fn escpos_and_unknown_stay_escpos() {199
for id in [200
"MFG:EPSON;CMD:ESC/POS;MDL:TM-T20;",201
"MFG:Xprinter;CMD:ESCPOS,TSPL;MDL:XP-365B;", // multi-language: keep ESC/POS202
"MFG:Foo;MDL:Bar;",203
"",204
"garbage without fields",205
] {206
let d = detect(&usb(0x0416, 0x5011), Some(id));207
assert_eq!(d.protocol, PrinterProtocol::EscPos, "{id}");208
}209
let d = detect(&usb(0x0416, 0x5011), None);210
assert_eq!(d.protocol, PrinterProtocol::EscPos);211
assert_eq!(d.source, DetectionSource::Default);212
assert_eq!(d.model_key, "usb:0416:5011");213
}214
215
#[test]216
fn tsc_vendor_without_device_id_is_tspl() {217
let d = detect(&usb(0x1203, 0x0231), None);218
assert_eq!(d.protocol, PrinterProtocol::Tspl);219
assert_eq!(d.source, DetectionSource::UsbVendor);220
assert_eq!(d.model_key, "usb:1203:0231");221
}222
223
#[test]224
fn serial_and_plain_queues_are_escpos() {225
assert_eq!(detect(&PrinterTarget::Serial("COM3".into()), None).protocol, PrinterProtocol::EscPos);226
assert_eq!(227
detect(&PrinterTarget::WinSpooler("POS-58".into()), None).protocol,228
PrinterProtocol::EscPos229
);230
assert_eq!(231
detect(&PrinterTarget::WinSpooler("Altec ATP-300 Pro".into()), None).protocol,232
PrinterProtocol::Tspl233
);234
}235
}@@ -0,0 +1,835 @@
1
//! TSPL/TSPL2 output for label printers (first version: whole page as bitmap).
2
//!
3
//! The document is first encoded by the unchanged [`crate::escpos::EscPosEncoder`]
4
//! and that ESC/POS byte stream is rendered into a bitmap by a small emulator
5
//! (Font A 12×24 cells, ESC a alignment, GS ! size, ESC E bold, GS v 0 raster,
6
//! GS k barcodes, GS ( k QR codes, ESC d feeds, GS V cut = next label). This keeps
7
//! the label layout identical to the receipt layout, then
8
//! [`encode_labels`] wraps it in TSPL:
9
//!
10
//! ```text
11
//! SIZE w mm,h mm / GAP g mm,0 mm (BLINE for black marks, GAP 0,0 continuous)
12
//! DIRECTION d,0 / REFERENCE 0,0 / CLS / BITMAP x,y,wbytes,h,0,<data> / PRINT 1,1
13
//! ```
14
//!
15
//! References: Altec TSPL/TSPL2 programming manual (2023-1-9): SIZE p.1, GAP p.2,
16
//! GAPDETECT p.4, BLINEDETECT p.5, BLINE p.7, DIRECTION p.12, REFERENCE p.13,
17
//! CLS, BITMAP p.44 (bit 0 = black dot), PRINT; GETSETTING$ p.211; `<ESC>!?` p.82.
18
19
use ab_glyph::{Font, FontRef, PxScale, ScaleFont};
20
use image::{GrayImage, Luma};
21
22
use crate::dsl::{BarcodeSymbology, QrEcc};
23
use crate::label_format::{LabelFormat, MediaKind};
24
use crate::raster;
25
26
/// ESC/POS source resolution assumed by Posprint's column model (8 dots/mm).
27
pub const SOURCE_DOTS_PER_MM: f32 = 8.0;
28
const CELL_W: f32 = 12.0;
29
const CELL_H: f32 = 24.0;
30
const LINE_ADVANCE: f32 = 30.0;
31
32
/// Render an ESC/POS stream (as produced by `EscPosEncoder`) to bitmaps.
33
/// `source_width` is the printable width in source dots, `scale` the output
34
/// pixels per source dot. Each `GS V` cut starts a new page.
35
pub fn render_escpos(bytes: &[u8], source_width: u32, scale: f32) -> Vec<GrayImage> {
36
let mut r = Renderer::new(source_width, scale);
37
r.run(bytes);
38
r.finish()
39
}
40
41
struct Renderer {
42
font: FontRef<'static>,
43
scale: f32,
44
width: u32,
45
rows: Vec<u8>,
46
y: u32,
47
pages: Vec<GrayImage>,
48
align: u8,
49
bold: bool,
50
size_w: u8,
51
size_h: u8,
52
line: Vec<u8>,
53
after_graphic: bool,
54
bc_height: u8,
55
bc_hri: bool,
56
bc_module: u8,
57
qr_size: u8,
58
qr_ecc: QrEcc,
59
qr_data: Vec<u8>,
60
}
61
62
impl Renderer {
63
fn new(source_width: u32, scale: f32) -> Self {
64
let font = FontRef::try_from_slice(epaint_default_fonts::HACK_REGULAR).expect("bundled font");
65
Self {
66
font,
67
scale,
68
width: ((source_width.max(1) as f32) * scale).round().max(1.0) as u32,
69
rows: Vec::new(),
70
y: 0,
71
pages: Vec::new(),
72
align: 0,
73
bold: false,
74
size_w: 1,
75
size_h: 1,
76
line: Vec::new(),
77
after_graphic: false,
78
bc_height: 162,
79
bc_hri: false,
80
bc_module: 3,
81
qr_size: 3,
82
qr_ecc: QrEcc::L,
83
qr_data: Vec::new(),
84
}
85
}
86
87
fn px(&self, v: f32) -> u32 {
88
(v * self.scale).round().max(0.0) as u32
89
}
90
91
fn ensure_rows(&mut self, bottom: u32) {
92
let need = bottom as usize * self.width as usize;
93
if self.rows.len() < need {
94
self.rows.resize(need, 255);
95
}
96
}
97
98
fn set_dark(&mut self, x: u32, y: u32) {
99
if x < self.width {
100
self.ensure_rows(y + 1);
101
self.rows[y as usize * self.width as usize + x as usize] = 0;
102
}
103
}
104
105
fn align_x(&self, w: u32) -> u32 {
106
let free = self.width.saturating_sub(w);
107
match self.align {
108
1 => free / 2,
109
2 => free,
110
_ => 0,
111
}
112
}
113
114
fn blit(&mut self, img: &GrayImage) {
115
let x0 = self.align_x(img.width());
116
let y0 = self.y;
117
for (x, y, p) in img.enumerate_pixels() {
118
if p.0[0] < 128 {
119
self.set_dark(x0 + x, y0 + y);
120
}
121
}
122
self.y += img.height();
123
self.ensure_rows(self.y);
124
self.after_graphic = true;
125
}
126
127
fn flush_line(&mut self) {
128
let text = std::mem::take(&mut self.line);
129
if text.is_empty() {
130
if self.after_graphic {
131
// LF after a graphic flushes it; keep a small gap (1 mm at
132
// 8 dots/mm) instead of a full blank line to save label space.
133
self.after_graphic = false;
134
self.y += self.px(8.0);
135
self.ensure_rows(self.y);
136
return;
137
}
138
self.y += self.px(LINE_ADVANCE * self.size_h as f32);
139
self.ensure_rows(self.y);
140
return;
141
}
142
self.after_graphic = false;
143
let cw = CELL_W * self.scale * self.size_w as f32;
144
let ch = CELL_H * self.scale * self.size_h as f32;
145
let line_w = (cw * text.len() as f32).round() as u32;
146
let x0 = self.align_x(line_w) as f32;
147
let y0 = self.y as f32;
148
// Hack: advance ≈ 0.602 em; fit the advance to the cell width.
149
let gid = self.font.glyph_id('M');
150
let unscaled_adv = self.font.h_advance_unscaled(gid);
151
let upem = self.font.units_per_em().unwrap_or(2048.0);
152
let sx = cw * upem / unscaled_adv;
153
let sy = ch * 0.85 / ((self.font.ascent_unscaled() - self.font.descent_unscaled()) / upem);
154
let pxs = PxScale { x: sx / upem * upem, y: sy };
155
let scaled = self.font.as_scaled(pxs);
156
let baseline = y0 + (ch - (scaled.ascent() - scaled.descent())) / 2.0 + scaled.ascent();
157
let mut dots: Vec<(u32, u32)> = Vec::new();
158
for (i, b) in text.iter().enumerate() {
159
let c = *b as char;
160
if c == ' ' {
161
continue;
162
}
163
let glyph = scaled.scaled_glyph(c);
164
let mut glyph = glyph;
165
glyph.position = ab_glyph::point(x0 + cw * i as f32, baseline);
166
if let Some(outlined) = self.font.outline_glyph(glyph) {
167
let bounds = outlined.px_bounds();
168
outlined.draw(|gx, gy, cov| {
169
if cov >= 0.5 {
170
let x = bounds.min.x + gx as f32;
171
let y = bounds.min.y + gy as f32;
172
if x >= 0.0 && y >= 0.0 {
173
dots.push((x as u32, y as u32));
174
}
175
}
176
});
177
}
178
}
179
let bold_px = if self.bold || self.size_w > 1 { (self.scale.round() as u32).max(1) } else { 0 };
180
for (x, y) in dots {
181
self.set_dark(x, y);
182
for d in 1..=bold_px {
183
self.set_dark(x + d, y);
184
}
185
}
186
self.y += self.px(LINE_ADVANCE * self.size_h as f32).max(ch.ceil() as u32);
187
self.ensure_rows(self.y);
188
}
189
190
fn cut(&mut self) {
191
if !self.line.is_empty() {
192
self.flush_line();
193
}
194
let rows = std::mem::take(&mut self.rows);
195
let h = (rows.len() / self.width as usize) as u32;
196
if h > 0 {
197
if let Some(img) = GrayImage::from_raw(self.width, h, rows) {
198
self.pages.push(img);
199
}
200
}
201
self.y = 0;
202
self.after_graphic = false;
203
}
204
205
fn finish(mut self) -> Vec<GrayImage> {
206
self.cut();
207
self.pages
208
.into_iter()
209
.filter_map(trim_bottom)
210
.collect()
211
}
212
213
fn barcode(&mut self, m: u8, data: &[u8]) {
214
let sym = match m {
215
65 | 0 => Some(BarcodeSymbology::UpcA),
216
66 | 1 => Some(BarcodeSymbology::UpcE),
217
67 | 2 => Some(BarcodeSymbology::Ean13),
218
68 | 3 => Some(BarcodeSymbology::Ean8),
219
69 | 4 => Some(BarcodeSymbology::Code39),
220
70 | 5 => Some(BarcodeSymbology::Itf),
221
71 | 6 => Some(BarcodeSymbology::Codabar),
222
73 => Some(BarcodeSymbology::Code128),
223
_ => None,
224
};
225
let text = String::from_utf8_lossy(data).to_string();
226
let Some(sym) = sym else { return };
227
let height = self.px(self.bc_height as f32).max(1);
228
let Ok(img) = raster::render_barcode(sym, &text, height) else {
229
return;
230
};
231
// Integer module width so bars stay scannable after scaling.
232
let mut k = ((self.bc_module as f32) * self.scale).round().max(1.0) as u32;
233
while k > 1 && img.width() * k > self.width {
234
k -= 1;
235
}
236
let scaled = image::imageops::resize(&img, img.width() * k, img.height(), image::imageops::FilterType::Nearest);
237
let scaled = if scaled.width() > self.width {
238
raster::scale_gray_to_print_width(scaled, self.width)
239
} else {
240
scaled
241
};
242
self.blit(&scaled);
243
if self.bc_hri {
244
let saved = self.align;
245
self.line = text.into_bytes();
246
self.after_graphic = false;
247
self.align = 1;
248
self.flush_line();
249
self.align = saved;
250
self.after_graphic = true;
251
}
252
}
253
254
fn qr(&mut self) {
255
let data = String::from_utf8_lossy(&self.qr_data).to_string();
256
let module = ((self.qr_size.max(1) as f32) * self.scale).round().max(1.0) as u32;
257
if let Ok(img) = raster::render_qr(&data, None, self.qr_ecc, module) {
258
// Quiet zone of 2 modules so the code scans next to label edges/text.
259
let pad = module * 2;
260
let mut framed = GrayImage::from_pixel(img.width() + 2 * pad, img.height() + 2 * pad, Luma([255]));
261
image::imageops::overlay(&mut framed, &img, i64::from(pad), i64::from(pad));
262
self.blit(&framed);
263
}
264
}
265
266
fn raster(&mut self, wbytes: usize, h: usize, data: &[u8]) {
267
let w = (wbytes * 8) as u32;
268
let mut img = GrayImage::from_pixel(w.max(1), (h as u32).max(1), Luma([255]));
269
for y in 0..h {
270
for x in 0..w as usize {
271
let byte = data.get(y * wbytes + x / 8).copied().unwrap_or(0);
272
if byte & (0x80 >> (x % 8)) != 0 {
273
img.put_pixel(x as u32, y as u32, Luma([0]));
274
}
275
}
276
}
277
let nw = self.px(w as f32).max(1);
278
let nh = self.px(h as f32).max(1);
279
let img = if (self.scale - 1.0).abs() < f32::EPSILON {
280
img
281
} else {
282
image::imageops::resize(&img, nw, nh, image::imageops::FilterType::Triangle)
283
};
284
let img = threshold(&img);
285
self.blit(&img);
286
}
287
288
fn run(&mut self, b: &[u8]) {
289
let mut i = 0;
290
let get = |i: usize| b.get(i).copied().unwrap_or(0);
291
while i < b.len() {
292
let c = b[i];
293
match c {
294
0x1B => {
295
let cmd = get(i + 1);
296
match cmd {
297
b'@' => {
298
self.align = 0;
299
self.bold = false;
300
self.size_w = 1;
301
self.size_h = 1;
302
i += 2;
303
}
304
b'a' => {
305
self.align = get(i + 2) % 48 % 3;
306
i += 3;
307
}
308
b'E' => {
309
self.bold = get(i + 2) & 1 == 1;
310
i += 3;
311
}
312
b'd' => {
313
if !self.line.is_empty() {
314
self.flush_line();
315
}
316
self.after_graphic = false;
317
self.y += self.px(LINE_ADVANCE) * get(i + 2) as u32;
318
self.ensure_rows(self.y);
319
i += 3;
320
}
321
b't' | b'M' | b'-' | b'!' | b'2' => {
322
i += if cmd == b'2' { 2 } else { 3 };
323
}
324
_ => i += 2,
325
}
326
}
327
0x1D => {
328
let cmd = get(i + 1);
329
match cmd {
330
b'!' => {
331
let n = get(i + 2);
332
self.size_w = ((n >> 4) & 7) + 1;
333
self.size_h = (n & 7) + 1;
334
i += 3;
335
}
336
b'V' => {
337
let m = get(i + 2);
338
i += if m == 65 || m == 66 { 4 } else { 3 };
339
self.cut();
340
}
341
b'h' => {
342
self.bc_height = get(i + 2).max(1);
343
i += 3;
344
}
345
b'H' => {
346
self.bc_hri = get(i + 2) % 48 != 0;
347
i += 3;
348
}
349
b'w' => {
350
self.bc_module = get(i + 2).clamp(1, 6);
351
i += 3;
352
}
353
b'k' => {
354
let m = get(i + 2);
355
if m >= 65 {
356
let n = get(i + 3) as usize;
357
let start = (i + 4).min(b.len());
358
let end = (start + n).min(b.len());
359
let data = b[start..end].to_vec();
360
self.barcode(m, &data);
361
i = end;
362
} else {
363
let start = (i + 3).min(b.len());
364
let end = b[start..].iter().position(|&x| x == 0).map(|p| start + p).unwrap_or(b.len());
365
let data = b[start..end].to_vec();
366
self.barcode(m, &data);
367
i = (end + 1).min(b.len());
368
}
369
}
370
b'(' if get(i + 2) == b'k' => {
371
let len = get(i + 3) as usize | (get(i + 4) as usize) << 8;
372
let start = (i + 5).min(b.len());
373
let end = (start + len).min(b.len());
374
let p = &b[start..end];
375
if p.len() >= 3 && p[0] == 49 {
376
match p[1] {
377
67 => self.qr_size = p[2].clamp(1, 16),
378
69 => {
379
self.qr_ecc = match p[2] {
380
49 => QrEcc::M,
381
50 => QrEcc::Q,
382
51 => QrEcc::H,
383
_ => QrEcc::L,
384
}
385
}
386
80 => self.qr_data = p[3..].to_vec(),
387
81 => self.qr(),
388
_ => {}
389
}
390
}
391
i = end;
392
}
393
b'v' if get(i + 2) == 0x30 => {
394
let wb = get(i + 4) as usize | (get(i + 5) as usize) << 8;
395
let h = get(i + 6) as usize | (get(i + 7) as usize) << 8;
396
let start = (i + 8).min(b.len());
397
let end = (start + wb * h).min(b.len());
398
let data = b[start..end].to_vec();
399
if !self.line.is_empty() {
400
self.flush_line();
401
}
402
self.raster(wb, h, &data);
403
i = end;
404
}
405
_ => i += 2,
406
}
407
}
408
b'\n' => {
409
self.flush_line();
410
i += 1;
411
}
412
b'\r' => i += 1,
413
0x20..=0x7E => {
414
self.line.push(c);
415
i += 1;
416
}
417
_ => {
418
self.line.push(b'?');
419
i += 1;
420
}
421
}
422
}
423
}
424
}
425
426
fn threshold(img: &GrayImage) -> GrayImage {
427
let mut out = img.clone();
428
for p in out.pixels_mut() {
429
p.0[0] = if p.0[0] < 128 { 0 } else { 255 };
430
}
431
out
432
}
433
434
/// Drop trailing white rows (receipt feeds before a cut); `None` if blank.
435
fn trim_bottom(img: GrayImage) -> Option<GrayImage> {
436
let (w, h) = img.dimensions();
437
let mut last = None;
438
for y in (0..h).rev() {
439
if (0..w).any(|x| img.get_pixel(x, y).0[0] < 128) {
440
last = Some(y);
441
break;
442
}
443
}
444
let last = last?;
445
Some(image::imageops::crop_imm(&img, 0, 0, w, last + 1).to_image())
446
}
447
448
/// Scale (output dots per source dot) so the page fits the label width.
449
pub fn page_scale(source_width: u32, format: &LabelFormat) -> f32 {
450
let dpmm = format.dots_per_mm() as f32;
451
let natural = dpmm / SOURCE_DOTS_PER_MM;
452
let label_w = format.width_mm * dpmm;
453
let fit = label_w / source_width.max(1) as f32;
454
natural.min(fit)
455
}
456
457
fn fmt_mm(v: f32) -> String {
458
let s = format!("{:.2}", v);
459
let s = s.trim_end_matches('0').trim_end_matches('.');
460
s.to_string()
461
}
462
463
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
464
pub struct TsplOptions {
465
/// Send GAPDETECT/BLINEDETECT with the label size first (sensor calibration;
466
/// the printer feeds a few labels).
467
pub calibrate: bool,
468
}
469
470
/// TSPL header lines for a label format (CRLF terminated).
471
pub fn setup_commands(format: &LabelFormat, label_height_mm: f32, opts: TsplOptions) -> String {
472
let mut s = String::new();
473
s.push_str(&format!("SIZE {} mm,{} mm\r\n", fmt_mm(format.width_mm), fmt_mm(label_height_mm)));
474
match format.media {
475
MediaKind::Gap => s.push_str(&format!("GAP {} mm,0 mm\r\n", fmt_mm(format.gap_mm))),
476
MediaKind::BlackMark => s.push_str(&format!("BLINE {} mm,0 mm\r\n", fmt_mm(format.gap_mm))),
477
MediaKind::Continuous => s.push_str("GAP 0,0\r\n"),
478
}
479
if opts.calibrate {
480
let dpmm = format.dots_per_mm() as f32;
481
let x = (label_height_mm * dpmm).round() as u32;
482
let y = (format.gap_mm * dpmm).round() as u32;
483
match format.media {
484
MediaKind::Gap => s.push_str(&format!("GAPDETECT {x},{y}\r\n")),
485
MediaKind::BlackMark => s.push_str(&format!("BLINEDETECT {x},{y}\r\n")),
486
MediaKind::Continuous => {}
487
}
488
}
489
s.push_str(&format!("DIRECTION {},0\r\n", if format.rotate_180 { 1 } else { 0 }));
490
s.push_str("REFERENCE 0,0\r\n");
491
s
492
}
493
494
/// TSPL `BITMAP` data: 1 bit per dot, MSB first, **0 = black** (manual p.44).
495
pub fn bitmap_bytes(img: &GrayImage) -> (usize, Vec<u8>) {
496
let (w, h) = img.dimensions();
497
let wb = (w as usize).div_ceil(8);
498
let mut out = vec![0xFFu8; wb * h as usize];
499
for (x, y, p) in img.enumerate_pixels() {
500
if p.0[0] < 128 {
501
out[y as usize * wb + x as usize / 8] &= !(0x80 >> (x % 8));
502
}
503
}
504
(wb, out)
505
}
506
507
/// Build a complete TSPL job for already-rendered pages. Pages taller than the
508
/// label are split over several labels; each page is centred horizontally.
509
pub fn encode_pages(pages: &[GrayImage], format: &LabelFormat, opts: TsplOptions) -> Vec<u8> {
510
let dpmm = format.dots_per_mm();
511
let label_w = (format.width_mm * dpmm as f32).round() as u32;
512
let mut chunks: Vec<GrayImage> = Vec::new();
513
let continuous = format.media == MediaKind::Continuous;
514
let label_h = (format.height_mm * dpmm as f32).round().max(1.0) as u32;
515
for page in pages {
516
if continuous {
517
chunks.push(page.clone());
518
continue;
519
}
520
let mut y = 0;
521
while y < page.height() {
522
let h = label_h.min(page.height() - y);
523
chunks.push(image::imageops::crop_imm(page, 0, y, page.width(), h).to_image());
524
y += h;
525
}
526
}
527
let mut out = Vec::new();
528
let height_mm = |c: &GrayImage| {
529
if continuous {
530
(c.height() as f32 / dpmm as f32).max(5.0)
531
} else {
532
format.height_mm
533
}
534
};
535
let first_h = chunks.first().map(height_mm).unwrap_or(format.height_mm);
536
out.extend_from_slice(setup_commands(format, first_h, opts).as_bytes());
537
let mut current_h = first_h;
538
for c in &chunks {
539
let h_mm = height_mm(c);
540
if (h_mm - current_h).abs() > f32::EPSILON {
541
out.extend_from_slice(format!("SIZE {} mm,{} mm\r\n", fmt_mm(format.width_mm), fmt_mm(h_mm)).as_bytes());
542
current_h = h_mm;
543
}
544
let (wb, data) = bitmap_bytes(c);
545
let x = label_w.saturating_sub(c.width()) / 2;
546
out.extend_from_slice(b"CLS\r\n");
547
out.extend_from_slice(format!("BITMAP {x},0,{wb},{},0,", c.height()).as_bytes());
548
out.extend_from_slice(&data);
549
out.extend_from_slice(b"\r\nPRINT 1,1\r\n");
550
}
551
out
552
}
553
554
/// ESC/POS bytes (from `EscPosEncoder`) → TSPL job for `format`.
555
pub fn escpos_to_tspl(escpos: &[u8], source_width: u32, format: &LabelFormat, opts: TsplOptions) -> Vec<u8> {
556
let scale = page_scale(source_width, format);
557
let pages = render_escpos(escpos, source_width, scale);
558
encode_pages(&pages, format, opts)
559
}
560
561
/// TSPL status query `<ESC>!?` (manual p.82).
562
pub const STATUS_QUERY: &[u8] = &[0x1B, b'!', b'?'];
563
564
/// Settings that can be read back over a bidirectional link (manual p.211).
565
pub const QUERY_PAPER_WIDTH: &str = "OUT GETSETTING$(\"CONFIG\",\"TSPL\",\"PAPER WIDTH\")\r\n";
566
pub const QUERY_PAPER_SIZE: &str = "OUT GETSETTING$(\"CONFIG\",\"TSPL\",\"PAPER SIZE\")\r\n";
567
pub const QUERY_GAP_SIZE: &str = "OUT GETSETTING$(\"CONFIG\",\"TSPL\",\"GAP SIZE\")\r\n";
568
pub const QUERY_DPI: &str = "OUT GETSETTING$(\"SYSTEM\",\"INFORMATION\",\"DPI\")\r\n";
569
570
/// Status byte meaning (manual p.82), `None` = ready.
571
pub fn status_problem(byte: u8) -> Option<StatusProblem> {
572
if byte == 0 || byte == 0x20 {
573
return None;
574
}
575
Some(if byte & 0x01 != 0 {
576
StatusProblem::HeadOpen
577
} else if byte & 0x04 != 0 {
578
StatusProblem::OutOfPaper
579
} else if byte & 0x08 != 0 {
580
StatusProblem::OutOfRibbon
581
} else if byte & 0x02 != 0 {
582
StatusProblem::PaperJam
583
} else if byte & 0x10 != 0 {
584
StatusProblem::Paused
585
} else {
586
StatusProblem::Other
587
})
588
}
589
590
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
591
pub enum StatusProblem {
592
HeadOpen,
593
PaperJam,
594
OutOfPaper,
595
OutOfRibbon,
596
Paused,
597
Other,
598
}
599
600
/// Parse a length reply from GETSETTING$ into mm. Units are only trusted when
601
/// explicit (`mm`, `inch`/`"`, `dot`); a bare number is assumed to be dots only
602
/// when `dpmm` is known and the value is clearly in dots range. Returns `None`
603
/// when unsure, so the dialog asks the user instead.
604
pub fn parse_length_mm(reply: &str, dpmm: Option<u32>) -> Option<f32> {
605
let r = reply.trim().trim_matches(char::from(0)).trim().to_ascii_lowercase();
606
let num: String = r
607
.chars()
608
.skip_while(|c| !c.is_ascii_digit())
609
.take_while(|c| c.is_ascii_digit() || *c == '.')
610
.collect();
611
let v: f32 = num.parse().ok()?;
612
if !v.is_finite() || v <= 0.0 {
613
return None;
614
}
615
let mm = if r.contains("mm") {
616
v
617
} else if r.contains("inch") || r.contains('"') {
618
v * 25.4
619
} else if r.contains("dot") {
620
v / dpmm? as f32
621
} else {
622
return None;
623
};
624
Some(mm)
625
}
626
627
pub fn parse_dpi(reply: &str) -> Option<u16> {
628
let n: String = reply.chars().filter(|c| c.is_ascii_digit()).collect();
629
match n.parse::<u16>().ok()? {
630
200 | 203 => Some(203),
631
300 => Some(300),
632
600 => Some(600),
633
_ => None,
634
}
635
}
636
637
#[cfg(test)]
638
mod tests {
639
use super::*;
640
use crate::escpos::EscPosEncoder;
641
use crate::io::PosMetadata;
642
643
fn fmt(w: f32, h: f32) -> LabelFormat {
644
LabelFormat { width_mm: w, height_mm: h, gap_mm: 3.0, media: MediaKind::Gap, dpi: 300, rotate_180: false }
645
}
646
647
fn split_cmds(job: &[u8]) -> Vec<String> {
648
// Text lines only (BITMAP data is binary): keep the line prefix up to data.
649
let mut out = Vec::new();
650
let mut i = 0;
651
while i < job.len() {
652
let end = job[i..].windows(2).position(|w| w == b"\r\n").map(|p| i + p).unwrap_or(job.len());
653
let line = &job[i..end];
654
if line.starts_with(b"BITMAP ") {
655
let hdr: Vec<u8> = line.iter().take_while(|_| true).copied().collect();
656
// header = first 5 commas
657
let mut commas = 0;
658
let mut k = 0;
659
while k < hdr.len() && commas < 5 {
660
if hdr[k] == b',' {
661
commas += 1;
662
}
663
k += 1;
664
}
665
let head = String::from_utf8_lossy(&hdr[..k]).to_string();
666
let parts: Vec<usize> = head.trim_start_matches("BITMAP ").trim_end_matches(',').split(',').map(|s| s.parse().unwrap()).collect();
667
let data_len = parts[2] * parts[3];
668
out.push(head);
669
i = i + k + data_len;
670
assert_eq!(&job[i..i + 2], b"\r\n", "bitmap data length must match header");
671
i += 2;
672
continue;
673
}
674
out.push(String::from_utf8_lossy(line).to_string());
675
i = end + 2;
676
}
677
out
678
}
679
680
#[test]
681
fn header_matches_spec_syntax() {
682
let s = setup_commands(&fmt(50.0, 30.0), 30.0, TsplOptions::default());
683
assert_eq!(s, "SIZE 50 mm,30 mm\r\nGAP 3 mm,0 mm\r\nDIRECTION 0,0\r\nREFERENCE 0,0\r\n");
684
let mut f = fmt(101.6, 25.4);
685
f.media = MediaKind::BlackMark;
686
f.gap_mm = 2.5;
687
f.rotate_180 = true;
688
let s = setup_commands(&f, 25.4, TsplOptions { calibrate: true });
689
assert_eq!(
690
s,
691
"SIZE 101.6 mm,25.4 mm\r\nBLINE 2.5 mm,0 mm\r\nBLINEDETECT 305,30\r\nDIRECTION 1,0\r\nREFERENCE 0,0\r\n"
692
);
693
f.media = MediaKind::Continuous;
694
let s = setup_commands(&f, 40.0, TsplOptions { calibrate: true });
695
assert!(s.contains("GAP 0,0\r\n") && !s.contains("DETECT"));
696
let g = setup_commands(&fmt(50.0, 30.0), 30.0, TsplOptions { calibrate: true });
697
assert!(g.contains("GAPDETECT 360,36\r\n"));
698
}
699
700
#[test]
701
fn bitmap_zero_is_black() {
702
let mut img = GrayImage::from_pixel(10, 2, Luma([255]));
703
img.put_pixel(0, 0, Luma([0]));
704
img.put_pixel(9, 1, Luma([0]));
705
let (wb, data) = bitmap_bytes(&img);
706
assert_eq!(wb, 2);
707
assert_eq!(data, vec![0x7F, 0xFF, 0xFF, 0xBF]);
708
}
709
710
#[test]
711
fn full_job_structure() {
712
let doc = crate::dsl::parse("# Hello\nWorld\n@barcode CODE128 ABC123\n@qr hi\n@cut\n").unwrap();
713
let md = PosMetadata { page_width_mm: 58.0, ..Default::default() };
714
let mut enc = EscPosEncoder::new(md.clone());
715
let esc = enc.encode_document(&doc).unwrap().to_vec();
716
let job = escpos_to_tspl(&esc, md.printable_dots() as u32, &fmt(100.0, 150.0), TsplOptions::default());
717
let cmds = split_cmds(&job);
718
assert_eq!(cmds[0], "SIZE 100 mm,150 mm");
719
assert_eq!(cmds[1], "GAP 3 mm,0 mm");
720
assert_eq!(cmds[2], "DIRECTION 0,0");
721
assert_eq!(cmds[3], "REFERENCE 0,0");
722
assert_eq!(cmds[4], "CLS");
723
assert!(cmds[5].starts_with("BITMAP "));
724
assert_eq!(cmds[6], "PRINT 1,1");
725
assert_eq!(cmds.len(), 7);
726
// 58 mm doc (384 source dots) at 300 dpi → 576 dots = 72 bytes, centred on 1200 dots.
727
let parts: Vec<u32> = cmds[5][7..].trim_end_matches(',').split(',').map(|s| s.parse().unwrap()).collect();
728
assert_eq!(parts[2], 72);
729
assert_eq!(parts[0], (1200 - 576) / 2);
730
assert_eq!(parts[1], 0);
731
assert_eq!(parts[4], 0);
732
assert!(parts[3] > 100);
733
}
734
735
#[test]
736
fn content_is_drawn() {
737
let doc = crate::dsl::parse("HELLO\n").unwrap();
738
let md = PosMetadata { page_width_mm: 80.0, ..Default::default() };
739
let esc = EscPosEncoder::new(md.clone()).encode_document(&doc).unwrap().to_vec();
740
let pages = render_escpos(&esc, md.printable_dots() as u32, 1.0);
741
assert_eq!(pages.len(), 1);
742
let p = &pages[0];
743
assert_eq!(p.width(), 576);
744
let dark = p.pixels().filter(|px| px.0[0] == 0).count();
745
assert!(dark > 100, "text must produce dots, got {dark}");
746
// Left aligned: nothing right of the 5 chars (60 dots).
747
assert!(p.enumerate_pixels().all(|(x, _, px)| x < 64 || px.0[0] == 255));
748
}
749
750
#[test]
751
fn center_and_right_alignment() {
752
for (dsl, check) in [(":center:\nX\n", 1u8), (":right:\nX\n", 2u8)] {
753
let doc = crate::dsl::parse(dsl).unwrap();
754
let md = PosMetadata { page_width_mm: 80.0, ..Default::default() };
755
let esc = EscPosEncoder::new(md.clone()).encode_document(&doc).unwrap().to_vec();
756
let p = &render_escpos(&esc, 576, 1.0)[0];
757
let xs: Vec<u32> = p.enumerate_pixels().filter(|(_, _, px)| px.0[0] == 0).map(|(x, _, _)| x).collect();
758
let min = *xs.iter().min().unwrap();
759
if check == 1 {
760
assert!((276..300).contains(&min), "center min {min}");
761
} else {
762
assert!(min >= 560, "right min {min}");
763
}
764
}
765
}
766
767
#[test]
768
fn cut_starts_new_label_and_trailing_feed_is_trimmed() {
769
let doc = crate::dsl::parse("A\n@feed 5\n@cut\nB\n@cut\n@feed 3\n@cut\n").unwrap();
770
let md = PosMetadata { page_width_mm: 58.0, ..Default::default() };
771
let esc = EscPosEncoder::new(md.clone()).encode_document(&doc).unwrap().to_vec();
772
let pages = render_escpos(&esc, 384, 1.5);
773
assert_eq!(pages.len(), 2, "blank page after last cut is skipped");
774
assert!(pages[0].height() < 40, "feed before cut trimmed: {}", pages[0].height());
775
let job = encode_pages(&pages, &fmt(60.0, 40.0), TsplOptions::default());
776
assert_eq!(split_cmds(&job).iter().filter(|c| *c == "PRINT 1,1").count(), 2);
777
}
778
779
#[test]
780
fn tall_page_splits_over_labels() {
781
let img = GrayImage::from_pixel(100, 250, Luma([0]));
782
let f = LabelFormat { width_mm: 20.0, height_mm: 10.0, gap_mm: 2.0, media: MediaKind::Gap, dpi: 203, rotate_180: false };
783
// 10 mm @ 8 dots/mm = 80 dots → 4 labels (80+80+80+10).
784
let job = encode_pages(&[img], &f, TsplOptions::default());
785
let cmds = split_cmds(&job);
786
let bitmaps: Vec<&String> = cmds.iter().filter(|c| c.starts_with("BITMAP")).collect();
787
assert_eq!(bitmaps.len(), 4);
788
assert_eq!(bitmaps[0].as_str(), "BITMAP 30,0,13,80,0,");
789
assert_eq!(bitmaps[3].as_str(), "BITMAP 30,0,13,10,0,");
790
}
791
792
#[test]
793
fn continuous_uses_content_height() {
794
let img = GrayImage::from_pixel(80, 400, Luma([0]));
795
let f = LabelFormat { width_mm: 10.0, height_mm: 10.0, gap_mm: 0.0, media: MediaKind::Continuous, dpi: 203, rotate_180: false };
796
let cmds = split_cmds(&encode_pages(&[img], &f, TsplOptions::default()));
797
assert_eq!(cmds[0], "SIZE 10 mm,50 mm");
798
assert_eq!(cmds[1], "GAP 0,0");
799
}
800
801
#[test]
802
fn wide_doc_shrinks_to_label() {
803
let f = fmt(40.0, 30.0);
804
let s = page_scale(576, &f);
805
assert!((576.0 * s - 480.0).abs() < 0.5);
806
assert!((page_scale(384, &fmt(100.0, 50.0)) - 1.5).abs() < 1e-6);
807
}
808
809
#[test]
810
fn barcodes_and_raster_render() {
811
let doc = crate::dsl::parse("@barcode CODE128 ABC\n@barcode RASTER CODE128 ABC\n@qr RASTER hi scale=4\n").unwrap();
812
let md = PosMetadata { page_width_mm: 58.0, ..Default::default() };
813
let esc = EscPosEncoder::new(md.clone()).encode_document(&doc).unwrap().to_vec();
814
let pages = render_escpos(&esc, 384, 1.5);
815
assert_eq!(pages.len(), 1);
816
assert!(pages[0].height() > 200);
817
assert_eq!(pages[0].width(), 576);
818
}
819
820
#[test]
821
fn parses_replies_conservatively() {
822
assert_eq!(parse_length_mm("50.00 mm", None), Some(50.0));
823
assert_eq!(parse_length_mm("2.00 inch", None), Some(50.8));
824
assert_eq!(parse_length_mm("600 dot", Some(12)), Some(50.0));
825
assert_eq!(parse_length_mm("600 dot", None), None);
826
assert_eq!(parse_length_mm("600", Some(12)), None);
827
assert_eq!(parse_length_mm("", None), None);
828
assert_eq!(parse_dpi("300\r\n"), Some(300));
829
assert_eq!(parse_dpi("203"), Some(203));
830
assert_eq!(parse_dpi("x"), None);
831
assert_eq!(status_problem(0), None);
832
assert_eq!(status_problem(0x04), Some(StatusProblem::OutOfPaper));
833
assert_eq!(status_problem(0x05), Some(StatusProblem::HeadOpen));
834
}
835
}
@@ -0,0 +1,835 @@1
//! TSPL/TSPL2 output for label printers (first version: whole page as bitmap).2
//!3
//! The document is first encoded by the unchanged [`crate::escpos::EscPosEncoder`]4
//! and that ESC/POS byte stream is rendered into a bitmap by a small emulator5
//! (Font A 12×24 cells, ESC a alignment, GS ! size, ESC E bold, GS v 0 raster,6
//! GS k barcodes, GS ( k QR codes, ESC d feeds, GS V cut = next label). This keeps7
//! the label layout identical to the receipt layout, then8
//! [`encode_labels`] wraps it in TSPL:9
//!10
//! ```text11
//! SIZE w mm,h mm / GAP g mm,0 mm (BLINE for black marks, GAP 0,0 continuous)12
//! DIRECTION d,0 / REFERENCE 0,0 / CLS / BITMAP x,y,wbytes,h,0,<data> / PRINT 1,113
//! ```14
//!15
//! References: Altec TSPL/TSPL2 programming manual (2023-1-9): SIZE p.1, GAP p.2,16
//! GAPDETECT p.4, BLINEDETECT p.5, BLINE p.7, DIRECTION p.12, REFERENCE p.13,17
//! CLS, BITMAP p.44 (bit 0 = black dot), PRINT; GETSETTING$ p.211; `<ESC>!?` p.82.18
19
use ab_glyph::{Font, FontRef, PxScale, ScaleFont};20
use image::{GrayImage, Luma};21
22
use crate::dsl::{BarcodeSymbology, QrEcc};23
use crate::label_format::{LabelFormat, MediaKind};24
use crate::raster;25
26
/// ESC/POS source resolution assumed by Posprint's column model (8 dots/mm).27
pub const SOURCE_DOTS_PER_MM: f32 = 8.0;28
const CELL_W: f32 = 12.0;29
const CELL_H: f32 = 24.0;30
const LINE_ADVANCE: f32 = 30.0;31
32
/// Render an ESC/POS stream (as produced by `EscPosEncoder`) to bitmaps.33
/// `source_width` is the printable width in source dots, `scale` the output34
/// pixels per source dot. Each `GS V` cut starts a new page.35
pub fn render_escpos(bytes: &[u8], source_width: u32, scale: f32) -> Vec<GrayImage> {36
let mut r = Renderer::new(source_width, scale);37
r.run(bytes);38
r.finish()39
}40
41
struct Renderer {42
font: FontRef<'static>,43
scale: f32,44
width: u32,45
rows: Vec<u8>,46
y: u32,47
pages: Vec<GrayImage>,48
align: u8,49
bold: bool,50
size_w: u8,51
size_h: u8,52
line: Vec<u8>,53
after_graphic: bool,54
bc_height: u8,55
bc_hri: bool,56
bc_module: u8,57
qr_size: u8,58
qr_ecc: QrEcc,59
qr_data: Vec<u8>,60
}61
62
impl Renderer {63
fn new(source_width: u32, scale: f32) -> Self {64
let font = FontRef::try_from_slice(epaint_default_fonts::HACK_REGULAR).expect("bundled font");65
Self {66
font,67
scale,68
width: ((source_width.max(1) as f32) * scale).round().max(1.0) as u32,69
rows: Vec::new(),70
y: 0,71
pages: Vec::new(),72
align: 0,73
bold: false,74
size_w: 1,75
size_h: 1,76
line: Vec::new(),77
after_graphic: false,78
bc_height: 162,79
bc_hri: false,80
bc_module: 3,81
qr_size: 3,82
qr_ecc: QrEcc::L,83
qr_data: Vec::new(),84
}85
}86
87
fn px(&self, v: f32) -> u32 {88
(v * self.scale).round().max(0.0) as u3289
}90
91
fn ensure_rows(&mut self, bottom: u32) {92
let need = bottom as usize * self.width as usize;93
if self.rows.len() < need {94
self.rows.resize(need, 255);95
}96
}97
98
fn set_dark(&mut self, x: u32, y: u32) {99
if x < self.width {100
self.ensure_rows(y + 1);101
self.rows[y as usize * self.width as usize + x as usize] = 0;102
}103
}104
105
fn align_x(&self, w: u32) -> u32 {106
let free = self.width.saturating_sub(w);107
match self.align {108
1 => free / 2,109
2 => free,110
_ => 0,111
}112
}113
114
fn blit(&mut self, img: &GrayImage) {115
let x0 = self.align_x(img.width());116
let y0 = self.y;117
for (x, y, p) in img.enumerate_pixels() {118
if p.0[0] < 128 {119
self.set_dark(x0 + x, y0 + y);120
}121
}122
self.y += img.height();123
self.ensure_rows(self.y);124
self.after_graphic = true;125
}126
127
fn flush_line(&mut self) {128
let text = std::mem::take(&mut self.line);129
if text.is_empty() {130
if self.after_graphic {131
// LF after a graphic flushes it; keep a small gap (1 mm at132
// 8 dots/mm) instead of a full blank line to save label space.133
self.after_graphic = false;134
self.y += self.px(8.0);135
self.ensure_rows(self.y);136
return;137
}138
self.y += self.px(LINE_ADVANCE * self.size_h as f32);139
self.ensure_rows(self.y);140
return;141
}142
self.after_graphic = false;143
let cw = CELL_W * self.scale * self.size_w as f32;144
let ch = CELL_H * self.scale * self.size_h as f32;145
let line_w = (cw * text.len() as f32).round() as u32;146
let x0 = self.align_x(line_w) as f32;147
let y0 = self.y as f32;148
// Hack: advance ≈ 0.602 em; fit the advance to the cell width.149
let gid = self.font.glyph_id('M');150
let unscaled_adv = self.font.h_advance_unscaled(gid);151
let upem = self.font.units_per_em().unwrap_or(2048.0);152
let sx = cw * upem / unscaled_adv;153
let sy = ch * 0.85 / ((self.font.ascent_unscaled() - self.font.descent_unscaled()) / upem);154
let pxs = PxScale { x: sx / upem * upem, y: sy };155
let scaled = self.font.as_scaled(pxs);156
let baseline = y0 + (ch - (scaled.ascent() - scaled.descent())) / 2.0 + scaled.ascent();157
let mut dots: Vec<(u32, u32)> = Vec::new();158
for (i, b) in text.iter().enumerate() {159
let c = *b as char;160
if c == ' ' {161
continue;162
}163
let glyph = scaled.scaled_glyph(c);164
let mut glyph = glyph;165
glyph.position = ab_glyph::point(x0 + cw * i as f32, baseline);166
if let Some(outlined) = self.font.outline_glyph(glyph) {167
let bounds = outlined.px_bounds();168
outlined.draw(|gx, gy, cov| {169
if cov >= 0.5 {170
let x = bounds.min.x + gx as f32;171
let y = bounds.min.y + gy as f32;172
if x >= 0.0 && y >= 0.0 {173
dots.push((x as u32, y as u32));174
}175
}176
});177
}178
}179
let bold_px = if self.bold || self.size_w > 1 { (self.scale.round() as u32).max(1) } else { 0 };180
for (x, y) in dots {181
self.set_dark(x, y);182
for d in 1..=bold_px {183
self.set_dark(x + d, y);184
}185
}186
self.y += self.px(LINE_ADVANCE * self.size_h as f32).max(ch.ceil() as u32);187
self.ensure_rows(self.y);188
}189
190
fn cut(&mut self) {191
if !self.line.is_empty() {192
self.flush_line();193
}194
let rows = std::mem::take(&mut self.rows);195
let h = (rows.len() / self.width as usize) as u32;196
if h > 0 {197
if let Some(img) = GrayImage::from_raw(self.width, h, rows) {198
self.pages.push(img);199
}200
}201
self.y = 0;202
self.after_graphic = false;203
}204
205
fn finish(mut self) -> Vec<GrayImage> {206
self.cut();207
self.pages208
.into_iter()209
.filter_map(trim_bottom)210
.collect()211
}212
213
fn barcode(&mut self, m: u8, data: &[u8]) {214
let sym = match m {215
65 | 0 => Some(BarcodeSymbology::UpcA),216
66 | 1 => Some(BarcodeSymbology::UpcE),217
67 | 2 => Some(BarcodeSymbology::Ean13),218
68 | 3 => Some(BarcodeSymbology::Ean8),219
69 | 4 => Some(BarcodeSymbology::Code39),220
70 | 5 => Some(BarcodeSymbology::Itf),221
71 | 6 => Some(BarcodeSymbology::Codabar),222
73 => Some(BarcodeSymbology::Code128),223
_ => None,224
};225
let text = String::from_utf8_lossy(data).to_string();226
let Some(sym) = sym else { return };227
let height = self.px(self.bc_height as f32).max(1);228
let Ok(img) = raster::render_barcode(sym, &text, height) else {229
return;230
};231
// Integer module width so bars stay scannable after scaling.232
let mut k = ((self.bc_module as f32) * self.scale).round().max(1.0) as u32;233
while k > 1 && img.width() * k > self.width {234
k -= 1;235
}236
let scaled = image::imageops::resize(&img, img.width() * k, img.height(), image::imageops::FilterType::Nearest);237
let scaled = if scaled.width() > self.width {238
raster::scale_gray_to_print_width(scaled, self.width)239
} else {240
scaled241
};242
self.blit(&scaled);243
if self.bc_hri {244
let saved = self.align;245
self.line = text.into_bytes();246
self.after_graphic = false;247
self.align = 1;248
self.flush_line();249
self.align = saved;250
self.after_graphic = true;251
}252
}253
254
fn qr(&mut self) {255
let data = String::from_utf8_lossy(&self.qr_data).to_string();256
let module = ((self.qr_size.max(1) as f32) * self.scale).round().max(1.0) as u32;257
if let Ok(img) = raster::render_qr(&data, None, self.qr_ecc, module) {258
// Quiet zone of 2 modules so the code scans next to label edges/text.259
let pad = module * 2;260
let mut framed = GrayImage::from_pixel(img.width() + 2 * pad, img.height() + 2 * pad, Luma([255]));261
image::imageops::overlay(&mut framed, &img, i64::from(pad), i64::from(pad));262
self.blit(&framed);263
}264
}265
266
fn raster(&mut self, wbytes: usize, h: usize, data: &[u8]) {267
let w = (wbytes * 8) as u32;268
let mut img = GrayImage::from_pixel(w.max(1), (h as u32).max(1), Luma([255]));269
for y in 0..h {270
for x in 0..w as usize {271
let byte = data.get(y * wbytes + x / 8).copied().unwrap_or(0);272
if byte & (0x80 >> (x % 8)) != 0 {273
img.put_pixel(x as u32, y as u32, Luma([0]));274
}275
}276
}277
let nw = self.px(w as f32).max(1);278
let nh = self.px(h as f32).max(1);279
let img = if (self.scale - 1.0).abs() < f32::EPSILON {280
img281
} else {282
image::imageops::resize(&img, nw, nh, image::imageops::FilterType::Triangle)283
};284
let img = threshold(&img);285
self.blit(&img);286
}287
288
fn run(&mut self, b: &[u8]) {289
let mut i = 0;290
let get = |i: usize| b.get(i).copied().unwrap_or(0);291
while i < b.len() {292
let c = b[i];293
match c {294
0x1B => {295
let cmd = get(i + 1);296
match cmd {297
b'@' => {298
self.align = 0;299
self.bold = false;300
self.size_w = 1;301
self.size_h = 1;302
i += 2;303
}304
b'a' => {305
self.align = get(i + 2) % 48 % 3;306
i += 3;307
}308
b'E' => {309
self.bold = get(i + 2) & 1 == 1;310
i += 3;311
}312
b'd' => {313
if !self.line.is_empty() {314
self.flush_line();315
}316
self.after_graphic = false;317
self.y += self.px(LINE_ADVANCE) * get(i + 2) as u32;318
self.ensure_rows(self.y);319
i += 3;320
}321
b't' | b'M' | b'-' | b'!' | b'2' => {322
i += if cmd == b'2' { 2 } else { 3 };323
}324
_ => i += 2,325
}326
}327
0x1D => {328
let cmd = get(i + 1);329
match cmd {330
b'!' => {331
let n = get(i + 2);332
self.size_w = ((n >> 4) & 7) + 1;333
self.size_h = (n & 7) + 1;334
i += 3;335
}336
b'V' => {337
let m = get(i + 2);338
i += if m == 65 || m == 66 { 4 } else { 3 };339
self.cut();340
}341
b'h' => {342
self.bc_height = get(i + 2).max(1);343
i += 3;344
}345
b'H' => {346
self.bc_hri = get(i + 2) % 48 != 0;347
i += 3;348
}349
b'w' => {350
self.bc_module = get(i + 2).clamp(1, 6);351
i += 3;352
}353
b'k' => {354
let m = get(i + 2);355
if m >= 65 {356
let n = get(i + 3) as usize;357
let start = (i + 4).min(b.len());358
let end = (start + n).min(b.len());359
let data = b[start..end].to_vec();360
self.barcode(m, &data);361
i = end;362
} else {363
let start = (i + 3).min(b.len());364
let end = b[start..].iter().position(|&x| x == 0).map(|p| start + p).unwrap_or(b.len());365
let data = b[start..end].to_vec();366
self.barcode(m, &data);367
i = (end + 1).min(b.len());368
}369
}370
b'(' if get(i + 2) == b'k' => {371
let len = get(i + 3) as usize | (get(i + 4) as usize) << 8;372
let start = (i + 5).min(b.len());373
let end = (start + len).min(b.len());374
let p = &b[start..end];375
if p.len() >= 3 && p[0] == 49 {376
match p[1] {377
67 => self.qr_size = p[2].clamp(1, 16),378
69 => {379
self.qr_ecc = match p[2] {380
49 => QrEcc::M,381
50 => QrEcc::Q,382
51 => QrEcc::H,383
_ => QrEcc::L,384
}385
}386
80 => self.qr_data = p[3..].to_vec(),387
81 => self.qr(),388
_ => {}389
}390
}391
i = end;392
}393
b'v' if get(i + 2) == 0x30 => {394
let wb = get(i + 4) as usize | (get(i + 5) as usize) << 8;395
let h = get(i + 6) as usize | (get(i + 7) as usize) << 8;396
let start = (i + 8).min(b.len());397
let end = (start + wb * h).min(b.len());398
let data = b[start..end].to_vec();399
if !self.line.is_empty() {400
self.flush_line();401
}402
self.raster(wb, h, &data);403
i = end;404
}405
_ => i += 2,406
}407
}408
b'\n' => {409
self.flush_line();410
i += 1;411
}412
b'\r' => i += 1,413
0x20..=0x7E => {414
self.line.push(c);415
i += 1;416
}417
_ => {418
self.line.push(b'?');419
i += 1;420
}421
}422
}423
}424
}425
426
fn threshold(img: &GrayImage) -> GrayImage {427
let mut out = img.clone();428
for p in out.pixels_mut() {429
p.0[0] = if p.0[0] < 128 { 0 } else { 255 };430
}431
out432
}433
434
/// Drop trailing white rows (receipt feeds before a cut); `None` if blank.435
fn trim_bottom(img: GrayImage) -> Option<GrayImage> {436
let (w, h) = img.dimensions();437
let mut last = None;438
for y in (0..h).rev() {439
if (0..w).any(|x| img.get_pixel(x, y).0[0] < 128) {440
last = Some(y);441
break;442
}443
}444
let last = last?;445
Some(image::imageops::crop_imm(&img, 0, 0, w, last + 1).to_image())446
}447
448
/// Scale (output dots per source dot) so the page fits the label width.449
pub fn page_scale(source_width: u32, format: &LabelFormat) -> f32 {450
let dpmm = format.dots_per_mm() as f32;451
let natural = dpmm / SOURCE_DOTS_PER_MM;452
let label_w = format.width_mm * dpmm;453
let fit = label_w / source_width.max(1) as f32;454
natural.min(fit)455
}456
457
fn fmt_mm(v: f32) -> String {458
let s = format!("{:.2}", v);459
let s = s.trim_end_matches('0').trim_end_matches('.');460
s.to_string()461
}462
463
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]464
pub struct TsplOptions {465
/// Send GAPDETECT/BLINEDETECT with the label size first (sensor calibration;466
/// the printer feeds a few labels).467
pub calibrate: bool,468
}469
470
/// TSPL header lines for a label format (CRLF terminated).471
pub fn setup_commands(format: &LabelFormat, label_height_mm: f32, opts: TsplOptions) -> String {472
let mut s = String::new();473
s.push_str(&format!("SIZE {} mm,{} mm\r\n", fmt_mm(format.width_mm), fmt_mm(label_height_mm)));474
match format.media {475
MediaKind::Gap => s.push_str(&format!("GAP {} mm,0 mm\r\n", fmt_mm(format.gap_mm))),476
MediaKind::BlackMark => s.push_str(&format!("BLINE {} mm,0 mm\r\n", fmt_mm(format.gap_mm))),477
MediaKind::Continuous => s.push_str("GAP 0,0\r\n"),478
}479
if opts.calibrate {480
let dpmm = format.dots_per_mm() as f32;481
let x = (label_height_mm * dpmm).round() as u32;482
let y = (format.gap_mm * dpmm).round() as u32;483
match format.media {484
MediaKind::Gap => s.push_str(&format!("GAPDETECT {x},{y}\r\n")),485
MediaKind::BlackMark => s.push_str(&format!("BLINEDETECT {x},{y}\r\n")),486
MediaKind::Continuous => {}487
}488
}489
s.push_str(&format!("DIRECTION {},0\r\n", if format.rotate_180 { 1 } else { 0 }));490
s.push_str("REFERENCE 0,0\r\n");491
s492
}493
494
/// TSPL `BITMAP` data: 1 bit per dot, MSB first, **0 = black** (manual p.44).495
pub fn bitmap_bytes(img: &GrayImage) -> (usize, Vec<u8>) {496
let (w, h) = img.dimensions();497
let wb = (w as usize).div_ceil(8);498
let mut out = vec![0xFFu8; wb * h as usize];499
for (x, y, p) in img.enumerate_pixels() {500
if p.0[0] < 128 {501
out[y as usize * wb + x as usize / 8] &= !(0x80 >> (x % 8));502
}503
}504
(wb, out)505
}506
507
/// Build a complete TSPL job for already-rendered pages. Pages taller than the508
/// label are split over several labels; each page is centred horizontally.509
pub fn encode_pages(pages: &[GrayImage], format: &LabelFormat, opts: TsplOptions) -> Vec<u8> {510
let dpmm = format.dots_per_mm();511
let label_w = (format.width_mm * dpmm as f32).round() as u32;512
let mut chunks: Vec<GrayImage> = Vec::new();513
let continuous = format.media == MediaKind::Continuous;514
let label_h = (format.height_mm * dpmm as f32).round().max(1.0) as u32;515
for page in pages {516
if continuous {517
chunks.push(page.clone());518
continue;519
}520
let mut y = 0;521
while y < page.height() {522
let h = label_h.min(page.height() - y);523
chunks.push(image::imageops::crop_imm(page, 0, y, page.width(), h).to_image());524
y += h;525
}526
}527
let mut out = Vec::new();528
let height_mm = |c: &GrayImage| {529
if continuous {530
(c.height() as f32 / dpmm as f32).max(5.0)531
} else {532
format.height_mm533
}534
};535
let first_h = chunks.first().map(height_mm).unwrap_or(format.height_mm);536
out.extend_from_slice(setup_commands(format, first_h, opts).as_bytes());537
let mut current_h = first_h;538
for c in &chunks {539
let h_mm = height_mm(c);540
if (h_mm - current_h).abs() > f32::EPSILON {541
out.extend_from_slice(format!("SIZE {} mm,{} mm\r\n", fmt_mm(format.width_mm), fmt_mm(h_mm)).as_bytes());542
current_h = h_mm;543
}544
let (wb, data) = bitmap_bytes(c);545
let x = label_w.saturating_sub(c.width()) / 2;546
out.extend_from_slice(b"CLS\r\n");547
out.extend_from_slice(format!("BITMAP {x},0,{wb},{},0,", c.height()).as_bytes());548
out.extend_from_slice(&data);549
out.extend_from_slice(b"\r\nPRINT 1,1\r\n");550
}551
out552
}553
554
/// ESC/POS bytes (from `EscPosEncoder`) → TSPL job for `format`.555
pub fn escpos_to_tspl(escpos: &[u8], source_width: u32, format: &LabelFormat, opts: TsplOptions) -> Vec<u8> {556
let scale = page_scale(source_width, format);557
let pages = render_escpos(escpos, source_width, scale);558
encode_pages(&pages, format, opts)559
}560
561
/// TSPL status query `<ESC>!?` (manual p.82).562
pub const STATUS_QUERY: &[u8] = &[0x1B, b'!', b'?'];563
564
/// Settings that can be read back over a bidirectional link (manual p.211).565
pub const QUERY_PAPER_WIDTH: &str = "OUT GETSETTING$(\"CONFIG\",\"TSPL\",\"PAPER WIDTH\")\r\n";566
pub const QUERY_PAPER_SIZE: &str = "OUT GETSETTING$(\"CONFIG\",\"TSPL\",\"PAPER SIZE\")\r\n";567
pub const QUERY_GAP_SIZE: &str = "OUT GETSETTING$(\"CONFIG\",\"TSPL\",\"GAP SIZE\")\r\n";568
pub const QUERY_DPI: &str = "OUT GETSETTING$(\"SYSTEM\",\"INFORMATION\",\"DPI\")\r\n";569
570
/// Status byte meaning (manual p.82), `None` = ready.571
pub fn status_problem(byte: u8) -> Option<StatusProblem> {572
if byte == 0 || byte == 0x20 {573
return None;574
}575
Some(if byte & 0x01 != 0 {576
StatusProblem::HeadOpen577
} else if byte & 0x04 != 0 {578
StatusProblem::OutOfPaper579
} else if byte & 0x08 != 0 {580
StatusProblem::OutOfRibbon581
} else if byte & 0x02 != 0 {582
StatusProblem::PaperJam583
} else if byte & 0x10 != 0 {584
StatusProblem::Paused585
} else {586
StatusProblem::Other587
})588
}589
590
#[derive(Debug, Clone, Copy, PartialEq, Eq)]591
pub enum StatusProblem {592
HeadOpen,593
PaperJam,594
OutOfPaper,595
OutOfRibbon,596
Paused,597
Other,598
}599
600
/// Parse a length reply from GETSETTING$ into mm. Units are only trusted when601
/// explicit (`mm`, `inch`/`"`, `dot`); a bare number is assumed to be dots only602
/// when `dpmm` is known and the value is clearly in dots range. Returns `None`603
/// when unsure, so the dialog asks the user instead.604
pub fn parse_length_mm(reply: &str, dpmm: Option<u32>) -> Option<f32> {605
let r = reply.trim().trim_matches(char::from(0)).trim().to_ascii_lowercase();606
let num: String = r607
.chars()608
.skip_while(|c| !c.is_ascii_digit())609
.take_while(|c| c.is_ascii_digit() || *c == '.')610
.collect();611
let v: f32 = num.parse().ok()?;612
if !v.is_finite() || v <= 0.0 {613
return None;614
}615
let mm = if r.contains("mm") {616
v617
} else if r.contains("inch") || r.contains('"') {618
v * 25.4619
} else if r.contains("dot") {620
v / dpmm? as f32621
} else {622
return None;623
};624
Some(mm)625
}626
627
pub fn parse_dpi(reply: &str) -> Option<u16> {628
let n: String = reply.chars().filter(|c| c.is_ascii_digit()).collect();629
match n.parse::<u16>().ok()? {630
200 | 203 => Some(203),631
300 => Some(300),632
600 => Some(600),633
_ => None,634
}635
}636
637
#[cfg(test)]638
mod tests {639
use super::*;640
use crate::escpos::EscPosEncoder;641
use crate::io::PosMetadata;642
643
fn fmt(w: f32, h: f32) -> LabelFormat {644
LabelFormat { width_mm: w, height_mm: h, gap_mm: 3.0, media: MediaKind::Gap, dpi: 300, rotate_180: false }645
}646
647
fn split_cmds(job: &[u8]) -> Vec<String> {648
// Text lines only (BITMAP data is binary): keep the line prefix up to data.649
let mut out = Vec::new();650
let mut i = 0;651
while i < job.len() {652
let end = job[i..].windows(2).position(|w| w == b"\r\n").map(|p| i + p).unwrap_or(job.len());653
let line = &job[i..end];654
if line.starts_with(b"BITMAP ") {655
let hdr: Vec<u8> = line.iter().take_while(|_| true).copied().collect();656
// header = first 5 commas657
let mut commas = 0;658
let mut k = 0;659
while k < hdr.len() && commas < 5 {660
if hdr[k] == b',' {661
commas += 1;662
}663
k += 1;664
}665
let head = String::from_utf8_lossy(&hdr[..k]).to_string();666
let parts: Vec<usize> = head.trim_start_matches("BITMAP ").trim_end_matches(',').split(',').map(|s| s.parse().unwrap()).collect();667
let data_len = parts[2] * parts[3];668
out.push(head);669
i = i + k + data_len;670
assert_eq!(&job[i..i + 2], b"\r\n", "bitmap data length must match header");671
i += 2;672
continue;673
}674
out.push(String::from_utf8_lossy(line).to_string());675
i = end + 2;676
}677
out678
}679
680
#[test]681
fn header_matches_spec_syntax() {682
let s = setup_commands(&fmt(50.0, 30.0), 30.0, TsplOptions::default());683
assert_eq!(s, "SIZE 50 mm,30 mm\r\nGAP 3 mm,0 mm\r\nDIRECTION 0,0\r\nREFERENCE 0,0\r\n");684
let mut f = fmt(101.6, 25.4);685
f.media = MediaKind::BlackMark;686
f.gap_mm = 2.5;687
f.rotate_180 = true;688
let s = setup_commands(&f, 25.4, TsplOptions { calibrate: true });689
assert_eq!(690
s,691
"SIZE 101.6 mm,25.4 mm\r\nBLINE 2.5 mm,0 mm\r\nBLINEDETECT 305,30\r\nDIRECTION 1,0\r\nREFERENCE 0,0\r\n"692
);693
f.media = MediaKind::Continuous;694
let s = setup_commands(&f, 40.0, TsplOptions { calibrate: true });695
assert!(s.contains("GAP 0,0\r\n") && !s.contains("DETECT"));696
let g = setup_commands(&fmt(50.0, 30.0), 30.0, TsplOptions { calibrate: true });697
assert!(g.contains("GAPDETECT 360,36\r\n"));698
}699
700
#[test]701
fn bitmap_zero_is_black() {702
let mut img = GrayImage::from_pixel(10, 2, Luma([255]));703
img.put_pixel(0, 0, Luma([0]));704
img.put_pixel(9, 1, Luma([0]));705
let (wb, data) = bitmap_bytes(&img);706
assert_eq!(wb, 2);707
assert_eq!(data, vec![0x7F, 0xFF, 0xFF, 0xBF]);708
}709
710
#[test]711
fn full_job_structure() {712
let doc = crate::dsl::parse("# Hello\nWorld\n@barcode CODE128 ABC123\n@qr hi\n@cut\n").unwrap();713
let md = PosMetadata { page_width_mm: 58.0, ..Default::default() };714
let mut enc = EscPosEncoder::new(md.clone());715
let esc = enc.encode_document(&doc).unwrap().to_vec();716
let job = escpos_to_tspl(&esc, md.printable_dots() as u32, &fmt(100.0, 150.0), TsplOptions::default());717
let cmds = split_cmds(&job);718
assert_eq!(cmds[0], "SIZE 100 mm,150 mm");719
assert_eq!(cmds[1], "GAP 3 mm,0 mm");720
assert_eq!(cmds[2], "DIRECTION 0,0");721
assert_eq!(cmds[3], "REFERENCE 0,0");722
assert_eq!(cmds[4], "CLS");723
assert!(cmds[5].starts_with("BITMAP "));724
assert_eq!(cmds[6], "PRINT 1,1");725
assert_eq!(cmds.len(), 7);726
// 58 mm doc (384 source dots) at 300 dpi → 576 dots = 72 bytes, centred on 1200 dots.727
let parts: Vec<u32> = cmds[5][7..].trim_end_matches(',').split(',').map(|s| s.parse().unwrap()).collect();728
assert_eq!(parts[2], 72);729
assert_eq!(parts[0], (1200 - 576) / 2);730
assert_eq!(parts[1], 0);731
assert_eq!(parts[4], 0);732
assert!(parts[3] > 100);733
}734
735
#[test]736
fn content_is_drawn() {737
let doc = crate::dsl::parse("HELLO\n").unwrap();738
let md = PosMetadata { page_width_mm: 80.0, ..Default::default() };739
let esc = EscPosEncoder::new(md.clone()).encode_document(&doc).unwrap().to_vec();740
let pages = render_escpos(&esc, md.printable_dots() as u32, 1.0);741
assert_eq!(pages.len(), 1);742
let p = &pages[0];743
assert_eq!(p.width(), 576);744
let dark = p.pixels().filter(|px| px.0[0] == 0).count();745
assert!(dark > 100, "text must produce dots, got {dark}");746
// Left aligned: nothing right of the 5 chars (60 dots).747
assert!(p.enumerate_pixels().all(|(x, _, px)| x < 64 || px.0[0] == 255));748
}749
750
#[test]751
fn center_and_right_alignment() {752
for (dsl, check) in [(":center:\nX\n", 1u8), (":right:\nX\n", 2u8)] {753
let doc = crate::dsl::parse(dsl).unwrap();754
let md = PosMetadata { page_width_mm: 80.0, ..Default::default() };755
let esc = EscPosEncoder::new(md.clone()).encode_document(&doc).unwrap().to_vec();756
let p = &render_escpos(&esc, 576, 1.0)[0];757
let xs: Vec<u32> = p.enumerate_pixels().filter(|(_, _, px)| px.0[0] == 0).map(|(x, _, _)| x).collect();758
let min = *xs.iter().min().unwrap();759
if check == 1 {760
assert!((276..300).contains(&min), "center min {min}");761
} else {762
assert!(min >= 560, "right min {min}");763
}764
}765
}766
767
#[test]768
fn cut_starts_new_label_and_trailing_feed_is_trimmed() {769
let doc = crate::dsl::parse("A\n@feed 5\n@cut\nB\n@cut\n@feed 3\n@cut\n").unwrap();770
let md = PosMetadata { page_width_mm: 58.0, ..Default::default() };771
let esc = EscPosEncoder::new(md.clone()).encode_document(&doc).unwrap().to_vec();772
let pages = render_escpos(&esc, 384, 1.5);773
assert_eq!(pages.len(), 2, "blank page after last cut is skipped");774
assert!(pages[0].height() < 40, "feed before cut trimmed: {}", pages[0].height());775
let job = encode_pages(&pages, &fmt(60.0, 40.0), TsplOptions::default());776
assert_eq!(split_cmds(&job).iter().filter(|c| *c == "PRINT 1,1").count(), 2);777
}778
779
#[test]780
fn tall_page_splits_over_labels() {781
let img = GrayImage::from_pixel(100, 250, Luma([0]));782
let f = LabelFormat { width_mm: 20.0, height_mm: 10.0, gap_mm: 2.0, media: MediaKind::Gap, dpi: 203, rotate_180: false };783
// 10 mm @ 8 dots/mm = 80 dots → 4 labels (80+80+80+10).784
let job = encode_pages(&[img], &f, TsplOptions::default());785
let cmds = split_cmds(&job);786
let bitmaps: Vec<&String> = cmds.iter().filter(|c| c.starts_with("BITMAP")).collect();787
assert_eq!(bitmaps.len(), 4);788
assert_eq!(bitmaps[0].as_str(), "BITMAP 30,0,13,80,0,");789
assert_eq!(bitmaps[3].as_str(), "BITMAP 30,0,13,10,0,");790
}791
792
#[test]793
fn continuous_uses_content_height() {794
let img = GrayImage::from_pixel(80, 400, Luma([0]));795
let f = LabelFormat { width_mm: 10.0, height_mm: 10.0, gap_mm: 0.0, media: MediaKind::Continuous, dpi: 203, rotate_180: false };796
let cmds = split_cmds(&encode_pages(&[img], &f, TsplOptions::default()));797
assert_eq!(cmds[0], "SIZE 10 mm,50 mm");798
assert_eq!(cmds[1], "GAP 0,0");799
}800
801
#[test]802
fn wide_doc_shrinks_to_label() {803
let f = fmt(40.0, 30.0);804
let s = page_scale(576, &f);805
assert!((576.0 * s - 480.0).abs() < 0.5);806
assert!((page_scale(384, &fmt(100.0, 50.0)) - 1.5).abs() < 1e-6);807
}808
809
#[test]810
fn barcodes_and_raster_render() {811
let doc = crate::dsl::parse("@barcode CODE128 ABC\n@barcode RASTER CODE128 ABC\n@qr RASTER hi scale=4\n").unwrap();812
let md = PosMetadata { page_width_mm: 58.0, ..Default::default() };813
let esc = EscPosEncoder::new(md.clone()).encode_document(&doc).unwrap().to_vec();814
let pages = render_escpos(&esc, 384, 1.5);815
assert_eq!(pages.len(), 1);816
assert!(pages[0].height() > 200);817
assert_eq!(pages[0].width(), 576);818
}819
820
#[test]821
fn parses_replies_conservatively() {822
assert_eq!(parse_length_mm("50.00 mm", None), Some(50.0));823
assert_eq!(parse_length_mm("2.00 inch", None), Some(50.8));824
assert_eq!(parse_length_mm("600 dot", Some(12)), Some(50.0));825
assert_eq!(parse_length_mm("600 dot", None), None);826
assert_eq!(parse_length_mm("600", Some(12)), None);827
assert_eq!(parse_length_mm("", None), None);828
assert_eq!(parse_dpi("300\r\n"), Some(300));829
assert_eq!(parse_dpi("203"), Some(203));830
assert_eq!(parse_dpi("x"), None);831
assert_eq!(status_problem(0), None);832
assert_eq!(status_problem(0x04), Some(StatusProblem::OutOfPaper));833
assert_eq!(status_problem(0x05), Some(StatusProblem::HeadOpen));834
}835
}