pinready 0.25.0

Cross-platform configurator and launcher supporting the adoption of Visual Pinball 10.8.1 — for testers and early adopters, not a replacement for a stable production setup
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
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
use std::io::BufReader;
use std::path::Path;

use base64::Engine;

// Illumination: all bulbs composited at this opacity
const BULB_OPACITY: f32 = 0.50;

// Brightness normalization: target median luminosity (0–255)
const TARGET_MEDIAN_LUM: f32 = 75.0;

// Max brightness adjustment factor to avoid blowing out dark images
const MAX_BRIGHTNESS_FACTOR: f32 = 2.5;
const MIN_BRIGHTNESS_FACTOR: f32 = 0.5;

/// Final resize target for both B2S and .vpx extraction — keeps the
/// in-memory DB blob small and the launcher rendering consistent.
const DISPLAY_WIDTH: u32 = 1280;
const DISPLAY_HEIGHT: u32 = 1024;

/// Decode base64 image data (with whitespace stripping) to a DynamicImage.
fn decode_b64_image(b64: &str) -> Option<image::DynamicImage> {
    let clean: String = b64.chars().filter(|c| !c.is_whitespace()).collect();
    let bytes = base64::engine::general_purpose::STANDARD
        .decode(&clean)
        .ok()?;
    image::load_from_memory(&bytes).ok()
}

/// Compute the median luminosity of an RGB image using its histogram.
pub(crate) fn median_luminosity(img: &image::RgbImage) -> f32 {
    let gray = image::DynamicImage::ImageRgb8(img.clone()).into_luma8();
    let mut hist = [0u32; 256];
    for p in gray.pixels() {
        hist[p[0] as usize] += 1;
    }
    let total = gray.pixels().count() as u32;
    let half = total / 2;
    let mut cumul = 0u32;
    for (i, &count) in hist.iter().enumerate() {
        cumul += count;
        if cumul >= half {
            return i as f32;
        }
    }
    0.0
}

/// Apply brightness adjustment to an RGB image.
pub(crate) fn adjust_brightness(img: &mut image::RgbImage, factor: f32) {
    for p in img.pixels_mut() {
        p[0] = (p[0] as f32 * factor).min(255.0) as u8;
        p[1] = (p[1] as f32 * factor).min(255.0) as u8;
        p[2] = (p[2] as f32 * factor).min(255.0) as u8;
    }
}

/// What `extract_backglass_from_b2s` needs from a `.directb2s`: the
/// backglass image, the grill height and the Backglass bulbs. Filled from
/// the strict `directb2s` crate when the file parses, else by
/// [`read_b2s_lenient`], so a file with a field the crate insists on
/// (`FileName` missing, `"-1"` where a `u8` is expected) still gets a
/// thumbnail. These are the only fields used anywhere in PinReady.
#[derive(Debug, Default, PartialEq)]
struct B2sData {
    backglass_image: String,
    grill_height: String,
    bulbs: Vec<B2sBulb>,
}

#[derive(Debug, Default, PartialEq)]
struct B2sBulb {
    parent: Option<String>,
    image: String,
    loc_x: String,
    loc_y: String,
}

impl From<directb2s::DirectB2SData> for B2sData {
    fn from(d: directb2s::DirectB2SData) -> Self {
        B2sData {
            backglass_image: d
                .images
                .backglass_image
                .map(|i| i.value)
                .unwrap_or_default(),
            grill_height: d.grill_height.value,
            bulbs: d
                .illumination
                .bulb
                .unwrap_or_default()
                .into_iter()
                .map(|b| B2sBulb {
                    parent: b.parent,
                    image: b.image,
                    loc_x: b.loc_x,
                    loc_y: b.loc_y,
                })
                .collect(),
        }
    }
}

