euv-core 0.47.1

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::*;

#[link(name = "android")]
unsafe extern "C" {
    /// Body of the `ANativeWindow_getWidth` free function.
    ///
    /// # Arguments
    ///
    /// - `*mut c_void` - A `*mut c_void` parameter.
    ///
    /// # Returns
    ///
    /// - `i32` - A 32-bit signed integer.
    fn ANativeWindow_getWidth(window: *mut c_void) -> i32;
    /// Body of the `ANativeWindow_getHeight` free function.
    ///
    /// # Arguments
    ///
    /// - `*mut c_void` - A `*mut c_void` parameter.
    ///
    /// # Returns
    ///
    /// - `i32` - A 32-bit signed integer.
    fn ANativeWindow_getHeight(window: *mut c_void) -> i32;
    /// Body of the `ANativeWindow_setBuffersGeometry` free function.
    ///
    /// # Arguments
    ///
    /// - `*mut c_void` - A `*mut c_void` parameter.
    /// - `i32` - A 32-bit signed integer (`i32`).
    /// - `i32` - A 32-bit signed integer (`i32`).
    /// - `i32` - A 32-bit signed integer (`i32`).
    ///
    /// # Returns
    ///
    /// - `i32` - A 32-bit signed integer.
    fn ANativeWindow_setBuffersGeometry(
        window: *mut c_void,
        width: i32,
        height: i32,
        format: i32,
    ) -> i32;
    /// Body of the `ANativeWindow_lock` free function.
    ///
    /// # Arguments
    ///
    /// - `*mut c_void` - A `*mut c_void` parameter.
    /// - `*mut ANativeWindowBuffer` - A `*mut ANativeWindowBuffer` parameter.
    /// - `*mut c_void` - A `*mut c_void` parameter.
    ///
    /// # Returns
    ///
    /// - `i32` - A 32-bit signed integer.
    fn ANativeWindow_lock(
        window: *mut c_void,
        out_buffer: *mut ANativeWindowBuffer,
        in_out_dirty_bounds: *mut c_void,
    ) -> i32;
    /// Body of the `ANativeWindow_unlockAndPost` free function.
    ///
    /// # Arguments
    ///
    /// - `*mut c_void` - A `*mut c_void` parameter.
    ///
    /// # Returns
    ///
    /// - `i32` - A 32-bit signed integer.
    fn ANativeWindow_unlockAndPost(window: *mut c_void) -> i32;
}

unsafe extern "C" {
    /// Dynamically opens a shared library on Android bionic.
    ///
    /// # Arguments
    ///
    /// - `*const c_char` - Null-terminated library name.
    /// - `i32` - Dynamic linker flags.
    ///
    /// # Returns
    ///
    /// - `*mut c_void` - Library handle or null.
    fn dlopen(filename: *const c_char, flag: i32) -> *mut c_void;
    /// Dynamically resolves a symbol pointer from a loaded Android shared library.
    ///
    /// # Arguments
    ///
    /// - `*mut c_void` - Loaded library handle.
    /// - `*const c_char` - Null-terminated symbol name.
    ///
    /// # Returns
    ///
    /// - `*mut c_void` - Resolved symbol pointer or null.
    fn dlsym(handle: *mut c_void, symbol: *const c_char) -> *mut c_void;
}

/// Resolves and caches `ANativeWindow_setFrameRate*` symbols once from `libandroid.so` without leaking `dlopen` handles.
///
/// # Returns
///
/// - `(usize, usize)` - Cached `(setFrameRateWithChangeStrategy, setFrameRate)` function pointer addresses (`0` when absent).
fn android_cached_frame_rate_syms() -> (usize, usize) {
    *ANDROID_FRAME_RATE_SYMS.get_or_init(|| -> (usize, usize) {
        // SAFETY: Opens `libandroid.so` once for the process lifetime and resolves optional API 30+/31+ symbols.
        unsafe {
            let lib: *mut c_void = dlopen(
                ANDROID_LIB_NAME.as_ptr().cast::<c_char>(),
                ANDROID_RTLD_LAZY,
            );
            if lib.is_null() {
                return (0, 0);
            }
            let sym31: usize = dlsym(
                lib,
                SYM_ANDROID_SET_FRAME_RATE_STRATEGY
                    .as_ptr()
                    .cast::<c_char>(),
            ) as usize;
            let sym30: usize =
                dlsym(lib, SYM_ANDROID_SET_FRAME_RATE.as_ptr().cast::<c_char>()) as usize;
            (sym31, sym30)
        }
    })
}

