thermark 0.33.0

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
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
//! User config: default printer address and connection prefs (**JSON only**).
//!
//! File location (platform standard):
//! - **macOS:** `~/Library/Application Support/thermark/config.json`
//! - **Linux:** `~/.config/thermark/config.json`
//! - **Windows:** `%APPDATA%\thermark\config.json`
//!
//! Override path with env `THERMARK_CONFIG`.
//!
//! Address resolution order for CLI:
//! 1. `-a` / `--addr` flag
//! 2. `THERMARK_ADDR` env
//! 3. `addr` in this config file

use crate::errors::{Error, Result};
use crate::geometry::{LabelMm, SafeArea};

/// Fallback label size when neither the CLI nor the config names one.
pub const DEFAULT_LABEL: &str = "50x30";
pub const MAX_SCAN_SECS: u64 = 300;
use crate::protocol::Model;
use serde::{Deserialize, Serialize};
use std::fs;
use std::io::{ErrorKind, Write};
use std::path::{Path, PathBuf};

/// Preferred link type stored in config / resolved for the CLI.
#[derive(
    Debug, Clone, Copy, PartialEq, Eq, Default, Hash, clap::ValueEnum, Serialize, Deserialize,
)]
#[value(rename_all = "lower")]
#[serde(rename_all = "lowercase")]
pub enum ConnPref {
    #[default]
    Ble,
    #[serde(alias = "serial")]
    Usb,
}

impl ConnPref {
    pub fn as_str(self) -> &'static str {
        match self {
            Self::Ble => "ble",
            Self::Usb => "usb",
        }
    }
}

impl std::fmt::Display for ConnPref {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.pad(self.as_str())
    }
}

impl std::str::FromStr for ConnPref {
    type Err = Error;

    fn from_str(value: &str) -> Result<Self> {
        match value.trim().to_ascii_lowercase().as_str() {
            "ble" => Ok(Self::Ble),
            "usb" | "serial" => Ok(Self::Usb),
            _ => Err(Error::msg(format!(
                "unknown connection '{value}' (try ble or usb)"
            ))),
        }
    }
}

/// On-disk / in-memory user preferences (JSON).
#[derive(Debug, Clone, Default, PartialEq, Eq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Config {
    /// Default BLE name / UUID or serial device path.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub addr: Option<String>,
    /// Link type (`ble` / `usb`).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub connection: Option<ConnPref>,
    /// Default model (`b1`, …).
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub model: Option<Model>,
    /// Default BLE scan seconds before connect.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub scan_secs: Option<u64>,
    /// Content/registration insets for this printer + media, in pixels.
    /// Set it from `thermark calibrate`; see `thermark config safe-area`.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub safe_area: Option<SafeArea>,
    /// Default label size, e.g. `"50x30"`. Saves repeating `--label` on media
    /// you use every day.
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub label: Option<String>,
}

impl Config {
    /// Empty config (no saved printer).
    pub fn new() -> Self {
        Self::default()
    }

    /// True when nothing is configured.
    pub fn is_empty(&self) -> bool {
        self.addr.is_none()
            && self.connection.is_none()
            && self.model.is_none()
            && self.scan_secs.is_none()
            && self.safe_area.is_none()
            && self.label.is_none()
    }

    /// Config directory (platform standard).
    pub fn config_dir() -> Result<PathBuf> {
        let dirs = directories::ProjectDirs::from("", "", "thermark")
            .ok_or_else(|| Error::msg("could not determine config directory for thermark"))?;
        Ok(dirs.config_dir().to_path_buf())
    }

    /// Path used by the CLI (`THERMARK_CONFIG` or `…/config.json`).
    /// A non-Unicode override is an error, never a fallback to the default.
    pub fn default_path() -> Result<PathBuf> {
        let env = match std::env::var("THERMARK_CONFIG") {
            Ok(path) => Some(path),
            Err(std::env::VarError::NotPresent) => None,
            // Never redirect an invalid override to the user's default config,
            // especially when the caller intends to update or clear that file.
            Err(std::env::VarError::NotUnicode(_)) => {
                return Err(Error::msg("THERMARK_CONFIG must be valid Unicode"));
            }
        };
        Self::default_path_with(env.as_deref())
    }

