native-gui-mock 1.0.0

Headless Mock backend and in-process E2E testing framework for Native GUI
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
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
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
//! Visual assertions, screenshot comparison, golden-image baselines, and diff generation.

use std::path::{Path, PathBuf};

use crate::e2e::{CaptureImage, Locator};
use native_gui_core::error::{GuiError, GuiResult};

/// A 2D pixel rectangle used for visual assertions, masks, and diff bounds.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Default)]
pub struct Rect {
    /// Horizontal coordinate of the top-left corner in pixels.
    pub x: u32,
    /// Vertical coordinate of the top-left corner in pixels.
    pub y: u32,
    /// Width in pixels.
    pub width: u32,
    /// Height in pixels.
    pub height: u32,
}

impl Rect {
    /// Creates a new rectangle.
    pub const fn new(x: u32, y: u32, width: u32, height: u32) -> Self {
        Self {
            x,
            y,
            width,
            height,
        }
    }

    /// Returns `true` if the rectangle contains the given pixel coordinate `(px, py)`.
    pub fn contains(&self, px: u32, py: u32) -> bool {
        px >= self.x
            && px < self.x.saturating_add(self.width)
            && py >= self.y
            && py < self.y.saturating_add(self.height)
    }

    /// Computes the minimal bounding rectangle enclosing both `self` and `other`.
    pub fn union(&self, other: &Rect) -> Rect {
        if self.width == 0 || self.height == 0 {
            return *other;
        }
        if other.width == 0 || other.height == 0 {
            return *self;
        }
        let min_x = self.x.min(other.x);
        let min_y = self.y.min(other.y);
        let max_x = (self.x + self.width).max(other.x + other.width);
        let max_y = (self.y + self.height).max(other.y + other.height);
        Rect {
            x: min_x,
            y: min_y,
            width: max_x - min_x,
            height: max_y - min_y,
        }
    }

    /// Computes the pixel area.
    pub fn area(&self) -> usize {
        (self.width as usize) * (self.height as usize)
    }
}

/// A region to ignore during visual screenshot comparison (e.g. clocks, carets, animations).
#[derive(Debug, Clone)]
pub enum MaskRegion {
    /// An absolute pixel bounding box.
    Rect(Rect),
    /// A widget resolved dynamically via a locator query.
    Element(Locator),
}

impl From<Rect> for MaskRegion {
    fn from(rect: Rect) -> Self {
        MaskRegion::Rect(rect)
    }
}

impl From<(u32, u32, u32, u32)> for MaskRegion {
    fn from((x, y, width, height): (u32, u32, u32, u32)) -> Self {
        MaskRegion::Rect(Rect::new(x, y, width, height))
    }
}

impl From<Locator> for MaskRegion {
    fn from(locator: Locator) -> Self {
        MaskRegion::Element(locator)
    }
}

/// Configuration options for visual comparison and golden-image assertions.
#[derive(Debug, Clone)]
pub struct ImageDiffOptions {
    /// Maximum allowed absolute difference per color channel (0-255).
    /// Defaults to 0 (exact pixel match).
    pub tolerance: u8,
    /// Maximum allowed percentage of mismatched pixels (0.0 to 100.0).
    /// For example, `1.0` allows up to 1.0% of evaluated pixels to differ.
    /// Defaults to 0.0 (zero differing pixels allowed).
    pub max_mismatch_percent: f64,
    /// Mask regions (pixel bounding boxes or locator queries) to ignore during comparison.
    pub masks: Vec<MaskRegion>,
    /// Optional directory where diff images and mismatch artifacts will be saved.
    pub diff_output_dir: Option<PathBuf>,
}

impl Default for ImageDiffOptions {
    fn default() -> Self {
        Self {
            tolerance: 0,
            max_mismatch_percent: 0.0,
            masks: Vec::new(),
            diff_output_dir: None,
        }
    }
}

impl ImageDiffOptions {
    /// Creates default comparison options (exact pixel match).
    pub fn new() -> Self {
        Self::default()
    }

    /// Sets the per-channel absolute color delta tolerance (0-255).
    pub fn with_tolerance(mut self, tolerance: u8) -> Self {
        self.tolerance = tolerance;
        self
    }

    /// Sets the maximum allowable percentage of mismatched pixels (0.0 to 100.0).
    pub fn with_max_mismatch_percent(mut self, percent: f64) -> Self {
        self.max_mismatch_percent = percent.clamp(0.0, 100.0);
        self
    }