/// Read only the fields of [`B2sData`] from a `.directb2s`, ignoring
/// everything else and every attribute that is missing or malformed.
/// Used when the strict `directb2s` parser refuses the file.
fn read_b2s_lenient<R: std::io::BufRead>(reader: R) -> Option<B2sData> {
    use quick_xml::events::Event;
    let mut xml = quick_xml::Reader::from_reader(reader);
    let mut buf = Vec::new();
    let mut out = B2sData::default();
    let mut path: Vec<Vec<u8>> = Vec::new();
    let mut seen_root = false;
    loop {
        let (ev, empty) = match xml.read_event_into(&mut buf) {
            Ok(Event::Eof) => break,
            Ok(Event::Start(e)) => (Some(e.into_owned()), false),
            Ok(Event::Empty(e)) => (Some(e.into_owned()), true),
            Ok(Event::End(_)) => {
                path.pop();
                (None, false)
            }
            Ok(_) => (None, false),
            // A broken document: keep what was read so far if it has an image.
            Err(_) => break,
        };
        buf.clear();
        let Some(e) = ev else { continue };
        let name = e.name().as_ref().as_bytes().to_vec();
        seen_root = true;
        let attr = |key: &str| -> Option<String> {
            e.attributes().flatten().find_map(|a| {
                (a.key.as_ref() == key)
                    .then(|| {
                        a.normalized_value(quick_xml::XmlVersion::Implicit1_0)
                            .ok()
                            .map(|v| v.into_owned())
                    })
                    .flatten()
            })
        };
        let parent = path.last().map(|p| p.as_slice());
        match (parent, name.as_slice()) {
            (Some(b"Images"), b"BackglassImage") => {
                out.backglass_image = attr("Value").unwrap_or_default();
            }
            (Some(b"Illumination"), b"Bulb") => out.bulbs.push(B2sBulb {
                parent: attr("Parent"),
                image: attr("Image").unwrap_or_default(),
                loc_x: attr("LocX").unwrap_or_default(),
                loc_y: attr("LocY").unwrap_or_default(),
            }),
            (Some(_), b"GrillHeight") => {
                out.grill_height = attr("Value").unwrap_or_default();
            }
            _ => {}
        }
        if !empty {
            path.push(name);
        }
    }
    (seen_root && !out.backglass_image.is_empty()).then_some(out)
}

/// Composite a single bulb sprite onto the base image at 50% opacity.
/// Only composites bulbs with Parent="Backglass".
fn composite_bulb(base: &mut image::RgbaImage, bulb: &B2sBulb) {
    // Only Backglass bulbs
    match &bulb.parent {
        Some(p) if p == "Backglass" => {}
        _ => return,
    }

    if bulb.image.is_empty() || bulb.image == "[stripped]" {
        return;
    }

    let x: i32 = bulb.loc_x.parse().unwrap_or(0);
    let y: i32 = bulb.loc_y.parse().unwrap_or(0);
    if x < 0 || y < 0 {
        return;
    }

    let sprite = match decode_b64_image(&bulb.image) {
        Some(img) => img.to_rgba8(),
        None => return,
    };

    let bw = base.width();
    let bh = base.height();
    for sy in 0..sprite.height() {
        for sx in 0..sprite.width() {
            let dx = x as u32 + sx;
            let dy = y as u32 + sy;
            if dx >= bw || dy >= bh {
                continue;
            }
            let src = sprite.get_pixel(sx, sy);
            let alpha = (src[3] as f32 / 255.0) * BULB_OPACITY;
            if alpha < 0.01 {
                continue;
            }
            let dst = base.get_pixel(dx, dy);
            let blend = |s: u8, d: u8| -> u8 {
                ((s as f32 * alpha) + (d as f32 * (1.0 - alpha))).min(255.0) as u8
            };
            base.put_pixel(
                dx,
                dy,
                image::Rgba([
                    blend(src[0], dst[0]),
                    blend(src[1], dst[1]),
                    blend(src[2], dst[2]),
                    255,
                ]),
            );
        }
    }
}

