euv-cli 0.51.0

Cross-platform CLI tool for the euv native UI framework supporting run, build, check, fmt, doctor, new, and Hyperlane SSE dynamic updates across all supported platforms.
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
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
use super::*;

/// Decodes a standard RFC 4648 Base64 string into raw bytes.
///
/// # Arguments
///
/// - `&str` - Base64-encoded ASCII text (whitespace ignored).
///
/// # Returns
///
/// - `io::Result<Vec<u8>>` - Decoded byte vector or format error.
pub fn decode_base64(input: &str) -> io::Result<Vec<u8>> {
    let mut out: Vec<u8> = Vec::with_capacity((input.len() * 3) / 4);
    let mut quartet: [u8; 4] = [0u8; 4];
    let mut q_len: usize = 0;
    let mut pad_count: usize = 0;
    for byte_val in input.bytes() {
        if byte_val.is_ascii_whitespace() {
            continue;
        }
        if byte_val == b'=' {
            pad_count += 1;
            quartet[q_len] = 0;
            q_len += 1;
        } else {
            if pad_count > 0 {
                return Err(Error::new(ErrorKind::InvalidData, ERR_BASE64_INVALID));
            }
            let decoded: u8 = decode_base64_char(byte_val)
                .ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_BASE64_INVALID))?;
            quartet[q_len] = decoded;
            q_len += 1;
        }
        if q_len == 4 {
            let triple: u32 = (u32::from(quartet[0]) << 18)
                | (u32::from(quartet[1]) << 12)
                | (u32::from(quartet[2]) << 6)
                | u32::from(quartet[3]);
            out.push(((triple >> 16) & 0xFF) as u8);
            if pad_count < 2 {
                out.push(((triple >> 8) & 0xFF) as u8);
            }
            if pad_count < 1 {
                out.push((triple & 0xFF) as u8);
            }
            q_len = 0;
            pad_count = 0;
        }
    }
    if q_len != 0 {
        return Err(Error::new(ErrorKind::InvalidData, ERR_BASE64_INVALID));
    }
    Ok(out)
}

/// Encodes raw bytes as standard RFC 4648 Base64 ASCII text.
///
/// # Arguments
///
/// - `&[u8]` - Raw byte slice.
///
/// # Returns
///
/// - `String` - Base64-encoded ASCII string.
#[must_use]
pub fn encode_base64(bytes: &[u8]) -> String {
    let mut out: String = String::with_capacity(bytes.len().div_ceil(3) * 4);
    let mut idx: usize = 0;
    while idx < bytes.len() {
        let first: u32 = u32::from(bytes[idx]);
        let has_second: bool = idx + 1 < bytes.len();
        let has_third: bool = idx + 2 < bytes.len();
        let second: u32 = if has_second {
            u32::from(bytes[idx + 1])
        } else {
            0
        };
        let third: u32 = if has_third {
            u32::from(bytes[idx + 2])
        } else {
            0
        };
        let triple: u32 = (first << 16) | (second << 8) | third;
        out.push(BASE64_ALPHABET[((triple >> 18) & 0x3F) as usize] as char);
        out.push(BASE64_ALPHABET[((triple >> 12) & 0x3F) as usize] as char);
        if has_second {
            out.push(BASE64_ALPHABET[((triple >> 6) & 0x3F) as usize] as char);
        } else {
            out.push('=');
        }
        if has_third {
            out.push(BASE64_ALPHABET[(triple & 0x3F) as usize] as char);
        } else {
            out.push('=');
        }
        idx += 3;
    }
    out
}

/// Returns the embedded lossless 96x96 canonical Euv brand PNG bytes with zero network access.
///
/// # Returns
///
/// - `io::Result<Vec<u8>>` - Raw PNG bytes decoded from `DEFAULT_BRAND_LOGO_DATA_URI`.
pub fn default_brand_logo_png_bytes() -> io::Result<Vec<u8>> {
    let payload: &str = DEFAULT_BRAND_LOGO_DATA_URI
        .strip_prefix(PNG_DATA_URI_PREFIX)
        .ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_BASE64_INVALID))?;
    decode_base64(payload)
}

/// Resolves source icon PNG bytes from explicit path, `EUV_APP_ICON`, or embedded default logo.
///
/// # Arguments
///
/// - `Option<&Path>` - Optional explicit PNG icon path override.
///
/// # Returns
///
/// - `io::Result<Vec<u8>>` - Validated PNG byte buffer.
pub fn resolve_icon_png_bytes(custom_icon: Option<&Path>) -> io::Result<Vec<u8>> {
    if let Some(path) = custom_icon {
        let bytes: Vec<u8> = fs::read(path)?;
        if bytes.starts_with(&PNG_SIGNATURE) {
            return Ok(bytes);
        }
        return Err(Error::new(
            ErrorKind::InvalidInput,
            format!("{ERR_ICON_SOURCE_INVALID}: {}", path.display()),
        ));
    }
    if let Ok(env_val) = env::var(ENV_APP_ICON) {
        let trimmed: &str = env_val.trim();
        if !trimmed.is_empty() {
            let env_path: PathBuf = PathBuf::from(trimmed);
            if env_path.is_file() {
                let bytes: Vec<u8> = fs::read(&env_path)?;
                if bytes.starts_with(&PNG_SIGNATURE) {
                    return Ok(bytes);
                }
            }
        }
    }
    default_brand_logo_png_bytes()
}

