euv-core 0.50.0

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
Documentation
use super::*;

/// Registers a platform-host native OS capability bridge (haptics, notifications, permissions, fullscreen, Dynamic Island).
///
/// # Arguments
///
/// - `fn(&str, &str, &str) -> bool` - Host callback handling `(kind, arg1, arg2)` and returning whether native OS execution succeeded.
pub fn register_native_action_bridge(bridge: fn(&str, &str, &str) -> bool) {
    EXTERNAL_NATIVE_ACTION_BRIDGE.store(bridge as *mut (), Ordering::Release);
}

/// Dispatches a native OS capability action `(kind, arg1, arg2)` to the registered host bridge, if any.
///
/// # Arguments
///
/// - `&str` - Action category (`"haptic"`, `"notify"`, `"island"`, `"permission"`, `"fullscreen"`, `"protocol"`).
/// - `&str` - Primary payload argument (e.g. title or permission key).
/// - `&str` - Secondary payload argument (e.g. body or rationale).
///
/// # Returns
///
/// - `bool` - `true` when handled by an active native OS host bridge.
pub fn dispatch_native_action(kind: &str, arg1: &str, arg2: &str) -> bool {
    let raw: *mut () = EXTERNAL_NATIVE_ACTION_BRIDGE.load(Ordering::Acquire);
    if raw.is_null() {
        return false;
    }
    // SAFETY: `raw` is stored exclusively via `register_native_action_bridge` from a `fn(&str, &str, &str) -> bool` pointer.
    let func: fn(&str, &str, &str) -> bool =
        unsafe { transmute::<*mut (), fn(&str, &str, &str) -> bool>(raw) };
    func(kind, arg1, arg2)
}

/// Copies `text` to the active OS or browser clipboard via direct platform hooks and any registered native action bridge.
///
/// # Arguments
///
/// - `&str` - UTF-8 text string to place on the system clipboard.
///
/// # Returns
///
/// - `bool` - `true` when at least one native or host clipboard sink accepted `text`.
pub fn write_system_clipboard(text: &str) -> bool {
    let bridge_ok: bool =
        dispatch_native_action(NATIVE_ACTION_CLIPBOARD, CLIPBOARD_ACTION_WRITE, text);
    #[cfg(target_os = "macos")]
    {
        macos_write_pasteboard(text) || bridge_ok
    }
    #[cfg(target_arch = "wasm32")]
    {
        web_write_clipboard(text) || bridge_ok
    }
    #[cfg(not(any(target_os = "macos", target_arch = "wasm32")))]
    {
        bridge_ok
    }
}

/// Validates that `url` is a safe external `http://` or `https://` URL without whitespace or control characters.
///
/// # Arguments
///
/// - `&str` - Candidate external URL string.
///
/// # Returns
///
/// - `bool` - `true` when `url` has a valid `http://` or `https://` prefix, a non-empty host authority, and no control or whitespace characters.
#[must_use]
pub fn is_valid_external_url(url: &str) -> bool {
    let trimmed: &str = url.trim();
    if trimmed.is_empty() {
        return false;
    }
    let rest: &str = if let Some(after_https) = trimmed.strip_prefix(URL_SCHEME_HTTPS) {
        after_https
    } else if let Some(after_http) = trimmed.strip_prefix(URL_SCHEME_HTTP) {
        after_http
    } else {
        return false;
    };
    if rest.is_empty() || rest.starts_with('/') {
        return false;
    }
    !trimmed
        .chars()
        .any(|ch: char| ch.is_control() || ch.is_whitespace())
}

/// Spawns the host desktop OS browser launcher for a validated URL outside test and headless runs.
///
/// # Arguments
///
/// - `&str` - Validated external URL string.
///
/// # Returns
///
/// - `bool` - `true` when the desktop launcher process spawned successfully.
#[cfg(not(target_arch = "wasm32"))]
fn open_external_url_desktop(target: &str) -> bool {
    if cfg!(test) || env::var_os(ENV_EUV_HEADLESS).is_some() {
        return false;
    }
    #[cfg(target_os = "macos")]
    {
        Command::new(OS_CMD_OPEN)
            .arg(target)
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn()
            .is_ok()
    }
    #[cfg(target_os = "linux")]
    {
        Command::new(OS_CMD_XDG_OPEN)
            .arg(target)
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn()
            .is_ok()
    }
    #[cfg(target_os = "windows")]
    {
        Command::new(OS_CMD_WIN_SHELL)
            .args([OS_CMD_WIN_EXEC, OS_CMD_WIN_START, "", target])
            .stdin(Stdio::null())
            .stdout(Stdio::null())
            .stderr(Stdio::null())
            .spawn()
            .is_ok()
    }
    #[cfg(not(any(target_os = "macos", target_os = "linux", target_os = "windows")))]
    {
        let _: &str = target;
        false
    }
}

