thermark 0.36.1

Local sticker printing for pocket thermal printers over BLE/USB — QR links, inventory tags, badges, photos; no vendor app
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
//! Compose printable labels: square QR + shaped text.

use crate::errors::{Error, Result};
use crate::font::LabelFont;
use crate::geometry::{LabelPx, Rect, SafeArea};
use image::{GrayImage, Luma};
use qrcode::QrCode;

#[derive(Debug, Clone, Copy, PartialEq, Eq, clap::ValueEnum)]
#[value(rename_all = "lower")]
pub enum TextSide {
    /// Text column on the left of the QR.
    #[value(alias = "l")]
    Left,
    /// Text column on the right of the QR.
    #[value(alias = "r")]
    Right,
}

#[derive(Debug, Clone)]
pub struct QrLabelOptions {
    pub url: String,
    pub side_text: String,
    pub label: LabelPx,
    /// Content/registration insets for this printer/media. `SafeArea::default()` is the
    /// measured B1 value; override from `Config::resolve_safe_area`.
    pub safe: SafeArea,
    pub text_side: TextSide,
    /// Draw a 1px outer border (off by default — not needed for printing).
    pub border: bool,
    /// Optional explicit font path; otherwise auto-pick system Arial/etc.
    pub font_path: Option<std::path::PathBuf>,
    /// Named font: "helvetica", "times", "arial", …
    pub font_name: Option<String>,
    /// Fixed text size in pixels (approx em height). `None` = auto-fit largest.
    pub font_size: Option<f32>,
}

/// Placement of the QR and text column on a label canvas.
///
/// Single source of truth for the side-by-side geometry — [`max_qr_side`] and
/// [`make_qr_label_opts`] both read it so they cannot drift apart.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct QrLayout {
    /// The reliably printable box this layout was fitted into.
    pub area: Rect,
    pub gap: u32,
    pub text_col_w: u32,
    pub qr_side: u32,
}

/// Breathing room inside the content area, in px. Purely aesthetic.
const MARGIN: u32 = 4;
/// Space between the QR and the text column, in px.
const GAP: u32 = 8;
/// Text column is this fraction of the label width…
const TEXT_COL_FRACTION: f64 = 0.34;
/// …but at least this many px, unless that would take over half the label.
const TEXT_COL_MIN: u32 = 64;
/// Below this, a QR holds too few modules to survive thermal printing.
const QR_SIDE_MIN: u32 = 64;
/// Smallest box worth laying text into, on either axis.
const MIN_TEXT_BOX_PX: u32 = 16;

/// The box every label type composes into: the label area, inset by the
/// cosmetic `MARGIN`.
///
/// **One owner for this calculation.** It was previously computed separately in
/// `qr_layout` and `make_text_label`, and the two drifted: the text path was
/// left laying out on the raw label, giving a box 232 rows tall on 50x30 media
/// instead of 184, so text was sized for space the printer cannot reach.
pub fn content_box(label: LabelPx, safe: SafeArea) -> Option<Rect> {
    let area = safe.content(label)?;
    Some(Rect {
        x: area.x + MARGIN,
        y: area.y + MARGIN,
        w: area.w.checked_sub(MARGIN * 2)?,
        h: area.h.checked_sub(MARGIN * 2)?,
    })
}

/// Compute the side-by-side layout inside the content area of `label`.
pub fn qr_layout(label: LabelPx, safe: SafeArea) -> Option<QrLayout> {
    let inner = content_box(label, safe)?;

    let ideal = ((label.width_px as f64) * TEXT_COL_FRACTION).round() as u32;
    // `clamp(TEXT_COL_MIN, w / 2)` panics when `w < 2 * TEXT_COL_MIN` (every
    // D11/D110 label). The upper bound is the real constraint, so apply it last.
    let text_col_w = ideal.max(TEXT_COL_MIN).min(inner.w / 2);

    let qr_budget_w = inner.w.saturating_sub(text_col_w + GAP);
    let qr_side = qr_budget_w.min(inner.h);

    (qr_side >= QR_SIDE_MIN).then_some(QrLayout {
        area: inner,
        gap: GAP,
        text_col_w,
        qr_side,
    })
}