/// Resolves and decodes the source icon into an RGBA8 raster image.
///
/// # Arguments
///
/// - `Option<&Path>` - Optional explicit PNG icon path override.
///
/// # Returns
///
/// - `io::Result<RgbaImage>` - Decoded RGBA8 image.
pub fn resolve_icon_rgba(custom_icon: Option<&Path>) -> io::Result<RgbaImage> {
    let png_bytes: Vec<u8> = resolve_icon_png_bytes(custom_icon)?;
    decode_png_rgba(&png_bytes)
}

/// Resolves an inline `data:image/png;base64,...` URI for HTML favicons and splash screens.
///
/// # Arguments
///
/// - `Option<&Path>` - Optional custom PNG icon path override.
///
/// # Returns
///
/// - `io::Result<String>` - Self-contained PNG data URI.
pub fn resolve_icon_data_uri(custom_icon: Option<&Path>) -> io::Result<String> {
    let env_icon: Option<PathBuf> = env::var(ENV_APP_ICON)
        .ok()
        .map(|val: String| val.trim().to_string())
        .filter(|val: &String| !val.is_empty())
        .map(PathBuf::from)
        .filter(|path: &PathBuf| path.is_file());
    if custom_icon.is_none() && env_icon.is_none() {
        return Ok(DEFAULT_BRAND_LOGO_DATA_URI.to_string());
    }
    let rgba: RgbaImage = resolve_icon_rgba(custom_icon)?;
    let resized: RgbaImage = resize_rgba(&rgba, ICON_DATA_URI_SIZE, ICON_DATA_URI_SIZE);
    let png_bytes: Vec<u8> = encode_png_rgba(&resized);
    let encoded: String = encode_base64(&png_bytes);
    Ok(format!("{PNG_DATA_URI_PREFIX}{encoded}"))
}

/// Decodes a non-interlaced PNG image (grayscale, RGB, palette+tRNS, gray+alpha, RGBA) to `RgbaImage`.
///
/// # Arguments
///
/// - `&[u8]` - Raw PNG file bytes.
///
/// # Returns
///
/// - `io::Result<RgbaImage>` - Decoded RGBA8 pixel buffer.
pub fn decode_png_rgba(png_bytes: &[u8]) -> io::Result<RgbaImage> {
    if png_bytes.len() < 33 || !png_bytes.starts_with(&PNG_SIGNATURE) {
        return Err(Error::new(ErrorKind::InvalidData, ERR_PNG_INVALID));
    }
    let mut pos: usize = PNG_SIGNATURE.len();
    let mut width: u32 = 0;
    let mut height: u32 = 0;
    let mut bit_depth: u8 = 0;
    let mut color_type: u8 = 0;
    let mut seen_ihdr: bool = false;
    let mut palette: Vec<[u8; 3]> = Vec::new();
    let mut trns: Vec<u8> = Vec::new();
    let mut idat_all: Vec<u8> = Vec::new();
    while pos + 12 <= png_bytes.len() {
        let chunk_len: usize = read_be_u32(png_bytes, pos)? as usize;
        let tag: [u8; 4] = [
            png_bytes[pos + 4],
            png_bytes[pos + 5],
            png_bytes[pos + 6],
            png_bytes[pos + 7],
        ];
        let data_start: usize = pos + 8;
        let data_end: usize = data_start
            .checked_add(chunk_len)
            .ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_PNG_INVALID))?;
        let crc_end: usize = data_end
            .checked_add(4)
            .ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_PNG_INVALID))?;
        let chunk_data: &[u8] = png_bytes
            .get(data_start..data_end)
            .ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_PNG_INVALID))?;
        if crc_end > png_bytes.len() {
            return Err(Error::new(ErrorKind::InvalidData, ERR_PNG_INVALID));
        }
        if tag == PNG_CHUNK_IHDR {
            if chunk_data.len() != 13 {
                return Err(Error::new(ErrorKind::InvalidData, ERR_PNG_INVALID));
            }
            width = read_be_u32(chunk_data, 0)?;
            height = read_be_u32(chunk_data, 4)?;
            bit_depth = chunk_data[8];
            color_type = chunk_data[9];
            let comp_method: u8 = chunk_data[10];
            let filter_method: u8 = chunk_data[11];
            let interlace_method: u8 = chunk_data[12];
            let supported_depth: bool = [1u8, 2, 4, 8].contains(&bit_depth);
            if width == 0
                || height == 0
                || comp_method != 0
                || filter_method != 0
                || interlace_method != 0
                || !supported_depth
            {
                return Err(Error::new(ErrorKind::InvalidData, ERR_PNG_UNSUPPORTED));
            }
            seen_ihdr = true;
        } else if tag == PNG_CHUNK_PLTE {
            if !chunk_data.len().is_multiple_of(3) {
                return Err(Error::new(ErrorKind::InvalidData, ERR_PNG_INVALID));
            }
            palette.clear();
            let mut idx: usize = 0;
            while idx < chunk_data.len() {
                palette.push([chunk_data[idx], chunk_data[idx + 1], chunk_data[idx + 2]]);
                idx += 3;
            }
        } else if tag == PNG_CHUNK_TRNS {
            trns = chunk_data.to_vec();
        } else if tag == PNG_CHUNK_IDAT {
            idat_all.extend_from_slice(chunk_data);
        } else if tag == PNG_CHUNK_IEND {
            break;
        }
        pos = crc_end;
    }
    if !seen_ihdr || idat_all.is_empty() {
        return Err(Error::new(ErrorKind::InvalidData, ERR_PNG_INVALID));
    }
    let samples_per_pixel: usize = match color_type {
        0 | 3 => 1,
        2 => 3,
        4 => 2,
        6 => 4,
        _ => return Err(Error::new(ErrorKind::InvalidData, ERR_PNG_UNSUPPORTED)),
    };
    let bits_per_pixel: usize = samples_per_pixel * usize::from(bit_depth);
    let stride: usize = (usize::try_from(width).unwrap_or(0) * bits_per_pixel).div_ceil(8);
    let filter_bpp: usize = cmp::max(1, bits_per_pixel.div_ceil(8));
    let expected_raw_len: usize = (stride + 1)
        .checked_mul(usize::try_from(height).unwrap_or(0))
        .ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_PNG_INVALID))?;
    let raw_scanlines: Vec<u8> = zlib_decompress(&idat_all)?;
    if raw_scanlines.len() < expected_raw_len {
        return Err(Error::new(ErrorKind::InvalidData, ERR_PNG_INVALID));
    }
    let mut prev_row: Vec<u8> = vec![0u8; stride];
    let mut curr_row: Vec<u8> = vec![0u8; stride];
    let mut rgba: Vec<u8> = Vec::with_capacity(
        usize::try_from(width).unwrap_or(0) * usize::try_from(height).unwrap_or(0) * 4,
    );
    let height_usize: usize = usize::try_from(height).unwrap_or(0);
    let width_usize: usize = usize::try_from(width).unwrap_or(0);
    let mut row_idx: usize = 0;
    while row_idx < height_usize {
        let row_start: usize = row_idx * (stride + 1);
        let filter_type: u8 = raw_scanlines[row_start];
        let src_row: &[u8] = &raw_scanlines[row_start + 1..row_start + 1 + stride];
        unfilter_png_scanline(filter_type, src_row, &prev_row, &mut curr_row, filter_bpp)?;
        expand_png_row_to_rgba(
            &curr_row,
            width_usize,
            bit_depth,
            color_type,
            &palette,
            &trns,
            &mut rgba,
        )?;
        prev_row.copy_from_slice(&curr_row);
        row_idx += 1;
    }
    Ok(RgbaImage::new(width, height, rgba))
}