    /// Adds a mask region to ignore during comparison.
    pub fn with_mask(mut self, mask: impl Into<MaskRegion>) -> Self {
        self.masks.push(mask.into());
        self
    }

    /// Adds a rectangular pixel region `(x, y, width, height)` to ignore.
    pub fn with_mask_rect(self, x: u32, y: u32, width: u32, height: u32) -> Self {
        self.with_mask(Rect::new(x, y, width, height))
    }

    /// Adds a widget locator to ignore during comparison.
    pub fn with_mask_element(self, locator: Locator) -> Self {
        self.with_mask(MaskRegion::Element(locator))
    }

    /// Sets a custom output directory for diff artifacts.
    pub fn with_diff_output_dir(mut self, dir: impl Into<PathBuf>) -> Self {
        self.diff_output_dir = Some(dir.into());
        self
    }
}

/// The outcome of comparing two images with tolerance and masks.
#[derive(Debug, Clone, PartialEq)]
pub struct ImageDiffResult {
    /// `true` if the images match within configured tolerances.
    pub passed: bool,
    /// Percentage of differing pixels relative to total evaluated pixels (0.0 to 100.0).
    pub mismatch_percentage: f64,
    /// Total count of pixels that differed beyond tolerance outside masked regions.
    pub mismatched_pixels: usize,
    /// Total evaluated pixels (excluding masked pixels).
    pub total_pixels: usize,
    /// Minimal bounding box containing all differing pixels, if any.
    pub diff_bounds: Option<Rect>,
    /// Generated diff image highlighting changed pixels in magenta against a faded baseline.
    pub diff_image: Option<CaptureImage>,
}

impl ImageDiffResult {
    /// Returns `true` if the visual comparison passed within tolerance.
    pub fn is_match(&self) -> bool {
        self.passed
    }

    /// Returns `true` if the visual comparison passed within tolerance.
    pub fn passed(&self) -> bool {
        self.passed
    }

    /// Returns the number of differing pixels.
    pub fn mismatched_pixels(&self) -> usize {
        self.mismatched_pixels
    }

    /// Returns the mismatch percentage.
    pub fn mismatch_percentage(&self) -> f64 {
        self.mismatch_percentage
    }

    /// Returns the bounding box of differences, if any.
    pub fn diff_bounds(&self) -> Option<Rect> {
        self.diff_bounds
    }

    /// Returns a reference to the generated diff image, if present.
    pub fn diff_image(&self) -> Option<&CaptureImage> {
        self.diff_image.as_ref()
    }

    /// Saves the diff image to disk as a PNG file.
    pub fn save_diff_image(&self, path: impl AsRef<Path>) -> GuiResult<()> {
        let diff_img = self.diff_image.as_ref().ok_or_else(|| {
            GuiError::Backend("e2e.visual: no diff image available to save".to_owned())
        })?;
        diff_img.save_png(path)
    }
}