/// Horizontal alignment of a text block within its box.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default, clap::ValueEnum)]
#[value(rename_all = "lower")]
pub enum TextAlign {
    #[value(alias = "l")]
    Left,
    #[default]
    #[value(alias = "c")]
    Center,
    #[value(alias = "r")]
    Right,
}

fn draw_border(img: &mut GrayImage) {
    let (w, h) = img.dimensions();
    for x in 0..w {
        img.put_pixel(x, 0, Luma([0]));
        img.put_pixel(x, h - 1, Luma([0]));
    }
    for y in 0..h {
        img.put_pixel(0, y, Luma([0]));
        img.put_pixel(w - 1, y, Luma([0]));
    }
}

/// How many millimetres the boundary probe covers, ending at the label's edge.
///
/// Thirteen bars leaves each numeral room on the narrowest supported probe;
/// the window is placed at the *end* of the label because that is the edge in
/// question.
pub const BOUNDARY_SPAN_MM: u32 = 13;

/// Options for a text-only sticker.
#[derive(Debug, Clone)]
pub struct TextLabelOptions {
    pub text: String,
    pub label: LabelPx,
    pub safe: SafeArea,
    pub align: TextAlign,
    pub border: bool,
    pub font_path: Option<std::path::PathBuf>,
    pub font_name: Option<String>,
    pub font_size: Option<f32>,
}

/// Load an explicit path, then a named font, then the system default.
fn load_font(path: Option<&std::path::Path>, name: Option<&str>) -> Result<LabelFont> {
    match (path, name) {
        (Some(p), _) => LabelFont::load(p),
        (None, Some(n)) => LabelFont::load_named(n),
        (None, None) => LabelFont::load_default(),
    }
}

/// Smallest module size a thermal print can hold and still scan reliably.
///
/// Below this the code is emitted but unreadable — heat bleed closes the gaps
/// between modules. Failing loudly beats handing someone a sticker that looks
/// right and never scans.
pub const QR_MIN_MODULE_PX: usize = 2;
/// Below this it scans, but marginally; worth saying so.
pub const QR_COMFORTABLE_MODULE_PX: usize = 3;

fn overlay_gray(dst: &mut GrayImage, src: &GrayImage, x0: u32, y0: u32) {
    let (dw, dh) = dst.dimensions();
    let (sw, sh) = src.dimensions();
    for y in 0..sh {
        for x in 0..sw {
            let dx = x0 + x;
            let dy = y0 + y;
            if dx < dw && dy < dh {
                dst.put_pixel(dx, dy, *src.get_pixel(x, y));
            }
        }
    }
}