/// Resizes an `RgbaImage` cleanly using premultiplied-alpha box averaging (downscale) or bilinear interpolation (upscale).
///
/// # Arguments
///
/// - `&RgbaImage` - Source RGBA8 image.
/// - `u32` - Target width in pixels (`>= 1`).
/// - `u32` - Target height in pixels (`>= 1`).
///
/// # Returns
///
/// - `RgbaImage` - Resized RGBA8 image.
#[must_use]
pub fn resize_rgba(image: &RgbaImage, target_width: u32, target_height: u32) -> RgbaImage {
    let dst_w: u32 = cmp::max(1, target_width);
    let dst_h: u32 = cmp::max(1, target_height);
    let src_w: u32 = image.get_width();
    let src_h: u32 = image.get_height();
    if src_w == dst_w && src_h == dst_h {
        return image.clone();
    }
    let src_pixels: &[u8] = image.get_pixels();
    let mut dst_pixels: Vec<u8> = vec![0u8; (dst_w as usize) * (dst_h as usize) * 4];
    let scale_x: f64 = f64::from(src_w) / f64::from(dst_w);
    let scale_y: f64 = f64::from(src_h) / f64::from(dst_h);
    if dst_w < src_w && dst_h < src_h {
        let mut dst_y: u32 = 0;
        while dst_y < dst_h {
            let y0: f64 = f64::from(dst_y) * scale_y;
            let y1: f64 = (f64::from(dst_y) + 1.0) * scale_y;
            let row_start: u32 = (y0.floor() as u32).min(src_h - 1);
            let row_end: u32 = (y1.ceil() as u32).min(src_h);
            let mut dst_x: u32 = 0;
            while dst_x < dst_w {
                let x0: f64 = f64::from(dst_x) * scale_x;
                let x1: f64 = (f64::from(dst_x) + 1.0) * scale_x;
                let col_start: u32 = (x0.floor() as u32).min(src_w - 1);
                let col_end: u32 = (x1.ceil() as u32).min(src_w);
                let mut acc_r: f64 = 0.0;
                let mut acc_g: f64 = 0.0;
                let mut acc_b: f64 = 0.0;
                let mut acc_a: f64 = 0.0;
                let mut weight_sum: f64 = 0.0;
                let mut sy: u32 = row_start;
                while sy < row_end {
                    let wy: f64 = (f64::from(sy + 1).min(y1) - f64::from(sy).max(y0)).max(0.0);
                    let mut sx: u32 = col_start;
                    while sx < col_end {
                        let wx: f64 = (f64::from(sx + 1).min(x1) - f64::from(sx).max(x0)).max(0.0);
                        let weight: f64 = wx * wy;
                        let offset: usize = ((sy * src_w + sx) as usize) * 4;
                        let alpha: f64 = f64::from(src_pixels[offset + 3]) / 255.0;
                        acc_r += f64::from(src_pixels[offset]) * alpha * weight;
                        acc_g += f64::from(src_pixels[offset + 1]) * alpha * weight;
                        acc_b += f64::from(src_pixels[offset + 2]) * alpha * weight;
                        acc_a += alpha * weight;
                        weight_sum += weight;
                        sx += 1;
                    }
                    sy += 1;
                }
                let dst_offset: usize = ((dst_y * dst_w + dst_x) as usize) * 4;
                if weight_sum > 0.0 && acc_a > 1e-6 {
                    let out_a: f64 = (acc_a / weight_sum).clamp(0.0, 1.0);
                    dst_pixels[dst_offset] = (acc_r / acc_a).round().clamp(0.0, 255.0) as u8;
                    dst_pixels[dst_offset + 1] = (acc_g / acc_a).round().clamp(0.0, 255.0) as u8;
                    dst_pixels[dst_offset + 2] = (acc_b / acc_a).round().clamp(0.0, 255.0) as u8;
                    dst_pixels[dst_offset + 3] = (out_a * 255.0).round().clamp(0.0, 255.0) as u8;
                }
                dst_x += 1;
            }
            dst_y += 1;
        }
    } else {
        let mut dst_y: u32 = 0;
        while dst_y < dst_h {
            let src_fy: f64 =
                ((f64::from(dst_y) + 0.5) * scale_y - 0.5).clamp(0.0, f64::from(src_h - 1));
            let y_lo: u32 = src_fy.floor() as u32;
            let y_hi: u32 = cmp::min(y_lo + 1, src_h - 1);
            let ty: f64 = src_fy - f64::from(y_lo);
            let mut dst_x: u32 = 0;
            while dst_x < dst_w {
                let src_fx: f64 =
                    ((f64::from(dst_x) + 0.5) * scale_x - 0.5).clamp(0.0, f64::from(src_w - 1));
                let x_lo: u32 = src_fx.floor() as u32;
                let x_hi: u32 = cmp::min(x_lo + 1, src_w - 1);
                let tx: f64 = src_fx - f64::from(x_lo);
                let weights: [f64; 4] = [
                    (1.0 - tx) * (1.0 - ty),
                    tx * (1.0 - ty),
                    (1.0 - tx) * ty,
                    tx * ty,
                ];
                let coords: [(u32, u32); 4] =
                    [(x_lo, y_lo), (x_hi, y_lo), (x_lo, y_hi), (x_hi, y_hi)];
                let mut acc_r: f64 = 0.0;
                let mut acc_g: f64 = 0.0;
                let mut acc_b: f64 = 0.0;
                let mut acc_a: f64 = 0.0;
                let mut idx: usize = 0;
                while idx < 4 {
                    let (cx, cy): (u32, u32) = coords[idx];
                    let weight: f64 = weights[idx];
                    let offset: usize = ((cy * src_w + cx) as usize) * 4;
                    let alpha: f64 = f64::from(src_pixels[offset + 3]) / 255.0;
                    acc_r += f64::from(src_pixels[offset]) * alpha * weight;
                    acc_g += f64::from(src_pixels[offset + 1]) * alpha * weight;
                    acc_b += f64::from(src_pixels[offset + 2]) * alpha * weight;
                    acc_a += alpha * weight;
                    idx += 1;
                }
                let dst_offset: usize = ((dst_y * dst_w + dst_x) as usize) * 4;
                if acc_a > 1e-6 {
                    dst_pixels[dst_offset] = (acc_r / acc_a).round().clamp(0.0, 255.0) as u8;
                    dst_pixels[dst_offset + 1] = (acc_g / acc_a).round().clamp(0.0, 255.0) as u8;
                    dst_pixels[dst_offset + 2] = (acc_b / acc_a).round().clamp(0.0, 255.0) as u8;
                    dst_pixels[dst_offset + 3] = (acc_a * 255.0).round().clamp(0.0, 255.0) as u8;
                }
                dst_x += 1;
            }
            dst_y += 1;
        }
    }
    RgbaImage::new(dst_w, dst_h, dst_pixels)
}

