euv-ui 0.51.0

Cross-platform UI component library and 17-scheme design system for the euv framework with pixel-consistent rendering across Web, Android, iOS, iPadOS, macOS, Windows, and Linux.
Documentation
use super::*;

/// Extracts an XML attribute value (`name="value"` or `name='value'`) from an SVG element tag slice.
///
/// # Arguments
///
/// - `&'a str` - Trimmed SVG element tag slice (without enclosing angle brackets).
/// - `&str` - Attribute name to locate.
///
/// # Returns
///
/// - `Option<&'a str>` - Extracted attribute value slice when present.
#[must_use]
fn extract_svg_attr<'a>(tag: &'a str, attr_name: &str) -> Option<&'a str> {
    let bytes: &[u8] = tag.as_bytes();
    let name_bytes: &[u8] = attr_name.as_bytes();
    let name_len: usize = name_bytes.len();
    let mut cursor: usize = 0;
    while cursor + name_len < bytes.len() {
        let rel: usize = tag[cursor..].find(attr_name)?;
        let pos: usize = cursor + rel;
        let left_ok: bool = pos == 0 || bytes[pos - 1].is_ascii_whitespace();
        let after: usize = pos + name_len;
        if left_ok && after < bytes.len() {
            let rest: &str = tag[after..].trim_start();
            if let Some(after_eq) = rest.strip_prefix('=') {
                let val_trimmed: &str = after_eq.trim_start();
                let mut chars: Chars<'_> = val_trimmed.chars();
                if let Some(quote) = chars.next()
                    && (quote == '"' || quote == '\'')
                    && let Some(end_idx) = val_trimmed[1..].find(quote)
                {
                    return Some(&val_trimmed[1..1 + end_idx]);
                }
            }
        }
        cursor = after;
    }
    None
}

/// Parses a numeric SVG attribute value or returns `fallback` when missing or non-finite.
///
/// # Arguments
///
/// - `&str` - Trimmed SVG element tag slice.
/// - `&str` - Attribute name to parse.
/// - `f32` - Default fallback value.
///
/// # Returns
///
/// - `f32` - Parsed numeric coordinate or dimension.
#[must_use]
fn parse_svg_attr_f32(tag: &str, attr_name: &str, fallback: f32) -> f32 {
    extract_svg_attr(tag, attr_name)
        .and_then(|raw: &str| raw.trim().parse::<f32>().ok())
        .filter(|val: &f32| val.is_finite())
        .unwrap_or(fallback)
}

/// Parses a 3-digit, 6-digit, or 8-digit hexadecimal SVG paint color string.
///
/// # Arguments
///
/// - `&str` - Raw SVG paint string (e.g. `#38BDF8`, `#FFF`, or `none`).
/// - `Color` - Fallback color when parsing fails.
///
/// # Returns
///
/// - `Color` - Decoded RGBA color (`COLOR_TRANSPARENT` for `none`).
#[must_use]
fn parse_svg_hex_color(raw: &str, fallback: Color) -> Color {
    let trimmed: &str = raw.trim();
    if trimmed.eq_ignore_ascii_case(SVG_PAINT_NONE) {
        return COLOR_TRANSPARENT;
    }
    let hex: &str = trimmed.strip_prefix('#').unwrap_or(trimmed);
    if hex.len() == 6
        && let Ok(rgb) = u32::from_str_radix(hex, 16)
    {
        return Color::hex(rgb);
    }
    if hex.len() == 3
        && let Ok(short) = u32::from_str_radix(hex, 16)
    {
        let red: u8 = (((short >> 8) & 0xF) * 17) as u8;
        let green: u8 = (((short >> 4) & 0xF) * 17) as u8;
        let blue: u8 = ((short & 0xF) * 17) as u8;
        return Color::rgb(red, green, blue);
    }
    if hex.len() == 8
        && let Ok(rgba) = u32::from_str_radix(hex, 16)
    {
        return Color::rgba(
            ((rgba >> 24) & 0xFF) as u8,
            ((rgba >> 16) & 0xFF) as u8,
            ((rgba >> 8) & 0xFF) as u8,
            (rgba & 0xFF) as u8,
        );
    }
    fallback
}

/// Computes the exact live physical pixel backing dimensions `(ceil(layout_w * dpr), ceil(layout_h * dpr))` for an `SvgDocument` without fixed low-resolution or `2048px` caps.
///
/// # Arguments
///
/// - `Rect` - Active logical layout bounds of the SVG viewport.
/// - `f32` - Live display DPI scale factor.
///
/// # Returns
///
/// - `(u32, u32)` - Exact physical `(width, height)` in device pixels.
#[must_use]
pub fn resolve_svg_physical_dimensions(bounds: Rect, scale_factor: f32) -> (u32, u32) {
    let safe_scale: f64 = f64::from(clamp_viewport_scale(scale_factor));
    let phys_w: u32 = (f64::from(bounds.get_width().max(1.0)) * safe_scale)
        .ceil()
        .max(1.0) as u32;
    let phys_h: u32 = (f64::from(bounds.get_height().max(1.0)) * safe_scale)
        .ceil()
        .max(1.0) as u32;
    (phys_w, phys_h)
}