    /// Resolve the config path from an explicit override.
    ///
    /// Separated from the environment read so it is testable without
    /// `set_var`, which is `unsafe` in edition 2024.
    pub fn default_path_with(env: Option<&str>) -> Result<PathBuf> {
        if let Some(p) = Self::nonempty(env) {
            return Ok(PathBuf::from(p));
        }
        Ok(Self::config_dir()?.join("config.json"))
    }

    /// Load from the default path. Missing file → empty config (not an error).
    pub fn load() -> Result<Self> {
        Self::load_from(&Self::default_path()?)
    }

    /// Load from an explicit path. Missing file → empty config.
    pub fn load_from(path: &Path) -> Result<Self> {
        let text = match fs::read_to_string(path) {
            Ok(text) => text,
            Err(error) if error.kind() == ErrorKind::NotFound => return Ok(Self::default()),
            Err(error) => {
                return Err(Error::msg(format!(
                    "read config {}: {error}",
                    path.display()
                )));
            }
        };
        Self::parse_json(&text)
            .map_err(|e| Error::msg(format!("parse config {}: {e}", path.display())))
    }

    /// Parse JSON body (no file I/O).
    pub fn parse_json(text: &str) -> Result<Self> {
        let config: Self =
            serde_json::from_str(text).map_err(|e| Error::msg(format!("invalid JSON: {e}")))?;
        config.validate()?;
        Ok(config)
    }

    /// Pretty-print JSON for display / file.
    pub fn to_json_pretty(&self) -> Result<String> {
        serde_json::to_string_pretty(self).map_err(|e| Error::msg(format!("serialize JSON: {e}")))
    }

    /// Write to the default path (creates parent dirs).
    pub fn save(&self) -> Result<PathBuf> {
        let path = Self::default_path()?;
        self.save_to(&path)?;
        Ok(path)
    }

    /// Write JSON to an explicit path.
    pub fn save_to(&self, path: &Path) -> Result<()> {
        self.validate()?;
        if let Some(parent) = path.parent() {
            fs::create_dir_all(parent)
                .map_err(|e| Error::msg(format!("create config dir {}: {e}", parent.display())))?;
        }
        let body = format!("{}\n", self.to_json_pretty()?);
        let parent = path.parent().unwrap_or_else(|| Path::new("."));
        // A unique sibling avoids concurrent writers sharing `config.json.tmp`.
        // Persisting within the same directory keeps the final rename atomic.
        let mut tmp = tempfile::NamedTempFile::new_in(parent).map_err(|e| {
            Error::msg(format!(
                "create temporary config in {}: {e}",
                parent.display()
            ))
        })?;
        tmp.write_all(body.as_bytes())
            .map_err(|e| Error::msg(format!("write temporary config: {e}")))?;
        tmp.as_file()
            .sync_all()
            .map_err(|e| Error::msg(format!("flush temporary config: {e}")))?;
        tmp.persist(path)
            .map_err(|e| Error::msg(format!("replace config {}: {}", path.display(), e.error)))?;
        Ok(())
    }

    /// Delete the default config file if it exists.
    pub fn clear() -> Result<bool> {
        Self::clear_at(&Self::default_path()?)
    }

    /// Delete config at an explicit path.
    pub fn clear_at(path: &Path) -> Result<bool> {
        match fs::remove_file(path) {
            Ok(()) => Ok(true),
            Err(error) if error.kind() == ErrorKind::NotFound => Ok(false),
            Err(error) => Err(Error::msg(format!(
                "remove config {}: {error}",
                path.display()
            ))),
        }
    }