/// Encodes an `RgbaImage` as an 8-bit RGBA PNG byte vector using pure Rust zlib and CRC-32.
///
/// # Arguments
///
/// - `&RgbaImage` - Source RGBA8 pixel buffer.
///
/// # Returns
///
/// - `Vec<u8>` - Complete standards-compliant PNG file bytes.
#[must_use]
pub fn encode_png_rgba(image: &RgbaImage) -> Vec<u8> {
    let width: u32 = image.get_width();
    let height: u32 = image.get_height();
    let stride: usize = (width as usize) * 4;
    let pixels: &[u8] = image.get_pixels();
    let mut scanlines: Vec<u8> = Vec::with_capacity((stride + 1) * (height as usize));
    let mut row: usize = 0;
    while row < (height as usize) {
        scanlines.push(0u8);
        let start: usize = row * stride;
        let end: usize = start + stride;
        if end <= pixels.len() {
            scanlines.extend_from_slice(&pixels[start..end]);
        } else {
            scanlines.resize(scanlines.len() + stride, 0u8);
        }
        row += 1;
    }
    let compressed: Vec<u8> = zlib_compress(&scanlines);
    let mut ihdr: [u8; 13] = [0u8; 13];
    ihdr[0..4].copy_from_slice(&width.to_be_bytes());
    ihdr[4..8].copy_from_slice(&height.to_be_bytes());
    ihdr[8] = 8;
    ihdr[9] = 6;
    ihdr[10] = 0;
    ihdr[11] = 0;
    ihdr[12] = 0;
    let mut out: Vec<u8> = Vec::with_capacity(PNG_SIGNATURE.len() + compressed.len() + 64);
    out.extend_from_slice(&PNG_SIGNATURE);
    push_png_chunk(&mut out, PNG_CHUNK_IHDR, &ihdr);
    push_png_chunk(&mut out, PNG_CHUNK_IDAT, &compressed);
    push_png_chunk(&mut out, PNG_CHUNK_IEND, &[]);
    out
}