/// User-override source: check `<table_dir>/medias/launcher.(png|webp|jpg|jpeg)`
/// in that priority order. Returns the raw file bytes as-is — we don't
/// re-encode because (a) the user picked the format deliberately and (b) the
/// `image` crate's egui loader accepts PNG/WebP/JPEG uniformly.
///
/// Priority rationale: PNG first (lossless, most common for manually
/// assembled frames); WebP second (modern, often smaller at equal quality);
/// JPEG last (lossy, but widely supported).
pub fn extract_backglass_from_launcher_override(table_dir: &Path) -> Option<Vec<u8>> {
    let medias = table_dir.join("medias");
    for ext in ["png", "webp", "jpg", "jpeg"] {
        let candidate = medias.join(format!("launcher.{ext}"));
        if candidate.is_file() {
            match std::fs::read(&candidate) {
                Ok(bytes) if !bytes.is_empty() => {
                    log::info!("Backglass: user override {}", candidate.display());
                    return Some(bytes);
                }
                Ok(_) => {
                    log::warn!("Backglass: {} is empty, skipping", candidate.display());
                }
                Err(e) => {
                    log::warn!("Backglass: failed to read {}: {e}", candidate.display());
                }
            }
        }
    }
    None
}

/// vpinmediadb-cached source: check `<table_dir>/medias/bg.png`. This is
/// dropped by the catalog enrichment worker for every successfully-matched
/// table; reading it is cheap (no XML parse, no .vpx scan, no brightness
/// normalization — the upstream image is already production-ready).
/// Returns the raw PNG bytes as-is.
pub fn extract_backglass_from_vpinmediadb(table_dir: &Path) -> Option<Vec<u8>> {
    let candidate = table_dir.join("medias").join("bg.png");
    if !candidate.is_file() {
        return None;
    }
    match std::fs::read(&candidate) {
        Ok(bytes) if !bytes.is_empty() => {
            log::info!("Backglass: vpinmediadb cache {}", candidate.display());
            Some(bytes)
        }
        Ok(_) => {
            log::warn!("Backglass: {} is empty, skipping", candidate.display());
            None
        }
        Err(e) => {
            log::warn!("Backglass: failed to read {}: {e}", candidate.display());
            None
        }
    }
}