    /// Update fields for `config set` (only overwrites provided values).
    pub fn apply_update(
        &mut self,
        addr: Option<&str>,
        connection: Option<ConnPref>,
        model: Option<Model>,
        scan_secs: Option<u64>,
        label: Option<&str>,
    ) -> Result<()> {
        // Validate every supplied value before changing `self`, so a failed
        // update cannot leave an in-memory config partially modified.
        let addr = match addr {
            Some(addr) => {
                let addr = addr.trim();
                if addr.is_empty() {
                    return Err(Error::msg("printer address cannot be blank"));
                }
                Some(addr.to_string())
            }
            None => None,
        };
        let label = match label {
            Some(label) => {
                let label = label.trim();
                LabelMm::parse(label)?;
                Some(label.to_string())
            }
            None => None,
        };
        if let Some(seconds) = scan_secs
            && !(1..=MAX_SCAN_SECS).contains(&seconds)
        {
            return Err(Error::msg(format!(
                "scan time must be 1..={MAX_SCAN_SECS} seconds, got {seconds}"
            )));
        }

        let mut updated = self.clone();
        if let Some(addr) = addr {
            updated.addr = Some(addr);
        }
        if let Some(connection) = connection {
            updated.connection = Some(connection);
        }
        if let Some(model) = model {
            updated.model = Some(model);
        }
        if let Some(scan_secs) = scan_secs {
            updated.scan_secs = Some(scan_secs);
        }
        if let Some(label) = label {
            updated.label = Some(label);
        }
        updated.validate()?;
        *self = updated;
        Ok(())
    }

    /// Set a printer address and connection, preserving optional fields.
    ///
    /// This compatibility helper is also used by `scan --save`; callers that
    /// need a partial update should use [`Self::apply_update`].
    pub fn apply_set(
        &mut self,
        addr: impl Into<String>,
        connection: ConnPref,
        model: Option<Model>,
        scan_secs: Option<u64>,
    ) -> Result<()> {
        let addr = addr.into();
        self.apply_update(Some(&addr), Some(connection), model, scan_secs, None)
    }

    pub fn validate(&self) -> Result<()> {
        if self
            .addr
            .as_deref()
            .is_some_and(|addr| addr.trim().is_empty())
        {
            return Err(Error::msg("configured printer address cannot be blank"));
        }
        if let Some(seconds) = self.scan_secs
            && !(1..=MAX_SCAN_SECS).contains(&seconds)
        {
            return Err(Error::msg(format!(
                "configured scan time must be 1..={MAX_SCAN_SECS} seconds, got {seconds}"
            )));
        }
        if let Some(label) = self.label.as_deref() {
            LabelMm::parse(label)
                .map_err(|e| Error::msg(format!("configured label is invalid: {e}")))?;
        }
        if let Some(safe_area) = self.safe_area {
            let label = LabelMm::parse(&self.resolve_label(None))?;
            let profile = crate::profile::profile_for_model(self.resolve_model(None));
            let pixels = label.to_pixels(profile.max_width_px, profile.pixels_per_mm());
            if safe_area.content(pixels).is_none() {
                return Err(Error::msg(
                    "configured safe-area insets consume the entire label",
                ));
            }
        }
        Ok(())
    }

    fn nonempty(s: Option<&str>) -> Option<&str> {
        s.map(str::trim).filter(|s| !s.is_empty())
    }

    /// Resolve printer address from explicit inputs.
    ///
    /// Takes the environment value rather than reading it, so tests need not
    /// mutate process-wide state. `std::env::set_var` is `unsafe` in edition
    /// 2024 precisely because another thread reading the environment at the
    /// same time is undefined behaviour — and the test suite runs in parallel
    /// with other tests that read it.
    pub fn resolve_addr_with(&self, cli: Option<&str>, env: Option<&str>) -> Result<String> {
        if let Some(a) = Self::nonempty(cli) {
            return Ok(a.to_string());
        }
        if let Some(a) = Self::nonempty(env) {
            return Ok(a.to_string());
        }
        if let Some(a) = Self::nonempty(self.addr.as_deref()) {
            return Ok(a.to_string());
        }
        Err(Error::msg(
            "no printer address: pass -a \"B1-YourPrinter\" (full name), set THERMARK_ADDR, \
             or: thermark scan --save / thermark config set -a \"B1-YourPrinter\"",
        ))
    }