/// Encodes a multi-resolution Windows `.ico` container (`16, 32, 48, 64, 128, 256` PNG frames).
///
/// # Arguments
///
/// - `&RgbaImage` - Source RGBA8 icon raster.
///
/// # Returns
///
/// - `Vec<u8>` - Complete Windows `.ico` file bytes.
#[must_use]
pub fn encode_ico_from_rgba(source: &RgbaImage) -> Vec<u8> {
    let mut frames: Vec<(u32, Vec<u8>)> = Vec::with_capacity(ICO_ICON_SIZES.len());
    for &size in ICO_ICON_SIZES.iter() {
        let resized: RgbaImage = resize_rgba(source, size, size);
        frames.push((size, encode_png_rgba(&resized)));
    }
    let count: u16 = frames.len() as u16;
    let mut out: Vec<u8> = Vec::new();
    out.extend_from_slice(&0u16.to_le_bytes());
    out.extend_from_slice(&1u16.to_le_bytes());
    out.extend_from_slice(&count.to_le_bytes());
    let mut data_offset: u32 = 6 + u32::from(count) * 16;
    for (size, png_bytes) in frames.iter() {
        let dim_byte: u8 = if *size >= 256 { 0 } else { *size as u8 };
        out.push(dim_byte);
        out.push(dim_byte);
        out.push(0u8);
        out.push(0u8);
        out.extend_from_slice(&1u16.to_le_bytes());
        out.extend_from_slice(&32u16.to_le_bytes());
        out.extend_from_slice(&(png_bytes.len() as u32).to_le_bytes());
        out.extend_from_slice(&data_offset.to_le_bytes());
        data_offset += png_bytes.len() as u32;
    }
    for (_, png_bytes) in frames.into_iter() {
        out.extend_from_slice(&png_bytes);
    }
    out
}

/// Encodes a multi-resolution macOS `.icns` container (`icp4`..`ic10`, `16..1024` PNG chunks).
///
/// # Arguments
///
/// - `&RgbaImage` - Source RGBA8 icon raster.
///
/// # Returns
///
/// - `Vec<u8>` - Complete macOS `.icns` file bytes.
#[must_use]
pub fn encode_icns_from_rgba(source: &RgbaImage) -> Vec<u8> {
    let mut body: Vec<u8> = Vec::new();
    for &(tag, size) in ICNS_ICON_SPECS.iter() {
        let resized: RgbaImage = resize_rgba(source, size, size);
        let png_bytes: Vec<u8> = encode_png_rgba(&resized);
        let chunk_len: u32 = (8 + png_bytes.len()) as u32;
        body.extend_from_slice(&tag);
        body.extend_from_slice(&chunk_len.to_be_bytes());
        body.extend_from_slice(&png_bytes);
    }
    let total_len: u32 = (8 + body.len()) as u32;
    let mut out: Vec<u8> = Vec::with_capacity(8 + body.len());
    out.extend_from_slice(&ICNS_MAGIC);
    out.extend_from_slice(&total_len.to_be_bytes());
    out.extend_from_slice(&body);
    out
}

/// Writes a square resized PNG icon of `size x size` pixels to `output_path`.
///
/// # Arguments
///
/// - `&Path` - Destination PNG file path.
/// - `u32` - Target square icon dimension in pixels.
/// - `Option<&Path>` - Optional custom source PNG override.
///
/// # Returns
///
/// - `io::Result<()>` - Write completion result.
pub fn write_icon_png(output_path: &Path, size: u32, custom_icon: Option<&Path>) -> io::Result<()> {
    let source: RgbaImage = resolve_icon_rgba(custom_icon)?;
    let resized: RgbaImage = resize_rgba(&source, size, size);
    let encoded: Vec<u8> = encode_png_rgba(&resized);
    write_icon_file(output_path, &encoded)
}

/// Writes a multi-resolution Windows `.ico` icon file to `output_path`.
///
/// # Arguments
///
/// - `&Path` - Destination `.ico` file path.
/// - `Option<&Path>` - Optional custom source PNG override.
///
/// # Returns
///
/// - `io::Result<()>` - Write completion result.
pub fn write_icon_ico(output_path: &Path, custom_icon: Option<&Path>) -> io::Result<()> {
    let source: RgbaImage = resolve_icon_rgba(custom_icon)?;
    let encoded: Vec<u8> = encode_ico_from_rgba(&source);
    write_icon_file(output_path, &encoded)
}

/// Writes a multi-resolution macOS `.icns` icon bundle to `output_path`.
///
/// # Arguments
///
/// - `&Path` - Destination `.icns` file path.
/// - `Option<&Path>` - Optional custom source PNG override.
///
/// # Returns
///
/// - `io::Result<()>` - Write completion result.
pub fn write_icon_icns(output_path: &Path, custom_icon: Option<&Path>) -> io::Result<()> {
    let source: RgbaImage = resolve_icon_rgba(custom_icon)?;
    let encoded: Vec<u8> = encode_icns_from_rgba(&source);
    write_icon_file(output_path, &encoded)
}