/// Compares two images using the provided options and resolved rectangular mask areas.
pub fn compare_images(
    actual: &CaptureImage,
    expected: &CaptureImage,
    options: &ImageDiffOptions,
    resolved_masks: &[Rect],
) -> GuiResult<ImageDiffResult> {
    if actual.width != expected.width || actual.height != expected.height {
        // Dimension mismatch is an immediate full failure
        let max_w = actual.width.max(expected.width);
        let max_h = actual.height.max(expected.height);
        let total = (max_w as usize) * (max_h as usize);
        return Ok(ImageDiffResult {
            passed: false,
            mismatch_percentage: 100.0,
            mismatched_pixels: total,
            total_pixels: total,
            diff_bounds: Some(Rect::new(0, 0, max_w, max_h)),
            diff_image: None,
        });
    }

    let width = actual.width;
    let height = actual.height;
    let total_pixels_in_image = (width as usize) * (height as usize);

    let mut mismatched_pixels = 0usize;
    let mut total_evaluated = 0usize;

    let mut min_diff_x = u32::MAX;
    let mut min_diff_y = u32::MAX;
    let mut max_diff_x = 0u32;
    let mut max_diff_y = 0u32;

    let mut diff_buffer = vec![0u8; total_pixels_in_image * 4];

    for y in 0..height {
        for x in 0..width {
            let pixel_idx = ((y * width + x) * 4) as usize;

            // Check if this pixel falls inside any resolved mask
            let is_masked = resolved_masks.iter().any(|mask| mask.contains(x, y));
            if is_masked {
                // Masked region: fill with muted dark slate in diff visualization
                diff_buffer[pixel_idx] = 60;
                diff_buffer[pixel_idx + 1] = 64;
                diff_buffer[pixel_idx + 2] = 75;
                diff_buffer[pixel_idx + 3] = 255;
                continue;
            }

            total_evaluated += 1;

            let act_r = actual.data[pixel_idx];
            let act_g = actual.data[pixel_idx + 1];
            let act_b = actual.data[pixel_idx + 2];
            let act_a = actual.data[pixel_idx + 3];

            let exp_r = expected.data[pixel_idx];
            let exp_g = expected.data[pixel_idx + 1];
            let exp_b = expected.data[pixel_idx + 2];
            let exp_a = expected.data[pixel_idx + 3];

            let dr = act_r.abs_diff(exp_r);
            let dg = act_g.abs_diff(exp_g);
            let db = act_b.abs_diff(exp_b);
            let da = act_a.abs_diff(exp_a);

            let is_mismatch = dr > options.tolerance
                || dg > options.tolerance
                || db > options.tolerance
                || da > options.tolerance;

            if is_mismatch {
                mismatched_pixels += 1;
                min_diff_x = min_diff_x.min(x);
                min_diff_y = min_diff_y.min(y);
                max_diff_x = max_diff_x.max(x);
                max_diff_y = max_diff_y.max(y);

                // Highlight mismatched pixel in bright magenta/red [255, 0, 128, 255]
                diff_buffer[pixel_idx] = 255;
                diff_buffer[pixel_idx + 1] = 0;
                diff_buffer[pixel_idx + 2] = 128;
                diff_buffer[pixel_idx + 3] = 255;
            } else {
                // Matching pixel: fade expected baseline to soft muted background
                let fade_r = (exp_r / 3).saturating_add(120);
                let fade_g = (exp_g / 3).saturating_add(120);
                let fade_b = (exp_b / 3).saturating_add(120);
                diff_buffer[pixel_idx] = fade_r;
                diff_buffer[pixel_idx + 1] = fade_g;
                diff_buffer[pixel_idx + 2] = fade_b;
                diff_buffer[pixel_idx + 3] = 255;
            }
        }
    }

    let mismatch_percentage = if total_evaluated > 0 {
        (mismatched_pixels as f64 / total_evaluated as f64) * 100.0
    } else {
        0.0
    };

    let passed = mismatch_percentage <= options.max_mismatch_percent;

    let diff_bounds = if mismatched_pixels > 0 && min_diff_x <= max_diff_x {
        Some(Rect::new(
            min_diff_x,
            min_diff_y,
            max_diff_x - min_diff_x + 1,
            max_diff_y - min_diff_y + 1,
        ))
    } else {
        None
    };

    let diff_image = Some(CaptureImage::new(width, height, diff_buffer));

    Ok(ImageDiffResult {
        passed,
        mismatch_percentage,
        mismatched_pixels,
        total_pixels: total_evaluated,
        diff_bounds,
        diff_image,
    })
}

// ---------------------------------------------------------------------------
// Pure, Dependency-Free PNG & Deflate Decoding
// ---------------------------------------------------------------------------

const PNG_SIGNATURE: [u8; 8] = [0x89, b'P', b'N', b'G', 0x0D, 0x0A, 0x1A, 0x0A];