/// Hints the preferred high-refresh frame rate to Android SurfaceFlinger via `ANativeWindow_setFrameRateWithChangeStrategy` (`CHANGE_FRAME_RATE_ALWAYS`, API 31+) or `ANativeWindow_setFrameRate` (API 30+).
///
/// # Arguments
///
/// - `usize` - Raw `ANativeWindow*` pointer.
/// - `f32` - Desired hardware refresh rate in Hertz (`60.0`..`480.0`).
///
/// # Returns
///
/// - `bool` - `true` when the NDK frame-rate hint symbol was resolved and returned status `0`.
pub fn android_set_native_window_frame_rate(native_window: usize, refresh_hz: f32) -> bool {
    if native_window == 0 || !refresh_hz.is_finite() || refresh_hz < MIN_REFRESH_RATE_HZ {
        return false;
    }
    let hz: f32 = refresh_hz.clamp(MIN_REFRESH_RATE_HZ, MAX_REFRESH_RATE_HZ);
    let (sym31, sym30): (usize, usize) = android_cached_frame_rate_syms();
    // SAFETY: Invokes cached optional API 30+/31+ NDK frame-rate symbols with exact C ABI.
    unsafe {
        if sym31 != 0 {
            let func: unsafe extern "C" fn(*mut c_void, f32, i8, i8) -> i32 =
                transmute(sym31 as *const c_void);
            return func(
                native_window as *mut c_void,
                hz,
                ANDROID_FRAME_RATE_COMPAT_FIXED_SOURCE,
                ANDROID_CHANGE_FRAME_RATE_ALWAYS,
            ) == 0;
        }
        if sym30 != 0 {
            let func: unsafe extern "C" fn(*mut c_void, f32, i8) -> i32 =
                transmute(sym30 as *const c_void);
            return func(
                native_window as *mut c_void,
                hz,
                ANDROID_FRAME_RATE_COMPAT_FIXED_SOURCE,
            ) == 0;
        }
        false
    }
}

/// Decodes a packed little-endian direct `ByteBuffer` touch batch flushed once per frame over JNI.
///
/// # Arguments
///
/// - `&[u8]` - Raw byte slice containing contiguous 20-byte `AndroidTouchBatchEntry` records.
///
/// # Returns
///
/// - `Vec<AndroidTouchBatchEntry>` - Decoded touch entries in arrival order.
#[must_use]
pub fn android_decode_touch_batch(bytes: &[u8]) -> Vec<AndroidTouchBatchEntry> {
    let count: usize = bytes.len() / ANDROID_TOUCH_BATCH_RECORD_BYTES;
    let mut out: Vec<AndroidTouchBatchEntry> = Vec::with_capacity(count);
    for idx in 0..count {
        let base: usize = idx * ANDROID_TOUCH_BATCH_RECORD_BYTES;
        let action: i32 = i32::from_le_bytes([
            bytes[base],
            bytes[base + 1],
            bytes[base + 2],
            bytes[base + 3],
        ]);
        let action_index: i32 = i32::from_le_bytes([
            bytes[base + 4],
            bytes[base + 5],
            bytes[base + 6],
            bytes[base + 7],
        ]);
        let pointer_id: i32 = i32::from_le_bytes([
            bytes[base + 8],
            bytes[base + 9],
            bytes[base + 10],
            bytes[base + 11],
        ]);
        let x: f32 = f32::from_le_bytes([
            bytes[base + 12],
            bytes[base + 13],
            bytes[base + 14],
            bytes[base + 15],
        ]);
        let y: f32 = f32::from_le_bytes([
            bytes[base + 16],
            bytes[base + 17],
            bytes[base + 18],
            bytes[base + 19],
        ]);
        out.push(AndroidTouchBatchEntry {
            action,
            action_index,
            pointer_id,
            x,
            y,
        });
    }
    out
}

/// Queries physical pixel dimensions from an attached `ANativeWindow*`.
///
/// # Arguments
///
/// - `usize` - Raw `ANativeWindow*` pointer.
///
/// # Returns
///
/// - `Option<(u32, u32)>` - Physical `(width, height)` when the native window is attached.
#[must_use]
pub fn android_query_window_size(native_window: usize) -> Option<(u32, u32)> {
    if native_window == 0 {
        return None;
    }
    // SAFETY: Caller supplies a live `ANativeWindow*` owned by the Android lifecycle.
    unsafe {
        let w: i32 = ANativeWindow_getWidth(native_window as *mut c_void);
        let h: i32 = ANativeWindow_getHeight(native_window as *mut c_void);
        if w > 0 && h > 0 {
            Some((w as u32, h as u32))
        } else {
            None
        }
    }
}