/// Writes all five Android/Wear OS mipmap launcher icons (`48..192px`) under `res_dir`.
///
/// # Arguments
///
/// - `&Path` - Android `res/` directory root.
/// - `Option<&Path>` - Optional custom source PNG override.
///
/// # Returns
///
/// - `io::Result<Vec<PathBuf>>` - Written launcher icon file paths.
pub fn write_android_mipmap_icons(
    res_dir: &Path,
    custom_icon: Option<&Path>,
) -> io::Result<Vec<PathBuf>> {
    let source: RgbaImage = resolve_icon_rgba(custom_icon)?;
    let mut written: Vec<PathBuf> = Vec::with_capacity(ANDROID_MIPMAP_SPECS.len());
    for &(density_dir, size) in ANDROID_MIPMAP_SPECS.iter() {
        let dest: PathBuf = res_dir.join(density_dir).join(ANDROID_LAUNCHER_ICON_NAME);
        let resized: RgbaImage = resize_rgba(&source, size, size);
        write_icon_file(&dest, &encode_png_rgba(&resized))?;
        written.push(dest);
    }
    Ok(written)
}

/// Writes all three iOS/iPadOS `.app` bundle icon PNGs (`120`, `180`, `1024`) into `bundle_dir`.
///
/// # Arguments
///
/// - `&Path` - `.app` bundle root directory.
/// - `Option<&Path>` - Optional custom source PNG override.
///
/// # Returns
///
/// - `io::Result<Vec<PathBuf>>` - Written bundle icon file paths.
pub fn write_ios_bundle_icons(
    bundle_dir: &Path,
    custom_icon: Option<&Path>,
) -> io::Result<Vec<PathBuf>> {
    let source: RgbaImage = resolve_icon_rgba(custom_icon)?;
    let mut written: Vec<PathBuf> = Vec::with_capacity(IOS_BUNDLE_ICON_SPECS.len());
    for &(filename, size) in IOS_BUNDLE_ICON_SPECS.iter() {
        let dest: PathBuf = bundle_dir.join(filename);
        let resized: RgbaImage = resize_rgba(&source, size, size);
        write_icon_file(&dest, &encode_png_rgba(&resized))?;
        written.push(dest);
    }
    Ok(written)
}

/// Writes standard Web showcase icon PNGs (`favicon.png`, `apple-touch-icon.png`, `euv-studio-logo-64.png`, `icon-64.png`, `icon-180.png`).
///
/// # Arguments
///
/// - `&Path` - Web output directory.
/// - `Option<&Path>` - Optional custom source PNG override.
///
/// # Returns
///
/// - `io::Result<Vec<PathBuf>>` - Written icon file paths.
pub fn write_web_icons(out_dir: &Path, custom_icon: Option<&Path>) -> io::Result<Vec<PathBuf>> {
    write_named_png_specs(out_dir, &WEB_BUNDLE_ICON_SPECS, custom_icon)
}

/// Writes raw Web WASM artifact icons (`favicon.png`, `apple-touch-icon.png`, `icon-64.png`, `icon-180.png`).
///
/// # Arguments
///
/// - `&Path` - Web output directory.
/// - `Option<&Path>` - Optional custom source PNG override.
///
/// # Returns
///
/// - `io::Result<Vec<PathBuf>>` - Written icon file paths.
pub fn write_web_raw_icons(out_dir: &Path, custom_icon: Option<&Path>) -> io::Result<Vec<PathBuf>> {
    write_named_png_specs(out_dir, &WEB_RAW_ICON_SPECS, custom_icon)
}

/// Writes a batch of `(filename, size_px)` PNG icons decoding the source image only once.
///
/// # Arguments
///
/// - `&Path` - Destination directory.
/// - `&[(&str, u32)]` - Icon filename and dimension specifications.
/// - `Option<&Path>` - Optional custom source PNG override.
///
/// # Returns
///
/// - `io::Result<Vec<PathBuf>>` - Written icon paths.
fn write_named_png_specs(
    out_dir: &Path,
    specs: &[(&str, u32)],
    custom_icon: Option<&Path>,
) -> io::Result<Vec<PathBuf>> {
    let source: RgbaImage = resolve_icon_rgba(custom_icon)?;
    let mut cache: BTreeMap<u32, Vec<u8>> = BTreeMap::new();
    let mut written: Vec<PathBuf> = Vec::with_capacity(specs.len());
    for &(filename, size) in specs.iter() {
        let png_bytes: &Vec<u8> = cache.entry(size).or_insert_with(|| {
            let resized: RgbaImage = resize_rgba(&source, size, size);
            encode_png_rgba(&resized)
        });
        let dest: PathBuf = out_dir.join(filename);
        write_icon_file(&dest, png_bytes)?;
        written.push(dest);
    }
    Ok(written)
}