/// Decodes PNG file bytes into a [`CaptureImage`].
///
/// Supports 8-bit truecolor (RGB) and truecolor with alpha (RGBA) PNGs with standard
/// scanline filters (None, Sub, Up, Average, Paeth) and deflate decompression (uncompressed
/// and fixed-Huffman blocks).
pub fn decode_png_rgba(bytes: &[u8]) -> GuiResult<CaptureImage> {
    if bytes.len() < 8 || bytes[0..8] != PNG_SIGNATURE {
        return Err(GuiError::Backend("e2e.png: invalid PNG signature".into()));
    }

    let mut pos = 8;
    let mut width = 0u32;
    let mut height = 0u32;
    let mut color_type = 0u8;
    let mut idat_data = Vec::new();

    while pos + 8 <= bytes.len() {
        let chunk_len =
            u32::from_be_bytes([bytes[pos], bytes[pos + 1], bytes[pos + 2], bytes[pos + 3]])
                as usize;
        let chunk_type = &bytes[pos + 4..pos + 8];
        pos += 8;

        if pos + chunk_len > bytes.len() {
            return Err(GuiError::Backend(
                "e2e.png: unexpected end of chunk data".into(),
            ));
        }

        let chunk_payload = &bytes[pos..pos + chunk_len];
        pos += chunk_len;
        pos += 4; // Skip CRC

        match chunk_type {
            b"IHDR" => {
                if chunk_len < 13 {
                    return Err(GuiError::Backend("e2e.png: malformed IHDR chunk".into()));
                }
                width = u32::from_be_bytes([
                    chunk_payload[0],
                    chunk_payload[1],
                    chunk_payload[2],
                    chunk_payload[3],
                ]);
                height = u32::from_be_bytes([
                    chunk_payload[4],
                    chunk_payload[5],
                    chunk_payload[6],
                    chunk_payload[7],
                ]);
                let bit_depth = chunk_payload[8];
                color_type = chunk_payload[9];
                let compression = chunk_payload[10];
                let filter = chunk_payload[11];
                let interlace = chunk_payload[12];

                if bit_depth != 8 {
                    return Err(GuiError::Backend(format!(
                        "e2e.png: unsupported bit depth {bit_depth}"
                    )));
                }
                if color_type != 6 && color_type != 2 {
                    return Err(GuiError::Backend(format!("e2e.png: unsupported color type {color_type} (only RGB and RGBA supported)")));
                }
                if compression != 0 || filter != 0 {
                    return Err(GuiError::Backend(
                        "e2e.png: unknown compression or filter method".into(),
                    ));
                }
                if interlace != 0 {
                    return Err(GuiError::Backend(
                        "e2e.png: interlacing is not supported".into(),
                    ));
                }
            }
            b"IDAT" => {
                idat_data.extend_from_slice(chunk_payload);
            }
            b"IEND" => break,
            _ => {
                // Ignore auxiliary chunks (e.g. tEXt, pHYs, gAMA)
            }
        }
    }

    if width == 0 || height == 0 {
        return Err(GuiError::Backend(
            "e2e.png: missing or zero dimensions in IHDR".into(),
        ));
    }
    if idat_data.is_empty() {
        return Err(GuiError::Backend("e2e.png: missing IDAT image data".into()));
    }

    let decompressed = inflate_zlib(&idat_data)?;

    let bpp = if color_type == 6 { 4usize } else { 3usize };
    let stride = (width as usize) * bpp;
    let expected_len = (height as usize) * (1 + stride);

    if decompressed.len() < expected_len {
        return Err(GuiError::Backend(format!(
            "e2e.png: decompressed length {} is smaller than required scanline buffer {}",
            decompressed.len(),
            expected_len
        )));
    }

    let mut rgba_out = Vec::with_capacity((width as usize) * (height as usize) * 4);
    let mut prior_row = vec![0u8; stride];
    let mut current_row = vec![0u8; stride];
    let mut dec_pos = 0;

    for _y in 0..height {
        let filter_type = decompressed[dec_pos];
        dec_pos += 1;

        let raw_line = &decompressed[dec_pos..dec_pos + stride];
        dec_pos += stride;

        for x in 0..stride {
            let filt = raw_line[x];
            let a = if x >= bpp { current_row[x - bpp] } else { 0 };
            let b = prior_row[x];
            let c = if x >= bpp { prior_row[x - bpp] } else { 0 };

            let recon = match filter_type {
                0 => filt,
                1 => filt.wrapping_add(a),
                2 => filt.wrapping_add(b),
                3 => filt.wrapping_add(((a as u16 + b as u16) / 2) as u8),
                4 => filt.wrapping_add(paeth_predictor(a, b, c)),
                other => {
                    return Err(GuiError::Backend(format!(
                        "e2e.png: invalid scanline filter type {other}"
                    )));
                }
            };
            current_row[x] = recon;
        }

        if color_type == 6 {
            rgba_out.extend_from_slice(&current_row);
        } else {
            // RGB -> RGBA
            for px in (0..stride).step_by(3) {
                rgba_out.push(current_row[px]);
                rgba_out.push(current_row[px + 1]);
                rgba_out.push(current_row[px + 2]);
                rgba_out.push(255);
            }
        }

        prior_row.copy_from_slice(&current_row);
    }

    Ok(CaptureImage::new(width, height, rgba_out))
}