/// return it as JPEG bytes in memory. The caller stores the bytes in the
/// SQLite cache (`backglass` table) instead of writing a PNG next to the
/// table — see issue #6 for why we no longer drop `.pinready_bg_v*.png`
/// files in user table folders.
///
/// Pipeline:
///   1. Load BackglassImage (base artwork, typically dark/unlit state)
///   2. Crop out the grill/DMD area at the bottom using GrillHeight
///   3. Composite all Backglass bulbs at 50% opacity (GI + flashers)
///   4. Normalize brightness to median luminosity of 75
///   5. Resize to DISPLAY_WIDTH×DISPLAY_HEIGHT and encode as JPEG 85
pub fn extract_backglass_from_b2s(directb2s_path: &Path) -> Option<Vec<u8>> {
    log::info!(
        "Extracting backglass from .directb2s: {}",
        directb2s_path.display()
    );

    let file = match std::fs::File::open(directb2s_path) {
        Ok(f) => f,
        Err(e) => {
            log::error!("Failed to open {}: {e}", directb2s_path.display());
            return None;
        }
    };
    let reader = BufReader::new(file);
    let data: B2sData = match directb2s::read(reader) {
        Ok(d) => d.into(),
        Err(strict) => {
            // The strict parser insists on fields we never use. Read the
            // few we need on our own before giving up on the file.
            let again = std::fs::File::open(directb2s_path)
                .ok()
                .and_then(|f| read_b2s_lenient(BufReader::new(f)));
            match again {
                Some(d) => {
                    log::warn!(
                        "{}: strict parse failed ({strict}); read the backglass leniently",
                        directb2s_path.display()
                    );
                    d
                }
                None => {
                    log::error!("Failed to parse {}: {strict}", directb2s_path.display());
                    return None;
                }
            }
        }
    };

    // Step 1: Load base backglass image
    if data.backglass_image.is_empty() || data.backglass_image == "[stripped]" {
        log::warn!("No backglass image data in {}", directb2s_path.display());
        return None;
    }

    let img = decode_b64_image(&data.backglass_image)?;

    // Step 2: Crop grill/DMD area
    let grill_height: u32 = data.grill_height.trim().parse().unwrap_or(0);
    let crop_height = if grill_height > 0 && grill_height < img.height() {
        img.height() - grill_height
    } else {
        img.height()
    };
    let cropped = img.crop_imm(0, 0, img.width(), crop_height);
    let mut rgba = cropped.to_rgba8();

    // Step 3: Composite Backglass bulbs at 50% opacity
    let bulb_count = {
        let bg_bulbs: Vec<_> = data
            .bulbs
            .iter()
            .filter(|b| {
                b.parent.as_deref() == Some("Backglass")
                    && !b.image.is_empty()
                    && b.image != "[stripped]"
            })
            .collect();
        let count = bg_bulbs.len();
        if count > 0 {
            log::info!(
                "Compositing {} Backglass bulbs at {}% opacity",
                count,
                (BULB_OPACITY * 100.0) as u32
            );
        }
        for bulb in &data.bulbs {
            composite_bulb(&mut rgba, bulb);
        }
        count
    };

    // Step 4: Normalize brightness by median luminosity
    let mut rgb = image::DynamicImage::ImageRgba8(rgba).into_rgb8();
    let median = median_luminosity(&rgb);
    if median > 1.0 {
        let factor =
            (TARGET_MEDIAN_LUM / median).clamp(MIN_BRIGHTNESS_FACTOR, MAX_BRIGHTNESS_FACTOR);
        log::info!(
            "Brightness normalization: median {:.0} -> {:.0} (x{:.2})",
            median,
            median * factor,
            factor
        );
        adjust_brightness(&mut rgb, factor);
    } else {
        log::warn!(
            "Very dark image (median={:.0}), skipping normalization",
            median
        );
    }

    // Step 5: Resize and encode JPEG to memory
    let final_img = image::DynamicImage::ImageRgb8(rgb);
    let resized = final_img.resize(
        DISPLAY_WIDTH,
        DISPLAY_HEIGHT,
        image::imageops::FilterType::Lanczos3,
    );
    let bytes = encode_jpeg(&resized)?;
    log::info!(
        "Extracted backglass ({}x{}, {} bulbs, {} bytes)",
        resized.width(),
        resized.height(),
        bulb_count,
        bytes.len()
    );
    Some(bytes)
}