/// Creates parent directories and writes encoded icon bytes to `output_path`.
///
/// # Arguments
///
/// - `&Path` - Destination file path.
/// - `&[u8]` - Encoded icon bytes.
///
/// # Returns
///
/// - `io::Result<()>` - Filesystem write result.
fn write_icon_file(output_path: &Path, bytes: &[u8]) -> io::Result<()> {
    if let Some(parent) = output_path.parent()
        && !parent.as_os_str().is_empty()
    {
        fs::create_dir_all(parent)?;
    }
    fs::write(output_path, bytes)
}

/// Appends one PNG chunk `(length, type, data, crc32)` to `out`.
///
/// # Arguments
///
/// - `&mut Vec<u8>` - Destination PNG buffer.
/// - `[u8; 4]` - 4-byte ASCII chunk type tag.
/// - `&[u8]` - Chunk payload bytes.
fn push_png_chunk(out: &mut Vec<u8>, tag: [u8; 4], data: &[u8]) {
    let mut crc_buf: Vec<u8> = Vec::with_capacity(4 + data.len());
    crc_buf.extend_from_slice(&tag);
    crc_buf.extend_from_slice(data);
    let checksum: u32 = crc32_bytes(&crc_buf);
    out.extend_from_slice(&(data.len() as u32).to_be_bytes());
    out.extend_from_slice(&tag);
    out.extend_from_slice(data);
    out.extend_from_slice(&checksum.to_be_bytes());
}

/// Decodes a single Base64 ASCII character to its 6-bit value.
///
/// # Arguments
///
/// - `u8` - Input ASCII byte.
///
/// # Returns
///
/// - `Option<u8>` - 6-bit symbol value or `None` if invalid.
fn decode_base64_char(byte_val: u8) -> Option<u8> {
    match byte_val {
        b'A'..=b'Z' => Some(byte_val - b'A'),
        b'a'..=b'z' => Some(byte_val - b'a' + 26),
        b'0'..=b'9' => Some(byte_val - b'0' + 52),
        b'+' => Some(62),
        b'/' => Some(63),
        _ => None,
    }
}

/// Reads a big-endian `u32` at `offset` with bounds validation.
///
/// # Arguments
///
/// - `&[u8]` - Input byte slice.
/// - `usize` - Starting byte offset.
///
/// # Returns
///
/// - `io::Result<u32>` - Decoded 32-bit integer.
fn read_be_u32(bytes: &[u8], offset: usize) -> io::Result<u32> {
    let slice: &[u8] = bytes
        .get(offset..offset + 4)
        .ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_PNG_INVALID))?;
    Ok(u32::from_be_bytes([slice[0], slice[1], slice[2], slice[3]]))
}

/// Reverses PNG scanline filtering (None, Sub, Up, Average, Paeth) into `dst`.
///
/// # Arguments
///
/// - `u8` - PNG filter method byte (`0..=4`).
/// - `&[u8]` - Filtered scanline bytes.
/// - `&[u8]` - Previous unfiltered scanline bytes.
/// - `&mut [u8]` - Destination unfiltered scanline buffer.
/// - `usize` - Bytes-per-pixel filter stride (`>= 1`).
///
/// # Returns
///
/// - `io::Result<()>` - Error if `filter_type` is unrecognized.
fn unfilter_png_scanline(
    filter_type: u8,
    src: &[u8],
    prev: &[u8],
    dst: &mut [u8],
    bpp: usize,
) -> io::Result<()> {
    match filter_type {
        0 => dst.copy_from_slice(src),
        1 => {
            let mut idx: usize = 0;
            while idx < src.len() {
                let left: u8 = if idx >= bpp { dst[idx - bpp] } else { 0 };
                dst[idx] = src[idx].wrapping_add(left);
                idx += 1;
            }
        }
        2 => {
            let mut idx: usize = 0;
            while idx < src.len() {
                dst[idx] = src[idx].wrapping_add(prev[idx]);
                idx += 1;
            }
        }
        3 => {
            let mut idx: usize = 0;
            while idx < src.len() {
                let left: u16 = if idx >= bpp {
                    u16::from(dst[idx - bpp])
                } else {
                    0
                };
                let up: u16 = u16::from(prev[idx]);
                let avg: u8 = ((left + up) / 2) as u8;
                dst[idx] = src[idx].wrapping_add(avg);
                idx += 1;
            }
        }
        4 => {
            let mut idx: usize = 0;
            while idx < src.len() {
                let left: u8 = if idx >= bpp { dst[idx - bpp] } else { 0 };
                let up: u8 = prev[idx];
                let up_left: u8 = if idx >= bpp { prev[idx - bpp] } else { 0 };
                dst[idx] = src[idx].wrapping_add(paeth_predictor(left, up, up_left));
                idx += 1;
            }
        }
        _ => return Err(Error::new(ErrorKind::InvalidData, ERR_PNG_FILTER)),
    }
    Ok(())
}

/// Computes the standard PNG Paeth predictor byte from left, above, and upper-left neighbors.
///
/// # Arguments
///
/// - `u8` - Left neighbor byte.
/// - `u8` - Above neighbor byte.
/// - `u8` - Upper-left neighbor byte.
///
/// # Returns
///
/// - `u8` - Selected predictor byte.
fn paeth_predictor(left: u8, up: u8, up_left: u8) -> u8 {
    let left_i: i32 = i32::from(left);
    let up_i: i32 = i32::from(up);
    let up_left_i: i32 = i32::from(up_left);
    let pred: i32 = left_i + up_i - up_left_i;
    let dist_left: i32 = (pred - left_i).abs();
    let dist_up: i32 = (pred - up_i).abs();
    let dist_up_left: i32 = (pred - up_left_i).abs();
    if dist_left <= dist_up && dist_left <= dist_up_left {
        left
    } else if dist_up <= dist_up_left {
        up
    } else {
        up_left
    }
}