    /// Resolve printer address: CLI flag → `THERMARK_ADDR` → config.
    ///
    /// Reads the environment here, at the edge, and defers the logic to
    /// [`Self::resolve_addr_with`] so it stays testable without `set_var`.
    pub fn resolve_addr(&self, cli_addr: Option<&str>) -> Result<String> {
        let env = std::env::var("THERMARK_ADDR").ok();
        self.resolve_addr_with(cli_addr, env.as_deref())
    }

    /// Prefer CLI connection when provided; else config; else BLE.
    pub fn resolve_connection(&self, cli: Option<ConnPref>) -> ConnPref {
        cli.or(self.connection).unwrap_or_default()
    }

    /// Prefer CLI model when provided; else config; else [`Model::B1`].
    pub fn resolve_model(&self, cli: Option<Model>) -> Model {
        cli.or(self.model).unwrap_or_default()
    }

    /// Label size: CLI flag, else saved default, else 50x30.
    pub fn resolve_label(&self, cli: Option<&str>) -> String {
        Self::nonempty(cli)
            .map(str::to_string)
            .or_else(|| Self::nonempty(self.label.as_deref()).map(str::to_string))
            .unwrap_or_else(|| DEFAULT_LABEL.to_string())
    }

    /// Saved safe area, or the standard 1 mm registration margin at this DPI.
    pub fn resolve_safe_area(&self, pixels_per_mm: f64) -> SafeArea {
        self.safe_area
            .unwrap_or_else(|| SafeArea::registration(pixels_per_mm))
    }