/// Extract a backglass image from inside a `.vpx` file by scanning its
/// `images/` catalog for any texture whose logical name contains
/// "backglass" (case-insensitive). Used as a fallback for tables shipped
/// without a companion `.directb2s` — issue #6 cases.
///
/// The `TableInfo.screenshot` field is empirically unusable (empty on
/// virtually every modern pincab table), so we ignore it and look at the
/// real image catalog. Examples this catches:
///
///   - Darkest Dungeon Original — `images/backglassimage.jpg`
///   - Die Hard Trilogy (VPW 2023) — `images/Backglass3scrnON.webp`,
///     `images/DHBackGlassOFF.webp`
///
/// The first matching image with decodable pixel data wins; we decode it
/// (the `.jpeg` field actually holds any encoded format — JPEG, PNG,
/// WebP, BMP), resize to the B2S pipeline dimensions, and return JPEG
/// bytes.
pub fn extract_backglass_from_vpx(vpx_path: &Path) -> Option<Vec<u8>> {
    log::info!(
        "Scanning .vpx images/ for a backglass asset: {}",
        vpx_path.display()
    );
    let mut vpx = match vpin::vpx::open(vpx_path) {
        Ok(f) => f,
        Err(e) => {
            log::error!("Failed to open .vpx {}: {e}", vpx_path.display());
            return None;
        }
    };
    let images = match vpx.read_images() {
        Ok(i) => i,
        Err(e) => {
            log::error!(
                "Failed to read image catalog from {}: {e}",
                vpx_path.display()
            );
            return None;
        }
    };

    // Collect all images whose name/path contains "backglass" and rank
    // them by encoded blob size. The real backglass is always a large
    // high-res photographic asset (200-500 KB typical), whereas slot
    // collisions — placeholder textures authors reuse across projects
    // (e.g. the Color_Black.jpg copied from Indianapolis 500 seen in
    // Darkest Dungeon) — compress to < 50 KB. Picking the biggest
    // candidate reliably selects the real one.
    let mut candidates: Vec<_> = images
        .iter()
        .filter(|img| {
            let name = img.name.to_lowercase();
            let path = img.path.to_lowercase();
            name.contains("backglass") || path.contains("backglass")
        })
        .filter_map(|img| {
            // Only entries with an encoded blob are usable; BMP-bits
            // (`bits` field, LZW-compressed BGRA) would need additional
            // decode code and are uncommon for backglass textures.
            let data = img.jpeg.as_ref()?.data.as_slice();
            if data.is_empty() {
                None
            } else {
                Some((img, data))
            }
        })
        .collect();
    if candidates.is_empty() {
        log::debug!(
            "No backglass candidate with encoded data in {}",
            vpx_path.display()
        );
        return None;
    }
    // Sort by blob size DESC, keep the biggest.
    candidates.sort_by_key(|(_, data)| std::cmp::Reverse(data.len()));
    for (img, data) in &candidates {
        log::info!(
            "  candidate: name={:?} path={:?} size={}",
            img.name,
            img.path,
            data.len()
        );
    }
    let (candidate, raw) = candidates[0];
    log::info!(
        "Picked largest backglass candidate: name={:?} ({} bytes)",
        candidate.name,
        raw.len()
    );
    let img = match image::load_from_memory(raw) {
        Ok(i) => i,
        Err(e) => {
            log::warn!(
                "Failed to decode backglass candidate {} from {}: {e}",
                candidate.name,
                vpx_path.display()
            );
            return None;
        }
    };
    let resized = img.resize(
        DISPLAY_WIDTH,
        DISPLAY_HEIGHT,
        image::imageops::FilterType::Lanczos3,
    );
    let bytes = encode_jpeg(&resized)?;
    log::info!(
        "Extracted embedded backglass from .vpx ({}x{}, {} bytes)",
        resized.width(),
        resized.height(),
        bytes.len()
    );
    Some(bytes)
}

/// JPEG quality for cached backglass blobs. 85 is the sweet spot for
/// photographic content: visually lossless at 1280×1024, ~5× smaller
/// than PNG, ~2× smaller than WebP lossless.
const BG_JPEG_QUALITY: u8 = 85;

/// Grid tile size. Stored apart from the full image (`backglass.thumb`)
/// and kept in the GPU for every table, so scrolling the grid never waits
/// for a decode: 480×384×4 bytes ≈ 0.74 MB per table.
pub const THUMB_WIDTH: u32 = 480;
pub const THUMB_HEIGHT: u32 = 384;

/// The grid thumbnail of an encoded backglass (any format the `image`
/// crate reads): fitted in `THUMB_WIDTH`×`THUMB_HEIGHT`, never enlarged,
/// JPEG. `None` if the bytes do not decode.
pub fn make_thumbnail(image_bytes: &[u8]) -> Option<Vec<u8>> {
    let img = image::load_from_memory(image_bytes).ok()?;
    let small = if img.width() <= THUMB_WIDTH && img.height() <= THUMB_HEIGHT {
        img
    } else {
        img.resize(
            THUMB_WIDTH,
            THUMB_HEIGHT,
            image::imageops::FilterType::Triangle,
        )
    };
    encode_jpeg(&small)
}

/// Encode a [`image::DynamicImage`] as JPEG bytes at `BG_JPEG_QUALITY`
/// for the SQLite cache. Uses `image::codecs::jpeg::JpegEncoder` because
/// `DynamicImage::write_to(ImageFormat::Jpeg)` doesn't expose a quality
/// parameter.
fn encode_jpeg(img: &image::DynamicImage) -> Option<Vec<u8>> {
    // JPEG can't encode with alpha — flatten to RGB first. Backglass
    // compositing is already done upstream; transparency isn't useful
    // in the cached display copy anyway.
    let rgb = img.to_rgb8();
    let mut buf = Vec::new();
    {
        let mut enc = image::codecs::jpeg::JpegEncoder::new_with_quality(
            std::io::Cursor::new(&mut buf),
            BG_JPEG_QUALITY,
        );
        enc.encode_image(&rgb).ok()?;
    }
    Some(buf)
}