/// Expands one unfiltered PNG scanline of any supported color type and bit depth into RGBA8 bytes.
///
/// # Arguments
///
/// - `&[u8]` - Unfiltered scanline bytes.
/// - `usize` - Row width in pixels.
/// - `u8` - Sample bit depth (`1`, `2`, `4`, or `8`).
/// - `u8` - PNG color type (`0`, `2`, `3`, `4`, or `6`).
/// - `&[[u8; 3]]` - Decoded `PLTE` RGB entries.
/// - `&[u8]` - Optional raw `tRNS` chunk bytes.
/// - `&mut Vec<u8>` - Destination RGBA8 accumulator.
///
/// # Returns
///
/// - `io::Result<()>` - Error if palette indices or row layout are invalid.
fn expand_png_row_to_rgba(
    row: &[u8],
    width: usize,
    bit_depth: u8,
    color_type: u8,
    palette: &[[u8; 3]],
    trns: &[u8],
    out: &mut Vec<u8>,
) -> io::Result<()> {
    match color_type {
        6 => {
            if bit_depth != 8 || row.len() < width * 4 {
                return Err(Error::new(ErrorKind::InvalidData, ERR_PNG_UNSUPPORTED));
            }
            out.extend_from_slice(&row[..width * 4]);
        }
        2 => {
            if bit_depth != 8 || row.len() < width * 3 {
                return Err(Error::new(ErrorKind::InvalidData, ERR_PNG_UNSUPPORTED));
            }
            let has_key: bool = trns.len() >= 6;
            let key_r: u8 = if has_key { trns[1] } else { 0 };
            let key_g: u8 = if has_key { trns[3] } else { 0 };
            let key_b: u8 = if has_key { trns[5] } else { 0 };
            let mut col: usize = 0;
            while col < width {
                let offset: usize = col * 3;
                let red: u8 = row[offset];
                let green: u8 = row[offset + 1];
                let blue: u8 = row[offset + 2];
                let alpha: u8 = if has_key && red == key_r && green == key_g && blue == key_b {
                    0
                } else {
                    255
                };
                out.extend_from_slice(&[red, green, blue, alpha]);
                col += 1;
            }
        }
        4 => {
            if bit_depth != 8 || row.len() < width * 2 {
                return Err(Error::new(ErrorKind::InvalidData, ERR_PNG_UNSUPPORTED));
            }
            let mut col: usize = 0;
            while col < width {
                let gray: u8 = row[col * 2];
                let alpha: u8 = row[col * 2 + 1];
                out.extend_from_slice(&[gray, gray, gray, alpha]);
                col += 1;
            }
        }
        3 => {
            let mut col: usize = 0;
            while col < width {
                let pal_idx: usize = usize::from(extract_packed_sample(row, col, bit_depth)?);
                let rgb: [u8; 3] = *palette
                    .get(pal_idx)
                    .ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_PNG_INVALID))?;
                let alpha: u8 = trns.get(pal_idx).copied().unwrap_or(255);
                out.extend_from_slice(&[rgb[0], rgb[1], rgb[2], alpha]);
                col += 1;
            }
        }
        0 => {
            let max_sample: u16 = (1u16 << bit_depth) - 1;
            let has_key: bool = trns.len() >= 2;
            let key_gray: u8 = if has_key { trns[1] } else { 0 };
            let mut col: usize = 0;
            while col < width {
                let raw_val: u8 = extract_packed_sample(row, col, bit_depth)?;
                let gray: u8 = if bit_depth == 8 {
                    raw_val
                } else {
                    ((u16::from(raw_val) * 255) / max_sample) as u8
                };
                let alpha: u8 = if has_key && raw_val == key_gray {
                    0
                } else {
                    255
                };
                out.extend_from_slice(&[gray, gray, gray, alpha]);
                col += 1;
            }
        }
        _ => return Err(Error::new(ErrorKind::InvalidData, ERR_PNG_UNSUPPORTED)),
    }
    Ok(())
}

/// Extracts a 1, 2, 4, or 8-bit sample at `col` from a packed PNG scanline.
///
/// # Arguments
///
/// - `&[u8]` - Unfiltered scanline bytes.
/// - `usize` - Pixel column index.
/// - `u8` - Sample bit depth (`1`, `2`, `4`, or `8`).
///
/// # Returns
///
/// - `io::Result<u8>` - Extracted unsigned sample value.
fn extract_packed_sample(row: &[u8], col: usize, bit_depth: u8) -> io::Result<u8> {
    if bit_depth == 8 {
        return row
            .get(col)
            .copied()
            .ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_PNG_INVALID));
    }
    let samples_per_byte: usize = usize::from(8 / bit_depth);
    let byte_idx: usize = col / samples_per_byte;
    let sub_idx: usize = col % samples_per_byte;
    let byte_val: u8 = *row
        .get(byte_idx)
        .ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_PNG_INVALID))?;
    let shift: u8 = 8 - bit_depth * ((sub_idx as u8) + 1);
    let mask: u8 = (1u8 << bit_depth) - 1;
    Ok((byte_val >> shift) & mask)
}