/// QR edge length [`make_qr_label_opts`] will use, or 0 when none fits.
///
/// Takes the same `safe` the renderer will: reporting against the default
/// while the caller renders with a configured one prints a number that does
/// not match the label.
pub fn max_qr_side(label: LabelPx, safe: SafeArea) -> u32 {
    qr_layout(label, safe).map_or(0, |l| l.qr_side)
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::geometry::LabelMm;

    fn test_font_path() -> std::path::PathBuf {
        std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fonts/DejaVuSans.ttf")
    }

    #[test]
    fn invalid_font_sizes_leave_the_image_unchanged() {
        let font = LabelFont::load(&test_font_path()).unwrap();
        let original = GrayImage::from_pixel(384, 240, Luma([255]));
        let bx = Rect {
            x: 4,
            y: 12,
            w: 376,
            h: 216,
        };
        for size in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY, 0.0, -1.0] {
            let mut img = original.clone();
            let error =
                draw_text_block(&mut img, &font, "HELLO", bx, TextAlign::Center, Some(size))
                    .unwrap_err();
            assert!(error.to_string().contains("finite, positive"));
            assert_eq!(img, original);
        }
    }

    #[test]
    fn overflowing_text_is_rejected_before_drawing_any_lines() {
        let font = LabelFont::load(&test_font_path()).unwrap();
        let original = GrayImage::from_pixel(384, 240, Luma([255]));
        for (text, bx, size) in [
            (
                "OVERFLOW\n".repeat(10),
                Rect {
                    x: 4,
                    y: 12,
                    w: 376,
                    h: 216,
                },
                Some(96.0),
            ),
            (
                "OVERFLOW\n".repeat(100),
                Rect {
                    x: 4,
                    y: 12,
                    w: 376,
                    h: 216,
                },
                None,
            ),
            (
                "W".into(),
                Rect {
                    x: 4,
                    y: 12,
                    w: 16,
                    h: 216,
                },
                Some(96.0),
            ),
        ] {
            let mut img = original.clone();
            let error =
                draw_text_block(&mut img, &font, &text, bx, TextAlign::Center, size).unwrap_err();
            assert!(error.to_string().contains("text does not fit"));
            assert_eq!(img, original, "failed layout must not leave partial text");
        }
    }

    #[test]
    fn qr_is_square() {
        let side = 200;
        let qr = render_qr_square("https://www.youtube.com", side).unwrap();
        assert_eq!(qr.dimensions(), (side, side));
    }

    #[test]
    fn label_text_is_left_to_right_abc() {
        let lp = LabelMm::parse("50x30").unwrap().to_pixels(384, 8.0);
        let img = make_qr_label_opts(&QrLabelOptions {
            url: "https://www.youtube.com".into(),
            side_text: "ABC".into(),
            label: lp,
            safe: SafeArea::default(),
            text_side: TextSide::Right,
            border: false,
            font_path: Some(test_font_path()),
            font_name: None,
            font_size: None,
        })
        .unwrap();
        assert_eq!(img.dimensions(), (384, 240));

        // Text lives in the right half; find dark runs and ensure width is reasonable
        let mut min_x = 9999u32;
        let mut max_x = 0u32;
        let mut count = 0u32;
        for (x, y, p) in img.enumerate_pixels() {
            if x > 200 && p[0] < 128 {
                min_x = min_x.min(x);
                max_x = max_x.max(x);
                count += 1;
                let _ = y;
            }
        }
        assert!(count > 50, "expected text ink, got {count}");
        assert!(max_x > min_x + 15, "ABC should span horizontally");
    }

    #[test]
    fn narrow_label_errors_instead_of_panicking() {
        // D11/D110 printheads are 96px, so `text_col_w.clamp(64, w / 2)` was
        // clamp(64, 48) — an unconditional panic for every QR on those models.
        let lp = LabelPx {
            width_px: 96,
            height_px: 240,
        };
        assert_eq!(max_qr_side(lp, SafeArea::default()), 0);
        let err = make_qr_label_opts(&QrLabelOptions {
            url: "https://example.com".into(),
            side_text: "HI".into(),
            label: lp,
            safe: SafeArea::default(),
            text_side: TextSide::Right,
            border: false,
            font_path: Some(test_font_path()),
            font_name: None,
            font_size: None,
        })
        .expect_err("96px label cannot fit QR + text");
        assert!(err.to_string().contains("too small"), "{err}");
    }

    #[test]
    fn qr_layout_is_the_only_source_of_layout_math() {
        // `max_qr_side` must report exactly what the renderer uses, or the two
        // copies of this math drift.
        let lp = LabelMm::parse("50x30").unwrap().to_pixels(384, 8.0);
        let layout = qr_layout(lp, SafeArea::default()).expect("50x30 fits");
        assert_eq!(max_qr_side(lp, SafeArea::default()), layout.qr_side);
        assert!(layout.text_col_w <= lp.width_px / 2);
        assert!(layout.qr_side + layout.text_col_w + layout.gap <= layout.area.w);
        assert!(layout.area.y + layout.area.h <= lp.height_px);
    }

    #[test]
    fn qr_layout_never_panics_across_label_sizes() {
        for w in (8..=384).step_by(8) {
            for h in [8u32, 32, 96, 240, 800] {
                let lp = LabelPx {
                    width_px: w,
                    height_px: h,
                };
                if let Some(l) = qr_layout(lp, SafeArea::default()) {
                    assert!(l.qr_side >= QR_SIDE_MIN);
                    assert!(l.qr_side <= l.area.h);
                }
            }
        }
    }

    #[test]
    fn qr_rejects_content_too_dense_to_scan() {
        // Long content used to render 1px modules into a 200px square: it
        // looked like a QR and was unscannable. 900 bytes needs 113 modules,
        // which is 1px each here.
        let long = "x".repeat(900);
        let err = render_qr_square(&long, 200).expect_err("should refuse");
        assert!(err.to_string().contains("too fine to scan"), "{err}");

        // The boundary: 600 bytes is 93 modules -> 2px, which still scans.
        assert!(render_qr_square(&"x".repeat(600), 200).is_ok());
    }

    #[test]
    fn qr_accepts_ordinary_content() {
        let img = render_qr_square("https://github.com/kahwee/thermark", 200).unwrap();
        assert_eq!(img.dimensions(), (200, 200));
    }

    #[test]
    fn qr_stays_clear_of_the_clipped_bottom_edge() {
        let lp = LabelMm::parse("50x30").unwrap().to_pixels(384, 8.0);
        let layout = qr_layout(lp, SafeArea::default()).unwrap();
        let safe = SafeArea::default();
        // The QR must end above the band the printer cannot reach.
        let qr_bottom = layout.area.y + (layout.area.h + layout.qr_side) / 2;
        assert!(
            qr_bottom <= lp.height_px - safe.bottom,
            "QR reaches {qr_bottom}, clipped band starts at {}",
            lp.height_px - safe.bottom
        );
    }

    #[test]
    fn text_label_renders_and_stays_in_the_safe_area() {
        let lp = LabelMm::parse("50x30").unwrap().to_pixels(384, 8.0);
        let img = make_text_label(&TextLabelOptions {
            text: "HELLO\nWORLD".into(),
            label: lp,
            safe: SafeArea::default(),
            align: TextAlign::Center,
            border: false,
            font_path: Some(test_font_path()),
            font_name: None,
            font_size: None,
        })
        .expect("render text label with vendored font");
        assert_eq!(img.dimensions(), (lp.width_px, lp.height_px));
        let safe = SafeArea::default();
        for y in (lp.height_px - safe.bottom)..lp.height_px {
            for x in 0..lp.width_px {
                assert_eq!(img.get_pixel(x, y)[0], 255, "ink at ({x},{y}) is clipped");
            }
        }
    }

    #[test]
    fn text_label_rejects_empty_text() {
        let lp = LabelMm::parse("50x30").unwrap().to_pixels(384, 8.0);
        assert!(
            make_text_label(&TextLabelOptions {
                text: "   ".into(),
                label: lp,
                safe: SafeArea::default(),
                align: TextAlign::Center,
                border: false,
                font_path: None,
                font_name: None,
                font_size: None,
            })
            .is_err()
        );
    }

    #[test]
    fn no_border_by_default() {
        let lp = LabelPx {
            width_px: 384,
            height_px: 240,
        };
        let img = make_qr_label_opts(&QrLabelOptions {
            url: "https://example.com".into(),
            side_text: "HI".into(),
            label: lp,
            safe: SafeArea::default(),
            text_side: TextSide::Right,
            border: false,
            font_path: Some(test_font_path()),
            font_name: None,
            font_size: None,
        })
        .unwrap();
        // Corners should be white (no border)
        assert_eq!(img.get_pixel(0, 0)[0], 255);
        assert_eq!(img.get_pixel(383, 0)[0], 255);
        assert_eq!(img.get_pixel(0, 239)[0], 255);
        assert_eq!(img.get_pixel(383, 239)[0], 255);
    }
}

mod qr;
pub use qr::{make_qr_label_opts, render_qr_square};

mod text;
pub use text::{draw_text_block, make_text_label};

mod calibration;
pub use calibration::{boundary_range, make_boundary_label, make_calibration_label};

pub use qr::make_qr_label_with_font;
pub use text::make_text_label_with_font;