/// Paints an `SvgDocument` losslessly into `display_list` as resolution-independent analytic vector `DrawCommand`s crisp at any layout size and DPR.
///
/// # Arguments
///
/// - `&SvgDocument` - Parsed SVG document carrying raw vector markup and fallback raster buffer.
/// - `Rect` - Live logical target layout bounds.
/// - `&mut DisplayList` - Destination display list receiving analytic vector commands.
///
/// # Returns
///
/// - `usize` - Number of analytic vector primitives emitted (`0` indicates raster fallback was used).
pub fn paint_svg_document_lossless(
    document: &SvgDocument,
    bounds: Rect,
    display_list: &mut DisplayList,
) -> usize {
    let raw_svg: &str = document.get_raw_svg().as_str();
    let mut vb_w: f32 = document.get_view_box_width().max(1.0);
    let mut vb_h: f32 = document.get_view_box_height().max(1.0);
    if let Some(vb_str) = extract_svg_attr(raw_svg, SVG_ATTR_VIEW_BOX) {
        let nums: Vec<f32> = vb_str
            .split_whitespace()
            .filter_map(|token: &str| token.parse::<f32>().ok())
            .collect();
        if nums.len() >= 4 {
            vb_w = nums[2].max(1.0);
            vb_h = nums[3].max(1.0);
        }
    }
    let scale_x: f32 = bounds.get_width().max(1.0) / vb_w;
    let scale_y: f32 = bounds.get_height().max(1.0) / vb_h;
    let uniform_scale: f32 = scale_x.min(scale_y);
    let ox: f32 = bounds.get_x();
    let oy: f32 = bounds.get_y();
    let mut emitted: usize = 0;
    let mut cursor: usize = 0;
    while let Some(open_rel) = raw_svg[cursor..].find('<') {
        let start: usize = cursor + open_rel;
        let Some(close_rel) = raw_svg[start..].find('>') else {
            break;
        };
        let tag: &str = raw_svg[start + 1..start + close_rel].trim();
        cursor = start + close_rel + 1;
        if tag.starts_with(SVG_TAG_RECT) {
            let rx_pos: f32 = ox + parse_svg_attr_f32(tag, "x", 0.0) * scale_x;
            let ry_pos: f32 = oy + parse_svg_attr_f32(tag, "y", 0.0) * scale_y;
            let rw: f32 = parse_svg_attr_f32(tag, SVG_ATTR_WIDTH, vb_w) * scale_x;
            let rh: f32 = parse_svg_attr_f32(tag, SVG_ATTR_HEIGHT, vb_h) * scale_y;
            let radius_x: f32 = parse_svg_attr_f32(tag, "rx", 0.0) * uniform_scale;
            let radius_y: f32 =
                parse_svg_attr_f32(tag, "ry", radius_x / uniform_scale.max(1e-4)) * uniform_scale;
            let corner_r: f32 = radius_x.max(radius_y).max(0.0);
            let fill_col: Color = parse_svg_hex_color(
                extract_svg_attr(tag, SVG_ATTR_FILL).unwrap_or(SVG_DEFAULT_RECT_FILL),
                Color::hex(0x0F172A),
            );
            let stroke_border: Border = match extract_svg_attr(tag, SVG_ATTR_STROKE) {
                Some(stroke_raw) => {
                    let stroke_col: Color = parse_svg_hex_color(stroke_raw, COLOR_TRANSPARENT);
                    let stroke_w: f32 =
                        parse_svg_attr_f32(tag, SVG_ATTR_STROKE_WIDTH, 1.0) * uniform_scale;
                    Border::new(stroke_w.max(0.5), stroke_col)
                }
                None => Border::default(),
            };
            display_list.push(DrawCommand::FillRoundedRect {
                rect: Rect::new(rx_pos, ry_pos, rw.max(0.5), rh.max(0.5)),
                color: fill_col,
                radius: CornerRadius::all(corner_r),
                border: stroke_border,
            });
            emitted += 1;
        } else if tag.starts_with(SVG_TAG_CIRCLE) {
            let cx: f32 = ox + parse_svg_attr_f32(tag, "cx", vb_w * 0.5) * scale_x;
            let cy: f32 = oy + parse_svg_attr_f32(tag, "cy", vb_h * 0.5) * scale_y;
            let rad: f32 = parse_svg_attr_f32(tag, "r", 16.0) * uniform_scale;
            let fill_col: Color = parse_svg_hex_color(
                extract_svg_attr(tag, SVG_ATTR_FILL).unwrap_or(SVG_DEFAULT_CIRCLE_FILL),
                Color::hex(0x38BDF8),
            );
            display_list.push(DrawCommand::Circle {
                center: Point::new(cx, cy),
                radius: rad.max(0.5),
                color: fill_col,
            });
            emitted += 1;
        } else if tag.starts_with(SVG_TAG_LINE) {
            let x1: f32 = ox + parse_svg_attr_f32(tag, "x1", 0.0) * scale_x;
            let y1: f32 = oy + parse_svg_attr_f32(tag, "y1", 0.0) * scale_y;
            let x2: f32 = ox + parse_svg_attr_f32(tag, "x2", vb_w) * scale_x;
            let y2: f32 = oy + parse_svg_attr_f32(tag, "y2", vb_h) * scale_y;
            let stroke_w: f32 =
                (parse_svg_attr_f32(tag, SVG_ATTR_STROKE_WIDTH, 1.0) * uniform_scale).max(0.75);
            let stroke_col: Color = parse_svg_hex_color(
                extract_svg_attr(tag, SVG_ATTR_STROKE).unwrap_or(SVG_DEFAULT_LINE_STROKE),
                COLOR_WHITE,
            );
            display_list.push(DrawCommand::Line {
                from: Point::new(x1, y1),
                to: Point::new(x2, y2),
                width: stroke_w,
                color: stroke_col,
            });
            emitted += 1;
        }
    }
    if emitted == 0 {
        display_list.push(DrawCommand::Image {
            rect: bounds,
            buffer: document.get_rasterized().clone(),
            radius: CornerRadius::default(),
        });
    }
    emitted
}