Skip to main content

euv_cli/builder/icon/
fn.rs

1use super::*;
2
3/// Decodes a standard RFC 4648 Base64 string into raw bytes.
4///
5/// # Arguments
6///
7/// - `&str` - Base64-encoded ASCII text (whitespace ignored).
8///
9/// # Returns
10///
11/// - `io::Result<Vec<u8>>` - Decoded byte vector or format error.
12pub fn decode_base64(input: &str) -> io::Result<Vec<u8>> {
13    let mut out: Vec<u8> = Vec::with_capacity((input.len() * 3) / 4);
14    let mut quartet: [u8; 4] = [0u8; 4];
15    let mut q_len: usize = 0;
16    let mut pad_count: usize = 0;
17    for byte_val in input.bytes() {
18        if byte_val.is_ascii_whitespace() {
19            continue;
20        }
21        if byte_val == b'=' {
22            pad_count += 1;
23            quartet[q_len] = 0;
24            q_len += 1;
25        } else {
26            if pad_count > 0 {
27                return Err(Error::new(ErrorKind::InvalidData, ERR_BASE64_INVALID));
28            }
29            let decoded: u8 = decode_base64_char(byte_val)
30                .ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_BASE64_INVALID))?;
31            quartet[q_len] = decoded;
32            q_len += 1;
33        }
34        if q_len == 4 {
35            let triple: u32 = (u32::from(quartet[0]) << 18)
36                | (u32::from(quartet[1]) << 12)
37                | (u32::from(quartet[2]) << 6)
38                | u32::from(quartet[3]);
39            out.push(((triple >> 16) & 0xFF) as u8);
40            if pad_count < 2 {
41                out.push(((triple >> 8) & 0xFF) as u8);
42            }
43            if pad_count < 1 {
44                out.push((triple & 0xFF) as u8);
45            }
46            q_len = 0;
47            pad_count = 0;
48        }
49    }
50    if q_len != 0 {
51        return Err(Error::new(ErrorKind::InvalidData, ERR_BASE64_INVALID));
52    }
53    Ok(out)
54}
55
56/// Encodes raw bytes as standard RFC 4648 Base64 ASCII text.
57///
58/// # Arguments
59///
60/// - `&[u8]` - Raw byte slice.
61///
62/// # Returns
63///
64/// - `String` - Base64-encoded ASCII string.
65#[must_use]
66pub fn encode_base64(bytes: &[u8]) -> String {
67    let mut out: String = String::with_capacity(bytes.len().div_ceil(3) * 4);
68    let mut idx: usize = 0;
69    while idx < bytes.len() {
70        let first: u32 = u32::from(bytes[idx]);
71        let has_second: bool = idx + 1 < bytes.len();
72        let has_third: bool = idx + 2 < bytes.len();
73        let second: u32 = if has_second {
74            u32::from(bytes[idx + 1])
75        } else {
76            0
77        };
78        let third: u32 = if has_third {
79            u32::from(bytes[idx + 2])
80        } else {
81            0
82        };
83        let triple: u32 = (first << 16) | (second << 8) | third;
84        out.push(BASE64_ALPHABET[((triple >> 18) & 0x3F) as usize] as char);
85        out.push(BASE64_ALPHABET[((triple >> 12) & 0x3F) as usize] as char);
86        if has_second {
87            out.push(BASE64_ALPHABET[((triple >> 6) & 0x3F) as usize] as char);
88        } else {
89            out.push('=');
90        }
91        if has_third {
92            out.push(BASE64_ALPHABET[(triple & 0x3F) as usize] as char);
93        } else {
94            out.push('=');
95        }
96        idx += 3;
97    }
98    out
99}
100
101/// Returns the embedded lossless 96x96 canonical Euv brand PNG bytes with zero network access.
102///
103/// # Returns
104///
105/// - `io::Result<Vec<u8>>` - Raw PNG bytes decoded from `DEFAULT_BRAND_LOGO_DATA_URI`.
106pub fn default_brand_logo_png_bytes() -> io::Result<Vec<u8>> {
107    let payload: &str = DEFAULT_BRAND_LOGO_DATA_URI
108        .strip_prefix(PNG_DATA_URI_PREFIX)
109        .ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_BASE64_INVALID))?;
110    decode_base64(payload)
111}
112
113/// Resolves source icon PNG bytes from explicit path, `EUV_APP_ICON`, or embedded default logo.
114///
115/// # Arguments
116///
117/// - `Option<&Path>` - Optional explicit PNG icon path override.
118///
119/// # Returns
120///
121/// - `io::Result<Vec<u8>>` - Validated PNG byte buffer.
122pub fn resolve_icon_png_bytes(custom_icon: Option<&Path>) -> io::Result<Vec<u8>> {
123    if let Some(path) = custom_icon {
124        let bytes: Vec<u8> = fs::read(path)?;
125        if bytes.starts_with(&PNG_SIGNATURE) {
126            return Ok(bytes);
127        }
128        return Err(Error::new(
129            ErrorKind::InvalidInput,
130            format!("{ERR_ICON_SOURCE_INVALID}: {}", path.display()),
131        ));
132    }
133    if let Ok(env_val) = env::var(ENV_APP_ICON) {
134        let trimmed: &str = env_val.trim();
135        if !trimmed.is_empty() {
136            let env_path: PathBuf = PathBuf::from(trimmed);
137            if env_path.is_file() {
138                let bytes: Vec<u8> = fs::read(&env_path)?;
139                if bytes.starts_with(&PNG_SIGNATURE) {
140                    return Ok(bytes);
141                }
142            }
143        }
144    }
145    default_brand_logo_png_bytes()
146}
147
148/// Resolves and decodes the source icon into an RGBA8 raster image.
149///
150/// # Arguments
151///
152/// - `Option<&Path>` - Optional explicit PNG icon path override.
153///
154/// # Returns
155///
156/// - `io::Result<RgbaImage>` - Decoded RGBA8 image.
157pub fn resolve_icon_rgba(custom_icon: Option<&Path>) -> io::Result<RgbaImage> {
158    let png_bytes: Vec<u8> = resolve_icon_png_bytes(custom_icon)?;
159    decode_png_rgba(&png_bytes)
160}
161
162/// Resolves an inline `data:image/png;base64,...` URI for HTML favicons and splash screens.
163///
164/// # Arguments
165///
166/// - `Option<&Path>` - Optional custom PNG icon path override.
167///
168/// # Returns
169///
170/// - `io::Result<String>` - Self-contained PNG data URI.
171pub fn resolve_icon_data_uri(custom_icon: Option<&Path>) -> io::Result<String> {
172    let env_icon: Option<PathBuf> = env::var(ENV_APP_ICON)
173        .ok()
174        .map(|val: String| val.trim().to_string())
175        .filter(|val: &String| !val.is_empty())
176        .map(PathBuf::from)
177        .filter(|path: &PathBuf| path.is_file());
178    if custom_icon.is_none() && env_icon.is_none() {
179        return Ok(DEFAULT_BRAND_LOGO_DATA_URI.to_string());
180    }
181    let rgba: RgbaImage = resolve_icon_rgba(custom_icon)?;
182    let resized: RgbaImage = resize_rgba(&rgba, ICON_DATA_URI_SIZE, ICON_DATA_URI_SIZE);
183    let png_bytes: Vec<u8> = encode_png_rgba(&resized);
184    let encoded: String = encode_base64(&png_bytes);
185    Ok(format!("{PNG_DATA_URI_PREFIX}{encoded}"))
186}
187
188/// Decodes a non-interlaced PNG image (grayscale, RGB, palette+tRNS, gray+alpha, RGBA) to `RgbaImage`.
189///
190/// # Arguments
191///
192/// - `&[u8]` - Raw PNG file bytes.
193///
194/// # Returns
195///
196/// - `io::Result<RgbaImage>` - Decoded RGBA8 pixel buffer.
197pub fn decode_png_rgba(png_bytes: &[u8]) -> io::Result<RgbaImage> {
198    if png_bytes.len() < 33 || !png_bytes.starts_with(&PNG_SIGNATURE) {
199        return Err(Error::new(ErrorKind::InvalidData, ERR_PNG_INVALID));
200    }
201    let mut pos: usize = PNG_SIGNATURE.len();
202    let mut width: u32 = 0;
203    let mut height: u32 = 0;
204    let mut bit_depth: u8 = 0;
205    let mut color_type: u8 = 0;
206    let mut seen_ihdr: bool = false;
207    let mut palette: Vec<[u8; 3]> = Vec::new();
208    let mut trns: Vec<u8> = Vec::new();
209    let mut idat_all: Vec<u8> = Vec::new();
210    while pos + 12 <= png_bytes.len() {
211        let chunk_len: usize = read_be_u32(png_bytes, pos)? as usize;
212        let tag: [u8; 4] = [
213            png_bytes[pos + 4],
214            png_bytes[pos + 5],
215            png_bytes[pos + 6],
216            png_bytes[pos + 7],
217        ];
218        let data_start: usize = pos + 8;
219        let data_end: usize = data_start
220            .checked_add(chunk_len)
221            .ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_PNG_INVALID))?;
222        let crc_end: usize = data_end
223            .checked_add(4)
224            .ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_PNG_INVALID))?;
225        let chunk_data: &[u8] = png_bytes
226            .get(data_start..data_end)
227            .ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_PNG_INVALID))?;
228        if crc_end > png_bytes.len() {
229            return Err(Error::new(ErrorKind::InvalidData, ERR_PNG_INVALID));
230        }
231        if tag == PNG_CHUNK_IHDR {
232            if chunk_data.len() != 13 {
233                return Err(Error::new(ErrorKind::InvalidData, ERR_PNG_INVALID));
234            }
235            width = read_be_u32(chunk_data, 0)?;
236            height = read_be_u32(chunk_data, 4)?;
237            bit_depth = chunk_data[8];
238            color_type = chunk_data[9];
239            let comp_method: u8 = chunk_data[10];
240            let filter_method: u8 = chunk_data[11];
241            let interlace_method: u8 = chunk_data[12];
242            let supported_depth: bool = [1u8, 2, 4, 8].contains(&bit_depth);
243            if width == 0
244                || height == 0
245                || comp_method != 0
246                || filter_method != 0
247                || interlace_method != 0
248                || !supported_depth
249            {
250                return Err(Error::new(ErrorKind::InvalidData, ERR_PNG_UNSUPPORTED));
251            }
252            seen_ihdr = true;
253        } else if tag == PNG_CHUNK_PLTE {
254            if !chunk_data.len().is_multiple_of(3) {
255                return Err(Error::new(ErrorKind::InvalidData, ERR_PNG_INVALID));
256            }
257            palette.clear();
258            let mut idx: usize = 0;
259            while idx < chunk_data.len() {
260                palette.push([chunk_data[idx], chunk_data[idx + 1], chunk_data[idx + 2]]);
261                idx += 3;
262            }
263        } else if tag == PNG_CHUNK_TRNS {
264            trns = chunk_data.to_vec();
265        } else if tag == PNG_CHUNK_IDAT {
266            idat_all.extend_from_slice(chunk_data);
267        } else if tag == PNG_CHUNK_IEND {
268            break;
269        }
270        pos = crc_end;
271    }
272    if !seen_ihdr || idat_all.is_empty() {
273        return Err(Error::new(ErrorKind::InvalidData, ERR_PNG_INVALID));
274    }
275    let samples_per_pixel: usize = match color_type {
276        0 | 3 => 1,
277        2 => 3,
278        4 => 2,
279        6 => 4,
280        _ => return Err(Error::new(ErrorKind::InvalidData, ERR_PNG_UNSUPPORTED)),
281    };
282    let bits_per_pixel: usize = samples_per_pixel * usize::from(bit_depth);
283    let stride: usize = (usize::try_from(width).unwrap_or(0) * bits_per_pixel).div_ceil(8);
284    let filter_bpp: usize = cmp::max(1, bits_per_pixel.div_ceil(8));
285    let expected_raw_len: usize = (stride + 1)
286        .checked_mul(usize::try_from(height).unwrap_or(0))
287        .ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_PNG_INVALID))?;
288    let raw_scanlines: Vec<u8> = zlib_decompress(&idat_all)?;
289    if raw_scanlines.len() < expected_raw_len {
290        return Err(Error::new(ErrorKind::InvalidData, ERR_PNG_INVALID));
291    }
292    let mut prev_row: Vec<u8> = vec![0u8; stride];
293    let mut curr_row: Vec<u8> = vec![0u8; stride];
294    let mut rgba: Vec<u8> = Vec::with_capacity(
295        usize::try_from(width).unwrap_or(0) * usize::try_from(height).unwrap_or(0) * 4,
296    );
297    let height_usize: usize = usize::try_from(height).unwrap_or(0);
298    let width_usize: usize = usize::try_from(width).unwrap_or(0);
299    let mut row_idx: usize = 0;
300    while row_idx < height_usize {
301        let row_start: usize = row_idx * (stride + 1);
302        let filter_type: u8 = raw_scanlines[row_start];
303        let src_row: &[u8] = &raw_scanlines[row_start + 1..row_start + 1 + stride];
304        unfilter_png_scanline(filter_type, src_row, &prev_row, &mut curr_row, filter_bpp)?;
305        expand_png_row_to_rgba(
306            &curr_row,
307            width_usize,
308            bit_depth,
309            color_type,
310            &palette,
311            &trns,
312            &mut rgba,
313        )?;
314        prev_row.copy_from_slice(&curr_row);
315        row_idx += 1;
316    }
317    Ok(RgbaImage::new(width, height, rgba))
318}
319
320/// Resizes an `RgbaImage` cleanly using premultiplied-alpha box averaging (downscale) or bilinear interpolation (upscale).
321///
322/// # Arguments
323///
324/// - `&RgbaImage` - Source RGBA8 image.
325/// - `u32` - Target width in pixels (`>= 1`).
326/// - `u32` - Target height in pixels (`>= 1`).
327///
328/// # Returns
329///
330/// - `RgbaImage` - Resized RGBA8 image.
331#[must_use]
332pub fn resize_rgba(image: &RgbaImage, target_width: u32, target_height: u32) -> RgbaImage {
333    let dst_w: u32 = cmp::max(1, target_width);
334    let dst_h: u32 = cmp::max(1, target_height);
335    let src_w: u32 = image.get_width();
336    let src_h: u32 = image.get_height();
337    if src_w == dst_w && src_h == dst_h {
338        return image.clone();
339    }
340    let src_pixels: &[u8] = image.get_pixels();
341    let mut dst_pixels: Vec<u8> = vec![0u8; (dst_w as usize) * (dst_h as usize) * 4];
342    let scale_x: f64 = f64::from(src_w) / f64::from(dst_w);
343    let scale_y: f64 = f64::from(src_h) / f64::from(dst_h);
344    if dst_w < src_w && dst_h < src_h {
345        let mut dst_y: u32 = 0;
346        while dst_y < dst_h {
347            let y0: f64 = f64::from(dst_y) * scale_y;
348            let y1: f64 = (f64::from(dst_y) + 1.0) * scale_y;
349            let row_start: u32 = (y0.floor() as u32).min(src_h - 1);
350            let row_end: u32 = (y1.ceil() as u32).min(src_h);
351            let mut dst_x: u32 = 0;
352            while dst_x < dst_w {
353                let x0: f64 = f64::from(dst_x) * scale_x;
354                let x1: f64 = (f64::from(dst_x) + 1.0) * scale_x;
355                let col_start: u32 = (x0.floor() as u32).min(src_w - 1);
356                let col_end: u32 = (x1.ceil() as u32).min(src_w);
357                let mut acc_r: f64 = 0.0;
358                let mut acc_g: f64 = 0.0;
359                let mut acc_b: f64 = 0.0;
360                let mut acc_a: f64 = 0.0;
361                let mut weight_sum: f64 = 0.0;
362                let mut sy: u32 = row_start;
363                while sy < row_end {
364                    let wy: f64 = (f64::from(sy + 1).min(y1) - f64::from(sy).max(y0)).max(0.0);
365                    let mut sx: u32 = col_start;
366                    while sx < col_end {
367                        let wx: f64 = (f64::from(sx + 1).min(x1) - f64::from(sx).max(x0)).max(0.0);
368                        let weight: f64 = wx * wy;
369                        let offset: usize = ((sy * src_w + sx) as usize) * 4;
370                        let alpha: f64 = f64::from(src_pixels[offset + 3]) / 255.0;
371                        acc_r += f64::from(src_pixels[offset]) * alpha * weight;
372                        acc_g += f64::from(src_pixels[offset + 1]) * alpha * weight;
373                        acc_b += f64::from(src_pixels[offset + 2]) * alpha * weight;
374                        acc_a += alpha * weight;
375                        weight_sum += weight;
376                        sx += 1;
377                    }
378                    sy += 1;
379                }
380                let dst_offset: usize = ((dst_y * dst_w + dst_x) as usize) * 4;
381                if weight_sum > 0.0 && acc_a > 1e-6 {
382                    let out_a: f64 = (acc_a / weight_sum).clamp(0.0, 1.0);
383                    dst_pixels[dst_offset] = (acc_r / acc_a).round().clamp(0.0, 255.0) as u8;
384                    dst_pixels[dst_offset + 1] = (acc_g / acc_a).round().clamp(0.0, 255.0) as u8;
385                    dst_pixels[dst_offset + 2] = (acc_b / acc_a).round().clamp(0.0, 255.0) as u8;
386                    dst_pixels[dst_offset + 3] = (out_a * 255.0).round().clamp(0.0, 255.0) as u8;
387                }
388                dst_x += 1;
389            }
390            dst_y += 1;
391        }
392    } else {
393        let mut dst_y: u32 = 0;
394        while dst_y < dst_h {
395            let src_fy: f64 =
396                ((f64::from(dst_y) + 0.5) * scale_y - 0.5).clamp(0.0, f64::from(src_h - 1));
397            let y_lo: u32 = src_fy.floor() as u32;
398            let y_hi: u32 = cmp::min(y_lo + 1, src_h - 1);
399            let ty: f64 = src_fy - f64::from(y_lo);
400            let mut dst_x: u32 = 0;
401            while dst_x < dst_w {
402                let src_fx: f64 =
403                    ((f64::from(dst_x) + 0.5) * scale_x - 0.5).clamp(0.0, f64::from(src_w - 1));
404                let x_lo: u32 = src_fx.floor() as u32;
405                let x_hi: u32 = cmp::min(x_lo + 1, src_w - 1);
406                let tx: f64 = src_fx - f64::from(x_lo);
407                let weights: [f64; 4] = [
408                    (1.0 - tx) * (1.0 - ty),
409                    tx * (1.0 - ty),
410                    (1.0 - tx) * ty,
411                    tx * ty,
412                ];
413                let coords: [(u32, u32); 4] =
414                    [(x_lo, y_lo), (x_hi, y_lo), (x_lo, y_hi), (x_hi, y_hi)];
415                let mut acc_r: f64 = 0.0;
416                let mut acc_g: f64 = 0.0;
417                let mut acc_b: f64 = 0.0;
418                let mut acc_a: f64 = 0.0;
419                let mut idx: usize = 0;
420                while idx < 4 {
421                    let (cx, cy): (u32, u32) = coords[idx];
422                    let weight: f64 = weights[idx];
423                    let offset: usize = ((cy * src_w + cx) as usize) * 4;
424                    let alpha: f64 = f64::from(src_pixels[offset + 3]) / 255.0;
425                    acc_r += f64::from(src_pixels[offset]) * alpha * weight;
426                    acc_g += f64::from(src_pixels[offset + 1]) * alpha * weight;
427                    acc_b += f64::from(src_pixels[offset + 2]) * alpha * weight;
428                    acc_a += alpha * weight;
429                    idx += 1;
430                }
431                let dst_offset: usize = ((dst_y * dst_w + dst_x) as usize) * 4;
432                if acc_a > 1e-6 {
433                    dst_pixels[dst_offset] = (acc_r / acc_a).round().clamp(0.0, 255.0) as u8;
434                    dst_pixels[dst_offset + 1] = (acc_g / acc_a).round().clamp(0.0, 255.0) as u8;
435                    dst_pixels[dst_offset + 2] = (acc_b / acc_a).round().clamp(0.0, 255.0) as u8;
436                    dst_pixels[dst_offset + 3] = (acc_a * 255.0).round().clamp(0.0, 255.0) as u8;
437                }
438                dst_x += 1;
439            }
440            dst_y += 1;
441        }
442    }
443    RgbaImage::new(dst_w, dst_h, dst_pixels)
444}
445
446/// Encodes an `RgbaImage` as an 8-bit RGBA PNG byte vector using pure Rust zlib and CRC-32.
447///
448/// # Arguments
449///
450/// - `&RgbaImage` - Source RGBA8 pixel buffer.
451///
452/// # Returns
453///
454/// - `Vec<u8>` - Complete standards-compliant PNG file bytes.
455#[must_use]
456pub fn encode_png_rgba(image: &RgbaImage) -> Vec<u8> {
457    let width: u32 = image.get_width();
458    let height: u32 = image.get_height();
459    let stride: usize = (width as usize) * 4;
460    let pixels: &[u8] = image.get_pixels();
461    let mut scanlines: Vec<u8> = Vec::with_capacity((stride + 1) * (height as usize));
462    let mut row: usize = 0;
463    while row < (height as usize) {
464        scanlines.push(0u8);
465        let start: usize = row * stride;
466        let end: usize = start + stride;
467        if end <= pixels.len() {
468            scanlines.extend_from_slice(&pixels[start..end]);
469        } else {
470            scanlines.resize(scanlines.len() + stride, 0u8);
471        }
472        row += 1;
473    }
474    let compressed: Vec<u8> = zlib_compress(&scanlines);
475    let mut ihdr: [u8; 13] = [0u8; 13];
476    ihdr[0..4].copy_from_slice(&width.to_be_bytes());
477    ihdr[4..8].copy_from_slice(&height.to_be_bytes());
478    ihdr[8] = 8;
479    ihdr[9] = 6;
480    ihdr[10] = 0;
481    ihdr[11] = 0;
482    ihdr[12] = 0;
483    let mut out: Vec<u8> = Vec::with_capacity(PNG_SIGNATURE.len() + compressed.len() + 64);
484    out.extend_from_slice(&PNG_SIGNATURE);
485    push_png_chunk(&mut out, PNG_CHUNK_IHDR, &ihdr);
486    push_png_chunk(&mut out, PNG_CHUNK_IDAT, &compressed);
487    push_png_chunk(&mut out, PNG_CHUNK_IEND, &[]);
488    out
489}
490
491/// Encodes a multi-resolution Windows `.ico` container (`16, 32, 48, 64, 128, 256` PNG frames).
492///
493/// # Arguments
494///
495/// - `&RgbaImage` - Source RGBA8 icon raster.
496///
497/// # Returns
498///
499/// - `Vec<u8>` - Complete Windows `.ico` file bytes.
500#[must_use]
501pub fn encode_ico_from_rgba(source: &RgbaImage) -> Vec<u8> {
502    let mut frames: Vec<(u32, Vec<u8>)> = Vec::with_capacity(ICO_ICON_SIZES.len());
503    for &size in ICO_ICON_SIZES.iter() {
504        let resized: RgbaImage = resize_rgba(source, size, size);
505        frames.push((size, encode_png_rgba(&resized)));
506    }
507    let count: u16 = frames.len() as u16;
508    let mut out: Vec<u8> = Vec::new();
509    out.extend_from_slice(&0u16.to_le_bytes());
510    out.extend_from_slice(&1u16.to_le_bytes());
511    out.extend_from_slice(&count.to_le_bytes());
512    let mut data_offset: u32 = 6 + u32::from(count) * 16;
513    for (size, png_bytes) in frames.iter() {
514        let dim_byte: u8 = if *size >= 256 { 0 } else { *size as u8 };
515        out.push(dim_byte);
516        out.push(dim_byte);
517        out.push(0u8);
518        out.push(0u8);
519        out.extend_from_slice(&1u16.to_le_bytes());
520        out.extend_from_slice(&32u16.to_le_bytes());
521        out.extend_from_slice(&(png_bytes.len() as u32).to_le_bytes());
522        out.extend_from_slice(&data_offset.to_le_bytes());
523        data_offset += png_bytes.len() as u32;
524    }
525    for (_, png_bytes) in frames.into_iter() {
526        out.extend_from_slice(&png_bytes);
527    }
528    out
529}
530
531/// Encodes a multi-resolution macOS `.icns` container (`icp4`..`ic10`, `16..1024` PNG chunks).
532///
533/// # Arguments
534///
535/// - `&RgbaImage` - Source RGBA8 icon raster.
536///
537/// # Returns
538///
539/// - `Vec<u8>` - Complete macOS `.icns` file bytes.
540#[must_use]
541pub fn encode_icns_from_rgba(source: &RgbaImage) -> Vec<u8> {
542    let mut body: Vec<u8> = Vec::new();
543    for &(tag, size) in ICNS_ICON_SPECS.iter() {
544        let resized: RgbaImage = resize_rgba(source, size, size);
545        let png_bytes: Vec<u8> = encode_png_rgba(&resized);
546        let chunk_len: u32 = (8 + png_bytes.len()) as u32;
547        body.extend_from_slice(&tag);
548        body.extend_from_slice(&chunk_len.to_be_bytes());
549        body.extend_from_slice(&png_bytes);
550    }
551    let total_len: u32 = (8 + body.len()) as u32;
552    let mut out: Vec<u8> = Vec::with_capacity(8 + body.len());
553    out.extend_from_slice(&ICNS_MAGIC);
554    out.extend_from_slice(&total_len.to_be_bytes());
555    out.extend_from_slice(&body);
556    out
557}
558
559/// Writes a square resized PNG icon of `size x size` pixels to `output_path`.
560///
561/// # Arguments
562///
563/// - `&Path` - Destination PNG file path.
564/// - `u32` - Target square icon dimension in pixels.
565/// - `Option<&Path>` - Optional custom source PNG override.
566///
567/// # Returns
568///
569/// - `io::Result<()>` - Write completion result.
570pub fn write_icon_png(output_path: &Path, size: u32, custom_icon: Option<&Path>) -> io::Result<()> {
571    let source: RgbaImage = resolve_icon_rgba(custom_icon)?;
572    let resized: RgbaImage = resize_rgba(&source, size, size);
573    let encoded: Vec<u8> = encode_png_rgba(&resized);
574    write_icon_file(output_path, &encoded)
575}
576
577/// Writes a multi-resolution Windows `.ico` icon file to `output_path`.
578///
579/// # Arguments
580///
581/// - `&Path` - Destination `.ico` file path.
582/// - `Option<&Path>` - Optional custom source PNG override.
583///
584/// # Returns
585///
586/// - `io::Result<()>` - Write completion result.
587pub fn write_icon_ico(output_path: &Path, custom_icon: Option<&Path>) -> io::Result<()> {
588    let source: RgbaImage = resolve_icon_rgba(custom_icon)?;
589    let encoded: Vec<u8> = encode_ico_from_rgba(&source);
590    write_icon_file(output_path, &encoded)
591}
592
593/// Writes a multi-resolution macOS `.icns` icon bundle to `output_path`.
594///
595/// # Arguments
596///
597/// - `&Path` - Destination `.icns` file path.
598/// - `Option<&Path>` - Optional custom source PNG override.
599///
600/// # Returns
601///
602/// - `io::Result<()>` - Write completion result.
603pub fn write_icon_icns(output_path: &Path, custom_icon: Option<&Path>) -> io::Result<()> {
604    let source: RgbaImage = resolve_icon_rgba(custom_icon)?;
605    let encoded: Vec<u8> = encode_icns_from_rgba(&source);
606    write_icon_file(output_path, &encoded)
607}
608
609/// Writes all five Android/Wear OS mipmap launcher icons (`48..192px`) under `res_dir`.
610///
611/// # Arguments
612///
613/// - `&Path` - Android `res/` directory root.
614/// - `Option<&Path>` - Optional custom source PNG override.
615///
616/// # Returns
617///
618/// - `io::Result<Vec<PathBuf>>` - Written launcher icon file paths.
619pub fn write_android_mipmap_icons(
620    res_dir: &Path,
621    custom_icon: Option<&Path>,
622) -> io::Result<Vec<PathBuf>> {
623    let source: RgbaImage = resolve_icon_rgba(custom_icon)?;
624    let mut written: Vec<PathBuf> = Vec::with_capacity(ANDROID_MIPMAP_SPECS.len());
625    for &(density_dir, size) in ANDROID_MIPMAP_SPECS.iter() {
626        let dest: PathBuf = res_dir.join(density_dir).join(ANDROID_LAUNCHER_ICON_NAME);
627        let resized: RgbaImage = resize_rgba(&source, size, size);
628        write_icon_file(&dest, &encode_png_rgba(&resized))?;
629        written.push(dest);
630    }
631    Ok(written)
632}
633
634/// Writes all three iOS/iPadOS `.app` bundle icon PNGs (`120`, `180`, `1024`) into `bundle_dir`.
635///
636/// # Arguments
637///
638/// - `&Path` - `.app` bundle root directory.
639/// - `Option<&Path>` - Optional custom source PNG override.
640///
641/// # Returns
642///
643/// - `io::Result<Vec<PathBuf>>` - Written bundle icon file paths.
644pub fn write_ios_bundle_icons(
645    bundle_dir: &Path,
646    custom_icon: Option<&Path>,
647) -> io::Result<Vec<PathBuf>> {
648    let source: RgbaImage = resolve_icon_rgba(custom_icon)?;
649    let mut written: Vec<PathBuf> = Vec::with_capacity(IOS_BUNDLE_ICON_SPECS.len());
650    for &(filename, size) in IOS_BUNDLE_ICON_SPECS.iter() {
651        let dest: PathBuf = bundle_dir.join(filename);
652        let resized: RgbaImage = resize_rgba(&source, size, size);
653        write_icon_file(&dest, &encode_png_rgba(&resized))?;
654        written.push(dest);
655    }
656    Ok(written)
657}
658
659/// Writes standard Web showcase icon PNGs (`favicon.png`, `apple-touch-icon.png`, `euv-studio-logo-64.png`, `icon-64.png`, `icon-180.png`).
660///
661/// # Arguments
662///
663/// - `&Path` - Web output directory.
664/// - `Option<&Path>` - Optional custom source PNG override.
665///
666/// # Returns
667///
668/// - `io::Result<Vec<PathBuf>>` - Written icon file paths.
669pub fn write_web_icons(out_dir: &Path, custom_icon: Option<&Path>) -> io::Result<Vec<PathBuf>> {
670    write_named_png_specs(out_dir, &WEB_BUNDLE_ICON_SPECS, custom_icon)
671}
672
673/// Writes raw Web WASM artifact icons (`favicon.png`, `apple-touch-icon.png`, `icon-64.png`, `icon-180.png`).
674///
675/// # Arguments
676///
677/// - `&Path` - Web output directory.
678/// - `Option<&Path>` - Optional custom source PNG override.
679///
680/// # Returns
681///
682/// - `io::Result<Vec<PathBuf>>` - Written icon file paths.
683pub fn write_web_raw_icons(out_dir: &Path, custom_icon: Option<&Path>) -> io::Result<Vec<PathBuf>> {
684    write_named_png_specs(out_dir, &WEB_RAW_ICON_SPECS, custom_icon)
685}
686
687/// Writes a batch of `(filename, size_px)` PNG icons decoding the source image only once.
688///
689/// # Arguments
690///
691/// - `&Path` - Destination directory.
692/// - `&[(&str, u32)]` - Icon filename and dimension specifications.
693/// - `Option<&Path>` - Optional custom source PNG override.
694///
695/// # Returns
696///
697/// - `io::Result<Vec<PathBuf>>` - Written icon paths.
698fn write_named_png_specs(
699    out_dir: &Path,
700    specs: &[(&str, u32)],
701    custom_icon: Option<&Path>,
702) -> io::Result<Vec<PathBuf>> {
703    let source: RgbaImage = resolve_icon_rgba(custom_icon)?;
704    let mut cache: BTreeMap<u32, Vec<u8>> = BTreeMap::new();
705    let mut written: Vec<PathBuf> = Vec::with_capacity(specs.len());
706    for &(filename, size) in specs.iter() {
707        let png_bytes: &Vec<u8> = cache.entry(size).or_insert_with(|| {
708            let resized: RgbaImage = resize_rgba(&source, size, size);
709            encode_png_rgba(&resized)
710        });
711        let dest: PathBuf = out_dir.join(filename);
712        write_icon_file(&dest, png_bytes)?;
713        written.push(dest);
714    }
715    Ok(written)
716}
717
718/// Creates parent directories and writes encoded icon bytes to `output_path`.
719///
720/// # Arguments
721///
722/// - `&Path` - Destination file path.
723/// - `&[u8]` - Encoded icon bytes.
724///
725/// # Returns
726///
727/// - `io::Result<()>` - Filesystem write result.
728fn write_icon_file(output_path: &Path, bytes: &[u8]) -> io::Result<()> {
729    if let Some(parent) = output_path.parent()
730        && !parent.as_os_str().is_empty()
731    {
732        fs::create_dir_all(parent)?;
733    }
734    fs::write(output_path, bytes)
735}
736
737/// Appends one PNG chunk `(length, type, data, crc32)` to `out`.
738///
739/// # Arguments
740///
741/// - `&mut Vec<u8>` - Destination PNG buffer.
742/// - `[u8; 4]` - 4-byte ASCII chunk type tag.
743/// - `&[u8]` - Chunk payload bytes.
744fn push_png_chunk(out: &mut Vec<u8>, tag: [u8; 4], data: &[u8]) {
745    let mut crc_buf: Vec<u8> = Vec::with_capacity(4 + data.len());
746    crc_buf.extend_from_slice(&tag);
747    crc_buf.extend_from_slice(data);
748    let checksum: u32 = crc32_bytes(&crc_buf);
749    out.extend_from_slice(&(data.len() as u32).to_be_bytes());
750    out.extend_from_slice(&tag);
751    out.extend_from_slice(data);
752    out.extend_from_slice(&checksum.to_be_bytes());
753}
754
755/// Decodes a single Base64 ASCII character to its 6-bit value.
756///
757/// # Arguments
758///
759/// - `u8` - Input ASCII byte.
760///
761/// # Returns
762///
763/// - `Option<u8>` - 6-bit symbol value or `None` if invalid.
764fn decode_base64_char(byte_val: u8) -> Option<u8> {
765    match byte_val {
766        b'A'..=b'Z' => Some(byte_val - b'A'),
767        b'a'..=b'z' => Some(byte_val - b'a' + 26),
768        b'0'..=b'9' => Some(byte_val - b'0' + 52),
769        b'+' => Some(62),
770        b'/' => Some(63),
771        _ => None,
772    }
773}
774
775/// Reads a big-endian `u32` at `offset` with bounds validation.
776///
777/// # Arguments
778///
779/// - `&[u8]` - Input byte slice.
780/// - `usize` - Starting byte offset.
781///
782/// # Returns
783///
784/// - `io::Result<u32>` - Decoded 32-bit integer.
785fn read_be_u32(bytes: &[u8], offset: usize) -> io::Result<u32> {
786    let slice: &[u8] = bytes
787        .get(offset..offset + 4)
788        .ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_PNG_INVALID))?;
789    Ok(u32::from_be_bytes([slice[0], slice[1], slice[2], slice[3]]))
790}
791
792/// Reverses PNG scanline filtering (None, Sub, Up, Average, Paeth) into `dst`.
793///
794/// # Arguments
795///
796/// - `u8` - PNG filter method byte (`0..=4`).
797/// - `&[u8]` - Filtered scanline bytes.
798/// - `&[u8]` - Previous unfiltered scanline bytes.
799/// - `&mut [u8]` - Destination unfiltered scanline buffer.
800/// - `usize` - Bytes-per-pixel filter stride (`>= 1`).
801///
802/// # Returns
803///
804/// - `io::Result<()>` - Error if `filter_type` is unrecognized.
805fn unfilter_png_scanline(
806    filter_type: u8,
807    src: &[u8],
808    prev: &[u8],
809    dst: &mut [u8],
810    bpp: usize,
811) -> io::Result<()> {
812    match filter_type {
813        0 => dst.copy_from_slice(src),
814        1 => {
815            let mut idx: usize = 0;
816            while idx < src.len() {
817                let left: u8 = if idx >= bpp { dst[idx - bpp] } else { 0 };
818                dst[idx] = src[idx].wrapping_add(left);
819                idx += 1;
820            }
821        }
822        2 => {
823            let mut idx: usize = 0;
824            while idx < src.len() {
825                dst[idx] = src[idx].wrapping_add(prev[idx]);
826                idx += 1;
827            }
828        }
829        3 => {
830            let mut idx: usize = 0;
831            while idx < src.len() {
832                let left: u16 = if idx >= bpp {
833                    u16::from(dst[idx - bpp])
834                } else {
835                    0
836                };
837                let up: u16 = u16::from(prev[idx]);
838                let avg: u8 = ((left + up) / 2) as u8;
839                dst[idx] = src[idx].wrapping_add(avg);
840                idx += 1;
841            }
842        }
843        4 => {
844            let mut idx: usize = 0;
845            while idx < src.len() {
846                let left: u8 = if idx >= bpp { dst[idx - bpp] } else { 0 };
847                let up: u8 = prev[idx];
848                let up_left: u8 = if idx >= bpp { prev[idx - bpp] } else { 0 };
849                dst[idx] = src[idx].wrapping_add(paeth_predictor(left, up, up_left));
850                idx += 1;
851            }
852        }
853        _ => return Err(Error::new(ErrorKind::InvalidData, ERR_PNG_FILTER)),
854    }
855    Ok(())
856}
857
858/// Computes the standard PNG Paeth predictor byte from left, above, and upper-left neighbors.
859///
860/// # Arguments
861///
862/// - `u8` - Left neighbor byte.
863/// - `u8` - Above neighbor byte.
864/// - `u8` - Upper-left neighbor byte.
865///
866/// # Returns
867///
868/// - `u8` - Selected predictor byte.
869fn paeth_predictor(left: u8, up: u8, up_left: u8) -> u8 {
870    let left_i: i32 = i32::from(left);
871    let up_i: i32 = i32::from(up);
872    let up_left_i: i32 = i32::from(up_left);
873    let pred: i32 = left_i + up_i - up_left_i;
874    let dist_left: i32 = (pred - left_i).abs();
875    let dist_up: i32 = (pred - up_i).abs();
876    let dist_up_left: i32 = (pred - up_left_i).abs();
877    if dist_left <= dist_up && dist_left <= dist_up_left {
878        left
879    } else if dist_up <= dist_up_left {
880        up
881    } else {
882        up_left
883    }
884}
885
886/// Expands one unfiltered PNG scanline of any supported color type and bit depth into RGBA8 bytes.
887///
888/// # Arguments
889///
890/// - `&[u8]` - Unfiltered scanline bytes.
891/// - `usize` - Row width in pixels.
892/// - `u8` - Sample bit depth (`1`, `2`, `4`, or `8`).
893/// - `u8` - PNG color type (`0`, `2`, `3`, `4`, or `6`).
894/// - `&[[u8; 3]]` - Decoded `PLTE` RGB entries.
895/// - `&[u8]` - Optional raw `tRNS` chunk bytes.
896/// - `&mut Vec<u8>` - Destination RGBA8 accumulator.
897///
898/// # Returns
899///
900/// - `io::Result<()>` - Error if palette indices or row layout are invalid.
901fn expand_png_row_to_rgba(
902    row: &[u8],
903    width: usize,
904    bit_depth: u8,
905    color_type: u8,
906    palette: &[[u8; 3]],
907    trns: &[u8],
908    out: &mut Vec<u8>,
909) -> io::Result<()> {
910    match color_type {
911        6 => {
912            if bit_depth != 8 || row.len() < width * 4 {
913                return Err(Error::new(ErrorKind::InvalidData, ERR_PNG_UNSUPPORTED));
914            }
915            out.extend_from_slice(&row[..width * 4]);
916        }
917        2 => {
918            if bit_depth != 8 || row.len() < width * 3 {
919                return Err(Error::new(ErrorKind::InvalidData, ERR_PNG_UNSUPPORTED));
920            }
921            let has_key: bool = trns.len() >= 6;
922            let key_r: u8 = if has_key { trns[1] } else { 0 };
923            let key_g: u8 = if has_key { trns[3] } else { 0 };
924            let key_b: u8 = if has_key { trns[5] } else { 0 };
925            let mut col: usize = 0;
926            while col < width {
927                let offset: usize = col * 3;
928                let red: u8 = row[offset];
929                let green: u8 = row[offset + 1];
930                let blue: u8 = row[offset + 2];
931                let alpha: u8 = if has_key && red == key_r && green == key_g && blue == key_b {
932                    0
933                } else {
934                    255
935                };
936                out.extend_from_slice(&[red, green, blue, alpha]);
937                col += 1;
938            }
939        }
940        4 => {
941            if bit_depth != 8 || row.len() < width * 2 {
942                return Err(Error::new(ErrorKind::InvalidData, ERR_PNG_UNSUPPORTED));
943            }
944            let mut col: usize = 0;
945            while col < width {
946                let gray: u8 = row[col * 2];
947                let alpha: u8 = row[col * 2 + 1];
948                out.extend_from_slice(&[gray, gray, gray, alpha]);
949                col += 1;
950            }
951        }
952        3 => {
953            let mut col: usize = 0;
954            while col < width {
955                let pal_idx: usize = usize::from(extract_packed_sample(row, col, bit_depth)?);
956                let rgb: [u8; 3] = *palette
957                    .get(pal_idx)
958                    .ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_PNG_INVALID))?;
959                let alpha: u8 = trns.get(pal_idx).copied().unwrap_or(255);
960                out.extend_from_slice(&[rgb[0], rgb[1], rgb[2], alpha]);
961                col += 1;
962            }
963        }
964        0 => {
965            let max_sample: u16 = (1u16 << bit_depth) - 1;
966            let has_key: bool = trns.len() >= 2;
967            let key_gray: u8 = if has_key { trns[1] } else { 0 };
968            let mut col: usize = 0;
969            while col < width {
970                let raw_val: u8 = extract_packed_sample(row, col, bit_depth)?;
971                let gray: u8 = if bit_depth == 8 {
972                    raw_val
973                } else {
974                    ((u16::from(raw_val) * 255) / max_sample) as u8
975                };
976                let alpha: u8 = if has_key && raw_val == key_gray {
977                    0
978                } else {
979                    255
980                };
981                out.extend_from_slice(&[gray, gray, gray, alpha]);
982                col += 1;
983            }
984        }
985        _ => return Err(Error::new(ErrorKind::InvalidData, ERR_PNG_UNSUPPORTED)),
986    }
987    Ok(())
988}
989
990/// Extracts a 1, 2, 4, or 8-bit sample at `col` from a packed PNG scanline.
991///
992/// # Arguments
993///
994/// - `&[u8]` - Unfiltered scanline bytes.
995/// - `usize` - Pixel column index.
996/// - `u8` - Sample bit depth (`1`, `2`, `4`, or `8`).
997///
998/// # Returns
999///
1000/// - `io::Result<u8>` - Extracted unsigned sample value.
1001fn extract_packed_sample(row: &[u8], col: usize, bit_depth: u8) -> io::Result<u8> {
1002    if bit_depth == 8 {
1003        return row
1004            .get(col)
1005            .copied()
1006            .ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_PNG_INVALID));
1007    }
1008    let samples_per_byte: usize = usize::from(8 / bit_depth);
1009    let byte_idx: usize = col / samples_per_byte;
1010    let sub_idx: usize = col % samples_per_byte;
1011    let byte_val: u8 = *row
1012        .get(byte_idx)
1013        .ok_or_else(|| Error::new(ErrorKind::InvalidData, ERR_PNG_INVALID))?;
1014    let shift: u8 = 8 - bit_depth * ((sub_idx as u8) + 1);
1015    let mask: u8 = (1u8 << bit_depth) - 1;
1016    Ok((byte_val >> shift) & mask)
1017}