fn paeth_predictor(a: u8, b: u8, c: u8) -> u8 {
    let p = a as i32 + b as i32 - c as i32;
    let pa = (p - a as i32).abs();
    let pb = (p - b as i32).abs();
    let pc = (p - c as i32).abs();
    if pa <= pb && pa <= pc {
        a
    } else if pb <= pc {
        b
    } else {
        c
    }
}

/// Decompresses zlib-wrapped deflate data (RFC 1950 / RFC 1951).
fn inflate_zlib(data: &[u8]) -> GuiResult<Vec<u8>> {
    if data.len() < 6 {
        return Err(GuiError::Backend(
            "e2e.deflate: zlib stream too short".into(),
        ));
    }
    let cmf = data[0];
    let flg = data[1];
    let check = ((cmf as u16) << 8) | (flg as u16);
    if !check.is_multiple_of(31) {
        return Err(GuiError::Backend(
            "e2e.deflate: zlib header checksum failed".into(),
        ));
    }
    let cm = cmf & 0x0F;
    if cm != 8 {
        return Err(GuiError::Backend(format!(
            "e2e.deflate: unsupported compression method {cm}"
        )));
    }
    let fdict = (flg & 0x20) != 0;
    let offset = if fdict { 6 } else { 2 };
    if data.len() < offset + 4 {
        return Err(GuiError::Backend(
            "e2e.deflate: truncated zlib payload".into(),
        ));
    }

    let payload = &data[offset..data.len() - 4];
    inflate_raw(payload)
}

struct BitReader<'a> {
    bytes: &'a [u8],
    pos: usize,
    bits: u32,
    num_bits: u8,
}

impl<'a> BitReader<'a> {
    fn new(bytes: &'a [u8]) -> Self {
        Self {
            bytes,
            pos: 0,
            bits: 0,
            num_bits: 0,
        }
    }

    fn ensure_bits(&mut self, n: u8) {
        while self.num_bits < n && self.pos < self.bytes.len() {
            self.bits |= (self.bytes[self.pos] as u32) << self.num_bits;
            self.num_bits += 8;
            self.pos += 1;
        }
    }

    fn read_bits(&mut self, n: u8) -> u32 {
        if n == 0 {
            return 0;
        }
        self.ensure_bits(n);
        let mask = (1u32 << n) - 1;
        let val = self.bits & mask;
        self.bits >>= n;
        self.num_bits = self.num_bits.saturating_sub(n);
        val
    }

    fn align_byte(&mut self) {
        let discard = self.num_bits % 8;
        self.bits >>= discard;
        self.num_bits -= discard;
        self.bits = 0;
        self.num_bits = 0;
    }

    fn read_u16_le(&mut self) -> GuiResult<u16> {
        self.align_byte();
        if self.pos + 2 > self.bytes.len() {
            return Err(GuiError::Backend(
                "e2e.deflate: unexpected end of stream reading u16".into(),
            ));
        }
        let val = u16::from_le_bytes([self.bytes[self.pos], self.bytes[self.pos + 1]]);
        self.pos += 2;
        Ok(val)
    }

    fn read_bytes(&mut self, len: usize) -> GuiResult<&'a [u8]> {
        self.align_byte();
        if self.pos + len > self.bytes.len() {
            return Err(GuiError::Backend(
                "e2e.deflate: unexpected end of stream reading bytes".into(),
            ));
        }
        let slice = &self.bytes[self.pos..self.pos + len];
        self.pos += len;
        Ok(slice)
    }
}