/// Locks an `ANativeWindow*`, copies RGBA8 pixels (supporting dirty-rect sub-region locks), and posts the frame.
///
/// # Arguments
///
/// - `usize` - Raw `ANativeWindow*` pointer.
/// - `&Framebuffer` - Rendered RGBA8 framebuffer.
/// - `&mut u32` - Cached surface width avoiding redundant `ANativeWindow_setBuffersGeometry` calls.
/// - `&mut u32` - Cached surface height avoiding redundant `ANativeWindow_setBuffersGeometry` calls.
/// - `Option<Rect>` - Optional dirty pixel sub-rectangle for partial lock/copy.
///
/// # Returns
///
/// - `Result<(), PlatformError>` - Presentation status.
pub(crate) fn android_present_native_window(
    native_window: usize,
    framebuffer: &Framebuffer,
    cached_w: &mut u32,
    cached_h: &mut u32,
    dirty_rect: Option<Rect>,
) -> Result<(), PlatformError> {
    if native_window == 0 {
        return Ok(());
    }
    let fb_w: u32 = framebuffer.get_width();
    let fb_h: u32 = framebuffer.get_height();
    let src_w: usize = fb_w as usize;
    let src_h: usize = fb_h as usize;
    let src_bytes: &[u8] = framebuffer.get_pixels().as_slice();
    let mut buffer: ANativeWindowBuffer = ANativeWindowBuffer {
        width: 0,
        height: 0,
        stride: 0,
        format: 0,
        bits: null_mut(),
        reserved: [0; 6],
    };
    let mut bounds: AndroidRect = match dirty_rect {
        Some(r) => AndroidRect {
            left: (r.get_x().floor().max(0.0) as i32).min(fb_w as i32),
            top: (r.get_y().floor().max(0.0) as i32).min(fb_h as i32),
            right: ((r.get_x() + r.get_width()).ceil().max(0.0) as i32).min(fb_w as i32),
            bottom: ((r.get_y() + r.get_height()).ceil().max(0.0) as i32).min(fb_h as i32),
        },
        None => AndroidRect::default(),
    };
    let use_dirty: bool =
        dirty_rect.is_some() && bounds.right > bounds.left && bounds.bottom > bounds.top;
    // SAFETY: Locks the NDK hardware surface buffer, copies bounded RGBA8 scanlines, and always unlocks.
    unsafe {
        if *cached_w != fb_w || *cached_h != fb_h {
            let _: i32 = ANativeWindow_setBuffersGeometry(
                native_window as *mut c_void,
                src_w as i32,
                src_h as i32,
                ANDROID_WINDOW_FORMAT_RGBA_8888,
            );
            *cached_w = fb_w;
            *cached_h = fb_h;
        }
        let dirty_ptr: *mut c_void = if use_dirty {
            (&mut bounds as *mut AndroidRect).cast::<c_void>()
        } else {
            null_mut()
        };
        let status: i32 = ANativeWindow_lock(native_window as *mut c_void, &mut buffer, dirty_ptr);
        if status != 0 {
            return Err(PlatformError::SurfaceError(
                ERR_ANDROID_LOCK_SURFACE.to_string(),
            ));
        }
        if !buffer.bits.is_null() && buffer.stride > 0 && buffer.height > 0 {
            let max_rows: usize = src_h.min(buffer.height as usize);
            let max_cols: usize = src_w.min(buffer.width.max(0) as usize);
            let (x0, y0, x1, y1): (usize, usize, usize, usize) = if use_dirty {
                (
                    (bounds.left.max(0) as usize).min(max_cols),
                    (bounds.top.max(0) as usize).min(max_rows),
                    (bounds.right.max(0) as usize).min(max_cols),
                    (bounds.bottom.max(0) as usize).min(max_rows),
                )
            } else {
                (0, 0, max_cols, max_rows)
            };
            let dst_stride_bytes: usize = (buffer.stride as usize) * 4;
            let src_stride_bytes: usize = src_w * 4;
            let row_copy_bytes: usize = x1.saturating_sub(x0).saturating_mul(4);
            let x_off_bytes: usize = x0.saturating_mul(4);
            let dst_base: *mut u8 = buffer.bits.cast::<u8>();
            if x0 == 0
                && y0 == 0
                && x1 == src_w
                && src_stride_bytes == dst_stride_bytes
                && y1.saturating_mul(row_copy_bytes) <= src_bytes.len()
            {
                copy_nonoverlapping(
                    src_bytes.as_ptr(),
                    dst_base,
                    y1.saturating_mul(row_copy_bytes),
                );
            } else if row_copy_bytes > 0 {
                for row in y0..y1 {
                    let src_off: usize = row * src_stride_bytes + x_off_bytes;
                    let dst_off: usize = row * dst_stride_bytes + x_off_bytes;
                    if src_off + row_copy_bytes <= src_bytes.len() {
                        copy_nonoverlapping(
                            src_bytes.as_ptr().add(src_off),
                            dst_base.add(dst_off),
                            row_copy_bytes,
                        );
                    }
                }
            }
        }
        let _: i32 = ANativeWindow_unlockAndPost(native_window as *mut c_void);
    }
    Ok(())
}