#[cfg(test)]
mod tests {
    use super::*;
    use image::{Rgb, RgbImage};

    // --- median_luminosity ---

    #[test]
    fn median_luminosity_black_image() {
        let img = RgbImage::from_pixel(10, 10, Rgb([0, 0, 0]));
        assert!((median_luminosity(&img) - 0.0).abs() < 1.0);
    }

    #[test]
    fn median_luminosity_white_image() {
        let img = RgbImage::from_pixel(10, 10, Rgb([255, 255, 255]));
        assert!((median_luminosity(&img) - 255.0).abs() < 1.0);
    }

    #[test]
    fn median_luminosity_gray_image() {
        let img = RgbImage::from_pixel(10, 10, Rgb([128, 128, 128]));
        let median = median_luminosity(&img);
        assert!((median - 128.0).abs() < 2.0, "expected ~128, got {median}");
    }

    #[test]
    fn median_luminosity_mixed() {
        // Half black, half white → median should be around 128–255 range
        let mut img = RgbImage::new(10, 10);
        for x in 0..10 {
            for y in 0..10 {
                let val = if y < 5 { 0 } else { 255 };
                img.put_pixel(x, y, Rgb([val, val, val]));
            }
        }
        let median = median_luminosity(&img);
        // With 50 black and 50 white pixels, median is either 0 or 255
        // depending on which side crosses the half mark
        assert!(median == 0.0 || median == 255.0);
    }

    // --- adjust_brightness ---

    #[test]
    fn adjust_brightness_factor_1_unchanged() {
        let mut img = RgbImage::from_pixel(2, 2, Rgb([100, 150, 200]));
        adjust_brightness(&mut img, 1.0);
        let p = img.get_pixel(0, 0);
        assert_eq!(p, &Rgb([100, 150, 200]));
    }

    #[test]
    fn adjust_brightness_factor_2() {
        let mut img = RgbImage::from_pixel(1, 1, Rgb([50, 100, 200]));
        adjust_brightness(&mut img, 2.0);
        let p = img.get_pixel(0, 0);
        assert_eq!(p[0], 100);
        assert_eq!(p[1], 200);
        assert_eq!(p[2], 255); // clamped from 400
    }

    #[test]
    fn adjust_brightness_factor_half() {
        let mut img = RgbImage::from_pixel(1, 1, Rgb([100, 200, 50]));
        adjust_brightness(&mut img, 0.5);
        let p = img.get_pixel(0, 0);
        assert_eq!(p[0], 50);
        assert_eq!(p[1], 100);
        assert_eq!(p[2], 25);
    }

    #[test]
    fn adjust_brightness_clamps_to_255() {
        let mut img = RgbImage::from_pixel(1, 1, Rgb([255, 255, 255]));
        adjust_brightness(&mut img, 3.0);
        let p = img.get_pixel(0, 0);
        assert_eq!(p, &Rgb([255, 255, 255]));
    }

    // --- decode_b64_image ---

    #[test]
    fn decode_b64_invalid_returns_none() {
        assert!(decode_b64_image("not-valid-base64!!!").is_none());
    }

    #[test]
    fn decode_b64_empty_returns_none() {
        assert!(decode_b64_image("").is_none());
    }

    #[test]
    fn decode_b64_valid_png() {
        // Minimal 1x1 red PNG encoded in base64
        let png_b64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==";
        let img = decode_b64_image(png_b64);
        assert!(img.is_some());
        let img = img.unwrap();
        assert_eq!(img.width(), 1);
        assert_eq!(img.height(), 1);
    }

    #[test]
    fn decode_b64_with_whitespace() {
        // Same PNG with whitespace injected
        let png_b64 = "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAf\n FcSJAAAADUlEQVR42mP8/5+hHgAHggJ/PchI7wAAAABJRU5ErkJggg==";
        assert!(decode_b64_image(png_b64).is_some());
    }