    /// Prefer CLI scan seconds when provided; else config; else 4.
    pub fn resolve_scan_secs(&self, cli: Option<u64>) -> u64 {
        cli.or(self.scan_secs).unwrap_or(4).clamp(1, MAX_SCAN_SECS)
    }
}

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

    #[test]
    fn connection_from_str_is_typed_and_rejects_unknown_values() {
        assert_eq!(" BLE ".parse::<ConnPref>().unwrap(), ConnPref::Ble);
        assert_eq!("usb".parse::<ConnPref>().unwrap(), ConnPref::Usb);
        assert_eq!("serial".parse::<ConnPref>().unwrap(), ConnPref::Usb);
        assert!("bluetooth".parse::<ConnPref>().is_err());
    }

    #[test]
    fn roundtrip_json_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.json");
        let cfg = Config {
            addr: Some("B1-YourPrinter".into()),
            connection: Some(ConnPref::Ble),
            model: Some(Model::B1),
            scan_secs: Some(6),
            safe_area: None,
            label: None,
        };
        cfg.save_to(&path).unwrap();
        let text = std::fs::read_to_string(&path).unwrap();
        assert!(text.trim_start().starts_with('{'));
        assert!(text.contains("B1-YourPrinter"));
        let loaded = Config::load_from(&path).unwrap();
        assert_eq!(loaded, cfg);
    }

    #[test]
    fn missing_file_is_empty() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("nope.json");
        let cfg = Config::load_from(&path).unwrap();
        assert!(cfg.is_empty());
    }

    #[test]
    fn concurrent_saves_use_distinct_atomic_temp_files() {
        let dir = tempfile::tempdir().unwrap();
        let path = std::sync::Arc::new(dir.path().join("config.json"));
        let threads: Vec<_> = (0..8)
            .map(|n| {
                let path = path.clone();
                std::thread::spawn(move || {
                    let cfg = Config {
                        addr: Some(format!("B1-{n}")),
                        ..Config::default()
                    };
                    cfg.save_to(&path)
                })
            })
            .collect();
        for thread in threads {
            thread.join().unwrap().unwrap();
        }
        let loaded = Config::load_from(&path).unwrap();
        assert!(loaded.addr.unwrap().starts_with("B1-"));
    }

    #[test]
    fn invalid_json_errors() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("bad.json");
        std::fs::write(&path, "{not json").unwrap();
        let err = Config::load_from(&path).unwrap_err().to_string();
        assert!(err.contains("parse") || err.contains("JSON"), "{err}");
    }

    #[test]
    fn rejects_unknown_or_invalid_config_values() {
        for body in [
            r#"{"adress":"B1-Typo"}"#,
            r#"{"addr":"   "}"#,
            r#"{"scan_secs":0}"#,
            r#"{"scan_secs":301}"#,
            r#"{"label":"not-a-label"}"#,
            r#"{"safe_area":{"top":4294967295,"bottom":1,"left":0,"right":0}}"#,
        ] {
            assert!(Config::parse_json(body).is_err(), "accepted {body}");
        }
    }

    #[test]
    fn apply_set_rejects_invalid_values_without_mutating() {
        let original = Config::default();
        let mut cfg = original.clone();
        assert!(cfg.apply_set("  ", ConnPref::Ble, None, None).is_err());
        assert_eq!(cfg, original);
        assert!(
            cfg.apply_set("B1-Test", ConnPref::Ble, None, Some(0))
                .is_err()
        );
        assert_eq!(cfg, original);
    }

    #[test]
    fn apply_set_merges_without_clobbering_unspecified() {
        let mut cfg = Config {
            addr: Some("old".into()),
            connection: Some(ConnPref::Usb),
            model: Some(Model::B1Pro),
            scan_secs: Some(9),
            safe_area: None,
            label: None,
        };
        cfg.apply_set("B1-New", ConnPref::Ble, None, None).unwrap();
        assert_eq!(cfg.addr.as_deref(), Some("B1-New"));
        assert_eq!(cfg.connection, Some(ConnPref::Ble));
        assert_eq!(cfg.model, Some(Model::B1Pro));
        assert_eq!(cfg.scan_secs, Some(9));
    }

    #[test]
    fn apply_update_changes_only_supplied_fields() {
        let mut cfg = Config {
            addr: Some("B1-Old".into()),
            connection: Some(ConnPref::Usb),
            model: Some(Model::B1Pro),
            scan_secs: Some(9),
            safe_area: None,
            label: Some("50x30".into()),
        };

        cfg.apply_update(Some(" B1-New "), None, None, None, Some("40x20"))
            .unwrap();

        assert_eq!(cfg.addr.as_deref(), Some("B1-New"));
        assert_eq!(cfg.connection, Some(ConnPref::Usb));
        assert_eq!(cfg.model, Some(Model::B1Pro));
        assert_eq!(cfg.scan_secs, Some(9));
        assert_eq!(cfg.label.as_deref(), Some("40x20"));
    }

    #[test]
    fn apply_update_validates_before_mutating() {
        let original = Config {
            addr: Some("B1-Old".into()),
            connection: Some(ConnPref::Usb),
            model: None,
            scan_secs: None,
            safe_area: None,
            label: Some("50x30".into()),
        };
        let mut cfg = original.clone();

        assert!(
            cfg.apply_update(Some("B1-New"), None, None, None, Some("invalid"))
                .is_err()
        );
        assert_eq!(cfg, original);

        let mut with_safe_area = Config {
            safe_area: Some(SafeArea::B1),
            ..original
        };
        let unchanged = with_safe_area.clone();
        assert!(
            with_safe_area
                .apply_update(None, None, None, None, Some("50x1"))
                .is_err()
        );
        assert_eq!(with_safe_area, unchanged);
    }

    #[test]
    fn apply_set_trims_addr() {
        let mut cfg = Config::default();
        cfg.apply_set("  B1-Spaced  ", ConnPref::Ble, None, None)
            .unwrap();
        assert_eq!(cfg.addr.as_deref(), Some("B1-Spaced"));
    }

    #[test]
    fn resolve_addr_priority() {
        // No `set_var`: the env value is a parameter, so this cannot race with
        // any other test that reads the environment.
        let cfg = Config {
            addr: Some("from-config".into()),
            ..Default::default()
        };
        assert_eq!(
            cfg.resolve_addr_with(Some("from-cli"), Some("from-env"))
                .unwrap(),
            "from-cli"
        );
        assert_eq!(
            cfg.resolve_addr_with(None, Some("from-env")).unwrap(),
            "from-env"
        );
        assert_eq!(cfg.resolve_addr_with(None, None).unwrap(), "from-config");
        // Blank values fall through instead of resolving to an empty address.
        assert_eq!(
            cfg.resolve_addr_with(Some("  "), Some("  ")).unwrap(),
            "from-config"
        );
    }

    #[test]
    fn resolve_addr_missing_errors() {
        let err = Config::default()
            .resolve_addr_with(None, None)
            .unwrap_err()
            .to_string();
        assert!(err.contains("config set"), "{err}");
    }

    #[test]
    fn resolve_label_prefers_cli_then_config_then_default() {
        let mut cfg = Config::default();
        assert_eq!(cfg.resolve_label(None), DEFAULT_LABEL);
        assert_eq!(cfg.resolve_label(Some("40x20")), "40x20");

        cfg.label = Some("30x15".into());
        assert_eq!(cfg.resolve_label(None), "30x15");
        assert_eq!(cfg.resolve_label(Some("40x20")), "40x20");
        // Blank flags fall through rather than producing an empty size.
        assert_eq!(cfg.resolve_label(Some("   ")), "30x15");
    }

    #[test]
    fn resolve_connection_and_scan() {
        let cfg = Config {
            connection: Some(ConnPref::Usb),
            scan_secs: Some(8),
            model: Some(Model::B1Pro),
            ..Default::default()
        };
        assert_eq!(cfg.resolve_connection(None), ConnPref::Usb);
        assert_eq!(cfg.resolve_connection(Some(ConnPref::Ble)), ConnPref::Ble);
        assert_eq!(cfg.resolve_model(None), Model::B1Pro);
        assert_eq!(cfg.resolve_model(Some(Model::B1)), Model::B1);
        assert_eq!(cfg.resolve_scan_secs(None), 8);
        assert_eq!(cfg.resolve_scan_secs(Some(0)), 1);
    }

    #[test]
    fn clear_at_removes_file() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("config.json");
        Config {
            addr: Some("x".into()),
            ..Default::default()
        }
        .save_to(&path)
        .unwrap();
        assert!(Config::clear_at(&path).unwrap());
        assert!(!path.exists());
        assert!(!Config::clear_at(&path).unwrap());
    }

    #[test]
    fn default_path_honors_thermark_config_env() {
        let dir = tempfile::tempdir().unwrap();
        let path = dir.path().join("custom.json");
        assert_eq!(Config::default_path_with(path.to_str()).unwrap(), path);
        // Blank or absent falls back to the platform config directory.
        assert!(
            Config::default_path_with(Some("  "))
                .unwrap()
                .ends_with("config.json")
        );
        assert!(
            Config::default_path_with(None)
                .unwrap()
                .ends_with("config.json")
        );
    }

    #[test]
    fn parse_json_object() {
        let cfg = Config::parse_json(r#"{"addr":"B1-Y","connection":"usb","model":"b1"}"#).unwrap();
        assert_eq!(cfg.addr.as_deref(), Some("B1-Y"));
        assert_eq!(cfg.connection, Some(ConnPref::Usb));
        assert_eq!(cfg.model, Some(Model::B1));
        // alias
        let cfg = Config::parse_json(r#"{"connection":"serial"}"#).unwrap();
        assert_eq!(cfg.connection, Some(ConnPref::Usb));
    }

    #[test]
    fn to_json_pretty_roundtrip() {
        let cfg = Config {
            addr: Some("B1-X".into()),
            ..Default::default()
        };
        let s = cfg.to_json_pretty().unwrap();
        let back = Config::parse_json(&s).unwrap();
        assert_eq!(back, cfg);
    }
}