/// Raw RFC 1951 deflate decompressor.
fn inflate_raw(data: &[u8]) -> GuiResult<Vec<u8>> {
    let mut reader = BitReader::new(data);
    let mut out = Vec::new();

    loop {
        let bfinal = reader.read_bits(1);
        let btype = reader.read_bits(2);

        match btype {
            0 => {
                // Stored / uncompressed block
                let len = reader.read_u16_le()? as usize;
                let nlen = reader.read_u16_le()? as usize;
                if (len ^ 0xFFFF) != nlen {
                    return Err(GuiError::Backend(
                        "e2e.deflate: invalid stored block length check".into(),
                    ));
                }
                let bytes = reader.read_bytes(len)?;
                out.extend_from_slice(bytes);
            }
            1 => {
                // Fixed Huffman block
                inflate_fixed_huffman(&mut reader, &mut out)?;
            }
            2 => {
                // Dynamic Huffman block
                inflate_dynamic_huffman(&mut reader, &mut out)?;
            }
            _ => {
                return Err(GuiError::Backend(
                    "e2e.deflate: reserved block type 3".into(),
                ));
            }
        }

        if bfinal != 0 {
            break;
        }
    }

    Ok(out)
}

fn inflate_fixed_huffman(reader: &mut BitReader, out: &mut Vec<u8>) -> GuiResult<()> {
    loop {
        let code = decode_fixed_lit_len(reader);
        match code {
            0..=255 => out.push(code as u8),
            256 => break, // End of block
            257..=285 => {
                let length = decode_length(code, reader)?;
                let dist_code = reader.read_bits(5) as u16;
                let distance = decode_distance(dist_code, reader)?;
                copy_match(out, length, distance)?;
            }
            _ => {
                return Err(GuiError::Backend(
                    "e2e.deflate: invalid literal/length code in fixed Huffman".into(),
                ))
            }
        }
    }
    Ok(())
}

fn decode_fixed_lit_len(reader: &mut BitReader) -> u16 {
    // RFC 1951 fixed Huffman lit/len tree:
    // 0..143: 8 bits (00110000..10111111) -> 0x30..0xBF
    // 144..255: 9 bits (110010000..111111111) -> 0x190..0x1FF
    // 256..279: 7 bits (0000000..0010111) -> 0x00..0x17
    // 280..287: 8 bits (11000000..11000111) -> 0xC0..0xC7
    reader.ensure_bits(9);
    // Reverse bit order for Huffman code
    let bits7 = reverse_bits(reader.bits & 0x7F, 7);
    if bits7 <= 0x17 {
        reader.read_bits(7);
        return 256 + bits7;
    }
    let bits8 = reverse_bits(reader.bits & 0xFF, 8);
    if bits8 <= 0xBF {
        reader.read_bits(8);
        return bits8 - 0x30;
    }
    if (0xC0..=0xC7).contains(&bits8) {
        reader.read_bits(8);
        return 280 + (bits8 - 0xC0);
    }
    let bits9 = reverse_bits(reader.bits & 0x1FF, 9);
    reader.read_bits(9);
    144 + (bits9 - 0x190)
}

fn reverse_bits(mut val: u32, n: u8) -> u16 {
    let mut res = 0;
    for _ in 0..n {
        res = (res << 1) | (val & 1);
        val >>= 1;
    }
    res as u16
}

fn decode_length(code: u16, reader: &mut BitReader) -> GuiResult<usize> {
    const LENGTH_BASE: [u16; 29] = [
        3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115,
        131, 163, 195, 227, 258,
    ];
    const EXTRA_BITS: [u8; 29] = [
        0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0,
    ];
    let idx = (code - 257) as usize;
    if idx >= 29 {
        return Err(GuiError::Backend("e2e.deflate: invalid length code".into()));
    }
    let extra = reader.read_bits(EXTRA_BITS[idx]) as usize;
    Ok(LENGTH_BASE[idx] as usize + extra)
}

fn decode_distance(code: u16, reader: &mut BitReader) -> GuiResult<usize> {
    const DIST_BASE: [u16; 30] = [
        1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537,
        2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577,
    ];
    const EXTRA_BITS: [u8; 30] = [
        0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12,
        13, 13,
    ];
    let idx = code as usize;
    if idx >= 30 {
        return Err(GuiError::Backend(
            "e2e.deflate: invalid distance code".into(),
        ));
    }
    let extra = reader.read_bits(EXTRA_BITS[idx]) as usize;
    Ok(DIST_BASE[idx] as usize + extra)
}

fn copy_match(out: &mut Vec<u8>, length: usize, distance: usize) -> GuiResult<()> {
    if distance == 0 || distance > out.len() {
        return Err(GuiError::Backend(format!(
            "e2e.deflate: match distance {distance} exceeds current output length {}",
            out.len()
        )));
    }
    let start = out.len() - distance;
    for i in 0..length {
        let b = out[start + i];
        out.push(b);
    }
    Ok(())
}