/// Opens a validated `http://` or `https://` URL externally via the registered host bridge, browser `window.open`, or native desktop launcher.
///
/// # Arguments
///
/// - `&str` - External URL to open (`https://...` or `http://...`).
///
/// # Returns
///
/// - `bool` - `true` when the URL passed validation and was accepted by a host bridge or OS/browser launcher.
pub fn open_external_url(url: &str) -> bool {
    if !is_valid_external_url(url) {
        return false;
    }
    let target: &str = url.trim();
    if let Ok(mut guard) = LAST_EXTERNAL_URL.lock() {
        *guard = Some(target.to_string());
    }
    let bridge_ok: bool = dispatch_native_action(NATIVE_ACTION_OPEN_URL, target, "");
    #[cfg(target_arch = "wasm32")]
    {
        bridge_ok || web_open_external_url(target)
    }
    #[cfg(not(target_arch = "wasm32"))]
    {
        let desktop_ok: bool = open_external_url_desktop(target);
        let headless_recorded: bool = cfg!(test) || env::var_os(ENV_EUV_HEADLESS).is_some();
        let host_ok: bool = bridge_ok || desktop_ok;
        host_ok || headless_recorded
    }
}

/// Dispatches an embedded bottom-sheet WebView open/navigate request to any active native host bridge and records telemetry for simulator verification.
///
/// # Arguments
///
/// - `&str` - Validated `http://` or `https://` target URL.
/// - `&str` - Sheet header title.
///
/// # Returns
///
/// - `bool` - `true` when `url` passed validation and the WebView sheet state updated.
pub fn open_webview_sheet_bridge(url: &str, title: &str) -> bool {
    if !is_valid_external_url(url) {
        return false;
    }
    let target: &str = url.trim();
    if let Ok(mut guard) = LAST_WEBVIEW_SHEET.lock() {
        *guard = Some((target.to_string(), title.to_string()));
    }
    if let Ok(mut frame_guard) = LAST_WEBVIEW_FRAME.lock() {
        *frame_guard = None;
    }
    let bridge_ok: bool = dispatch_native_action(NATIVE_ACTION_WEBVIEW, target, title);
    #[cfg(target_arch = "wasm32")]
    {
        let _: bool = web_webview_open(target, title) || bridge_ok;
    }
    #[cfg(target_os = "macos")]
    {
        if !bridge_ok && !cfg!(test) && env::var_os(ENV_EUV_HEADLESS).is_none() {
            let _: bool = macos_webview_open(target, title);
        }
    }
    #[cfg(not(any(target_arch = "wasm32", target_os = "macos")))]
    {
        let _: bool = bridge_ok;
    }
    true
}

/// Synchronizes the screen-space logical viewport rectangle and opacity of the active embedded WebView sheet with the host overlay.
///
/// # Arguments
///
/// - `Rect` - Screen-space logical viewport rectangle covering the embedded WebView content container.
/// - `f32` - Effective composed opacity in `0.0..=1.0`.
///
/// # Returns
///
/// - `bool` - `true` when the geometry or opacity changed and was dispatched to the host overlay.
pub fn sync_webview_sheet_frame(bounds: Rect, opacity: f32) -> bool {
    let left_px: f32 = if bounds.get_x().is_finite() {
        bounds.get_x()
    } else {
        0.0
    };
    let top_px: f32 = if bounds.get_y().is_finite() {
        bounds.get_y()
    } else {
        0.0
    };
    let width_px: f32 = if bounds.get_width().is_finite() {
        bounds.get_width().max(0.0)
    } else {
        0.0
    };
    let height_px: f32 = if bounds.get_height().is_finite() {
        bounds.get_height().max(0.0)
    } else {
        0.0
    };
    let alpha_val: f32 = if opacity.is_finite() {
        opacity.clamp(0.0, 1.0)
    } else {
        0.0
    };
    let next_rect: Rect = Rect::new(left_px, top_px, width_px, height_px);
    let next_frame: (Rect, f32) = (next_rect, alpha_val);
    if let Ok(mut frame_guard) = LAST_WEBVIEW_FRAME.lock() {
        if let Some((prev_rect, prev_alpha)) = *frame_guard {
            let same_pos: bool = (prev_rect.get_x() - left_px).abs() <= 0.25
                && (prev_rect.get_y() - top_px).abs() <= 0.25;
            let same_size: bool = (prev_rect.get_width() - width_px).abs() <= 0.25
                && (prev_rect.get_height() - height_px).abs() <= 0.25;
            let same_alpha: bool = (prev_alpha - alpha_val).abs() <= 0.005;
            if same_pos && same_size && same_alpha {
                return false;
            }
        }
        *frame_guard = Some(next_frame);
    }
    let payload_csv: String =
        format!("{left_px:.2},{top_px:.2},{width_px:.2},{height_px:.2},{alpha_val:.3}");
    let bridge_ok: bool =
        dispatch_native_action(NATIVE_ACTION_WEBVIEW, WEBVIEW_ACTION_FRAME, &payload_csv);
    #[cfg(target_arch = "wasm32")]
    {
        let _: bool =
            web_webview_frame(left_px, top_px, width_px, height_px, alpha_val) || bridge_ok;
    }
    #[cfg(target_os = "macos")]
    {
        if !bridge_ok && !cfg!(test) && env::var_os(ENV_EUV_HEADLESS).is_none() {
            let _: bool = macos_webview_frame(left_px, top_px, width_px, height_px, alpha_val);
        }
    }
    #[cfg(not(any(target_arch = "wasm32", target_os = "macos")))]
    {
        let _: bool = bridge_ok;
    }
    true
}