    // --- lenient .directb2s reader ---

    const B2S_ODD: &str = r#"<?xml version="1.0" encoding="utf-8"?>
<DirectB2SData Version="1.2">
  <Name Value="odd"/>
  <Images>
    <BackglassOffImage Value="ignored"/>
    <BackglassImage Value="IMGDATA"/>
    <ThumbnailImage Value="ignored"/>
  </Images>
  <GrillHeight Value=" 120 "/>
  <Illumination>
    <Bulb ID="1" Parent="Backglass" Image="BULB1" LocX="10" LocY="20" RomIDType="-1" DualMode="-1"/>
    <Bulb ID="2" Parent="DMD" Image="BULB2" LocX="1" LocY="2"/>
    <Bulb ID="3" Image="BULB3"/>
  </Illumination>
</DirectB2SData>"#;

    #[test]
    fn lenient_reader_takes_what_the_strict_parser_refuses() {
        // No FileName on BackglassImage and "-1" where the crate wants a u8.
        assert!(directb2s::read(std::io::Cursor::new(B2S_ODD)).is_err());
        let d = read_b2s_lenient(std::io::Cursor::new(B2S_ODD)).unwrap();
        assert_eq!(d.backglass_image, "IMGDATA");
        assert_eq!(d.grill_height.trim(), "120");
        assert_eq!(d.bulbs.len(), 3);
        assert_eq!(
            d.bulbs[0],
            B2sBulb {
                parent: Some("Backglass".into()),
                image: "BULB1".into(),
                loc_x: "10".into(),
                loc_y: "20".into(),
            }
        );
        assert_eq!(d.bulbs[1].parent.as_deref(), Some("DMD"));
        assert_eq!(d.bulbs[2].parent, None);
        assert_eq!(d.bulbs[2].loc_x, "");
    }

    #[test]
    fn lenient_reader_needs_a_backglass_image() {
        let no_image = "<DirectB2SData><Images/><GrillHeight Value=\"1\"/></DirectB2SData>";
        assert!(read_b2s_lenient(std::io::Cursor::new(no_image)).is_none());
        assert!(read_b2s_lenient(std::io::Cursor::new("not xml at all")).is_none());
        assert!(read_b2s_lenient(std::io::Cursor::new("")).is_none());
    }

    #[test]
    fn lenient_reader_keeps_the_image_of_a_truncated_file() {
        let cut = &B2S_ODD[..B2S_ODD.find("<Illumination>").unwrap() + 20];
        let d = read_b2s_lenient(std::io::Cursor::new(cut)).unwrap();
        assert_eq!(d.backglass_image, "IMGDATA");
        assert!(d.bulbs.is_empty());
    }

    // --- grid thumbnails ---

    fn png_of(w: u32, h: u32) -> Vec<u8> {
        let img = image::DynamicImage::ImageRgb8(RgbImage::from_pixel(w, h, Rgb([90, 40, 160])));
        let mut buf = Vec::new();
        img.write_to(&mut std::io::Cursor::new(&mut buf), image::ImageFormat::Png)
            .unwrap();
        buf
    }

    #[test]
    fn thumbnail_fits_the_tile_and_keeps_the_ratio() {
        let t = make_thumbnail(&png_of(1280, 720)).unwrap();
        let img = image::load_from_memory(&t).unwrap();
        assert_eq!(img.width(), THUMB_WIDTH);
        assert_eq!(img.height(), 270);
        let tall = image::load_from_memory(&make_thumbnail(&png_of(1146, 1024)).unwrap()).unwrap();
        assert_eq!(tall.height(), THUMB_HEIGHT);
        assert!(tall.width() < THUMB_WIDTH);
    }

    #[test]
    fn thumbnail_never_enlarges_and_refuses_garbage() {
        let small = image::load_from_memory(&make_thumbnail(&png_of(200, 100)).unwrap()).unwrap();
        assert_eq!((small.width(), small.height()), (200, 100));
        assert!(make_thumbnail(b"not an image").is_none());
        assert!(make_thumbnail(&[]).is_none());
    }
}