fn inflate_dynamic_huffman(reader: &mut BitReader, out: &mut Vec<u8>) -> GuiResult<()> {
    let hlit = (reader.read_bits(5) + 257) as usize;
    let hdist = (reader.read_bits(5) + 1) as usize;
    let hclen = (reader.read_bits(4) + 4) as usize;

    const CL_ORDER: [usize; 19] = [
        16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15,
    ];
    let mut cl_lengths = [0u8; 19];
    for i in 0..hclen {
        cl_lengths[CL_ORDER[i]] = reader.read_bits(3) as u8;
    }

    let cl_tree = HuffmanTable::build(&cl_lengths)?;

    let mut lengths = Vec::with_capacity(hlit + hdist);
    while lengths.len() < hlit + hdist {
        let sym = cl_tree.decode(reader)?;
        match sym {
            0..=15 => lengths.push(sym as u8),
            16 => {
                let repeat = (reader.read_bits(2) + 3) as usize;
                let last = *lengths.last().ok_or_else(|| {
                    GuiError::Backend("e2e.deflate: repeat with no prior code".into())
                })?;
                for _ in 0..repeat {
                    lengths.push(last);
                }
            }
            17 => {
                let repeat = (reader.read_bits(3) + 3) as usize;
                lengths.extend(std::iter::repeat_n(0, repeat));
            }
            18 => {
                let repeat = (reader.read_bits(7) + 11) as usize;
                lengths.extend(std::iter::repeat_n(0, repeat));
            }
            _ => {
                return Err(GuiError::Backend(
                    "e2e.deflate: invalid code length symbol".into(),
                ))
            }
        }
    }

    let lit_tree = HuffmanTable::build(&lengths[..hlit])?;
    let dist_tree = HuffmanTable::build(&lengths[hlit..])?;

    loop {
        let sym = lit_tree.decode(reader)?;
        match sym {
            0..=255 => out.push(sym as u8),
            256 => break,
            257..=285 => {
                let length = decode_length(sym, reader)?;
                let dist_code = dist_tree.decode(reader)?;
                let distance = decode_distance(dist_code, reader)?;
                copy_match(out, length, distance)?;
            }
            _ => {
                return Err(GuiError::Backend(
                    "e2e.deflate: invalid symbol in dynamic block".into(),
                ))
            }
        }
    }

    Ok(())
}

struct HuffmanTable {
    symbols: Vec<u16>,
    codes: Vec<u16>,
    lengths: Vec<u8>,
}

impl HuffmanTable {
    fn build(lengths: &[u8]) -> GuiResult<Self> {
        let mut max_len = 0;
        for &l in lengths {
            if l > max_len {
                max_len = l;
            }
        }
        if max_len == 0 {
            return Ok(Self {
                symbols: Vec::new(),
                codes: Vec::new(),
                lengths: Vec::new(),
            });
        }

        let mut bl_count = vec![0u16; (max_len + 1) as usize];
        for &l in lengths {
            if l > 0 {
                bl_count[l as usize] += 1;
            }
        }

        let mut next_code = vec![0u16; (max_len + 1) as usize];
        let mut code = 0u16;
        for bits in 1..=max_len {
            code = (code + bl_count[(bits - 1) as usize]) << 1;
            next_code[bits as usize] = code;
        }

        let mut symbols = Vec::new();
        let mut codes = Vec::new();
        let mut lens = Vec::new();

        for (sym, &len) in lengths.iter().enumerate() {
            if len > 0 {
                let c = next_code[len as usize];
                next_code[len as usize] += 1;
                symbols.push(sym as u16);
                codes.push(c);
                lens.push(len);
            }
        }

        Ok(Self {
            symbols,
            codes,
            lengths: lens,
        })
    }

    fn decode(&self, reader: &mut BitReader) -> GuiResult<u16> {
        let mut curr_code = 0u16;
        for bits in 1..=15 {
            let bit = reader.read_bits(1) as u16;
            curr_code = (curr_code << 1) | bit;
            for (i, &l) in self.lengths.iter().enumerate() {
                if l == bits && self.codes[i] == curr_code {
                    return Ok(self.symbols[i]);
                }
            }
        }
        Err(GuiError::Backend(
            "e2e.deflate: huffman symbol not found".into(),
        ))
    }
}