/// Reloads the active webpage inside any hosted native embedded bottom-sheet WebView.
///
/// # Returns
///
/// - `bool` - `true` when an active WebView target existed and a reload command was dispatched.
pub fn reload_webview_sheet_bridge() -> bool {
    let active_url: Option<String> = LAST_WEBVIEW_SHEET.lock().ok().and_then(
        |guard: MutexGuard<'_, Option<(String, String)>>| {
            guard.as_ref().map(|pair: &(String, String)| pair.0.clone())
        },
    );
    let Some(target_url) = active_url else {
        return false;
    };
    let bridge_ok: bool =
        dispatch_native_action(NATIVE_ACTION_WEBVIEW, WEBVIEW_ACTION_RELOAD, &target_url);
    #[cfg(target_arch = "wasm32")]
    {
        let _: bool = web_webview_reload(&target_url) || bridge_ok;
    }
    #[cfg(target_os = "macos")]
    {
        if !bridge_ok && !cfg!(test) && env::var_os(ENV_EUV_HEADLESS).is_none() {
            let _: bool = macos_webview_reload(&target_url);
        }
    }
    #[cfg(not(any(target_arch = "wasm32", target_os = "macos")))]
    {
        let _: bool = bridge_ok;
    }
    true
}

/// Notifies any active native host bridge that the embedded bottom-sheet WebView was dismissed.
///
/// # Returns
///
/// - `bool` - `true` when handled by an active native host bridge.
pub fn close_webview_sheet_bridge() -> bool {
    if let Ok(mut guard) = LAST_WEBVIEW_SHEET.lock() {
        *guard = None;
    }
    if let Ok(mut frame_guard) = LAST_WEBVIEW_FRAME.lock() {
        *frame_guard = None;
    }
    let bridge_ok: bool = dispatch_native_action(NATIVE_ACTION_WEBVIEW, WEBVIEW_ACTION_CLOSE, "");
    #[cfg(target_arch = "wasm32")]
    {
        web_webview_close() || bridge_ok
    }
    #[cfg(target_os = "macos")]
    {
        if !bridge_ok && !cfg!(test) && env::var_os(ENV_EUV_HEADLESS).is_none() {
            macos_webview_close() || bridge_ok
        } else {
            bridge_ok
        }
    }
    #[cfg(not(any(target_arch = "wasm32", target_os = "macos")))]
    {
        bridge_ok
    }
}

/// Returns the most recently synchronized embedded WebView `(bounds, opacity)` frame, or `None` after close.
///
/// # Returns
///
/// - `Option<(Rect, f32)>` - Last dispatched embedded WebView viewport rectangle and opacity.
#[must_use]
pub fn last_webview_sheet_frame() -> Option<(Rect, f32)> {
    LAST_WEBVIEW_FRAME
        .lock()
        .ok()
        .and_then(|guard: MutexGuard<'_, Option<(Rect, f32)>>| *guard)
}

/// Returns the most recently validated URL passed to `open_external_url` in this process.
///
/// # Returns
///
/// - `Option<String>` - Last external browser URL, if any.
#[must_use]
pub fn last_opened_external_url() -> Option<String> {
    LAST_EXTERNAL_URL
        .lock()
        .ok()
        .and_then(|guard: MutexGuard<'_, Option<String>>| guard.clone())
}

/// Returns the currently active `(url, title)` pair opened via `open_webview_sheet_bridge`, or `None` after close.
///
/// # Returns
///
/// - `Option<(String, String)>` - Active WebView sheet URL and title, if open.
#[must_use]
pub fn active_webview_sheet_target() -> Option<(String, String)> {
    LAST_WEBVIEW_SHEET
        .lock()
        .ok()
        .and_then(|guard: MutexGuard<'_, Option<(String, String)>>| guard.clone())
}

/// Clears recorded `open_external_url` and `open_webview_sheet_bridge` telemetry for isolated test runs.
pub fn clear_link_action_history() {
    if let Ok(mut ext_guard) = LAST_EXTERNAL_URL.lock() {
        *ext_guard = None;
    }
    if let Ok(mut wv_guard) = LAST_WEBVIEW_SHEET.lock() {
        *wv_guard = None;
    }
    if let Ok(mut frame_guard) = LAST_WEBVIEW_FRAME.lock() {
        *frame_guard = None;
    }
}