euv-core 0.46.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::*;

#[cfg(target_env = "ohos")]
#[link(name = "ace_ndk.z")]
unsafe extern "C" {
    /// Retrieves the UTF-8 `<XComponent>` ID string from `OH_NativeXComponent`.
    ///
    /// # Arguments
    ///
    /// - `*mut OhNativeXComponent` - Active XComponent handle.
    /// - `*mut u8` - Output UTF-8 buffer.
    /// - `*mut u64` - In-out buffer capacity / written length.
    ///
    /// # Returns
    ///
    /// - `i32` - `OH_NATIVEXCOMPONENT_RESULT_SUCCESS` (`0`) on success.
    pub fn OH_NativeXComponent_GetXComponentId(
        component: *mut OhNativeXComponent,
        id: *mut u8,
        size: *mut u64,
    ) -> i32;
    /// Queries physical surface `(width, height)` for an ArkUI XComponent window.
    ///
    /// # Arguments
    ///
    /// - `*mut OhNativeXComponent` - Active XComponent handle.
    /// - `*const OhNativeWindow` - Native surface window handle.
    /// - `*mut u64` - Output width in physical pixels.
    /// - `*mut u64` - Output height in physical pixels.
    ///
    /// # Returns
    ///
    /// - `i32` - `0` on success.
    pub fn OH_NativeXComponent_GetXComponentSize(
        component: *mut OhNativeXComponent,
        window: *const OhNativeWindow,
        width: *mut u64,
        height: *mut u64,
    ) -> i32;
    /// Registers surface lifecycle and touch callbacks on `OH_NativeXComponent`.
    ///
    /// # Arguments
    ///
    /// - `*mut OhNativeXComponent` - Active XComponent handle.
    /// - `*mut OhNativeXComponentCallback` - Static callback function table.
    ///
    /// # Returns
    ///
    /// - `i32` - `0` on success.
    pub fn OH_NativeXComponent_RegisterCallback(
        component: *mut OhNativeXComponent,
        callback: *mut OhNativeXComponentCallback,
    ) -> i32;
    /// Extracts the latest multi-touch payload from `OH_NativeXComponent`.
    ///
    /// # Arguments
    ///
    /// - `*mut OhNativeXComponent` - Active XComponent handle.
    /// - `*const OhNativeWindow` - Associated native window handle.
    /// - `*mut OhNativeXComponentTouchEvent` - Output touch event struct.
    ///
    /// # Returns
    ///
    /// - `i32` - `0` on success.
    pub fn OH_NativeXComponent_GetTouchEvent(
        component: *mut OhNativeXComponent,
        window: *const OhNativeWindow,
        touch_event: *mut OhNativeXComponentTouchEvent,
    ) -> i32;
}

#[cfg(target_env = "ohos")]
#[link(name = "native_window")]
unsafe extern "C" {
    /// Configures `OHNativeWindow` geometry or pixel format options (`SET_BUFFER_GEOMETRY`, `SET_FORMAT`).
    ///
    /// # Arguments
    ///
    /// - `*mut OhNativeWindow` - Active native window handle.
    /// - `i32` - `NativeWindowOperation` option code.
    /// - `...` - Variadic option value arguments.
    ///
    /// # Returns
    ///
    /// - `i32` - `0` on success.
    pub fn OH_NativeWindow_NativeWindowHandleOpt(
        window: *mut OhNativeWindow,
        code: i32,
        ...
    ) -> i32;
    /// Requests the next writable producer buffer from `OHNativeWindow`.
    ///
    /// # Arguments
    ///
    /// - `*mut OhNativeWindow` - Active native window handle.
    /// - `*mut *mut OhNativeWindowBuffer` - Output native buffer pointer.
    /// - `*mut i32` - Output acquire sync fence file descriptor.
    ///
    /// # Returns
    ///
    /// - `i32` - `0` on success.
    pub fn OH_NativeWindow_NativeWindowRequestBuffer(
        window: *mut OhNativeWindow,
        buffer: *mut *mut OhNativeWindowBuffer,
        fence_fd: *mut i32,
    ) -> i32;
    /// Flushes a rendered producer buffer to HarmonyOS RenderService with optional damage `region`.
    ///
    /// # Arguments
    ///
    /// - `*mut OhNativeWindow` - Active native window handle.
    /// - `*mut OhNativeWindowBuffer` - Producer buffer obtained via `RequestBuffer`.
    /// - `i32` - Release sync fence file descriptor (`-1` when CPU writes are complete).
    /// - `OhRegion` - Damaged pixel region descriptor.
    ///
    /// # Returns
    ///
    /// - `i32` - `0` on success.
    pub fn OH_NativeWindow_NativeWindowFlushBuffer(
        window: *mut OhNativeWindow,
        buffer: *mut OhNativeWindowBuffer,
        fence_fd: i32,
        region: OhRegion,
    ) -> i32;
    /// Aborts a previously requested `OHNativeWindowBuffer` without presenting it.
    ///
    /// # Arguments
    ///
    /// - `*mut OhNativeWindow` - Active native window handle.
    /// - `*mut OhNativeWindowBuffer` - Buffer to return cleanly to the queue.
    ///
    /// # Returns
    ///
    /// - `i32` - `0` on success.
    pub fn OH_NativeWindow_NativeWindowAbortBuffer(
        window: *mut OhNativeWindow,
        buffer: *mut OhNativeWindowBuffer,
    ) -> i32;
    /// Resolves the `OhBufferHandle` descriptor backing `buffer`.
    ///
    /// # Arguments
    ///
    /// - `*mut OhNativeWindowBuffer` - Requested native window buffer.
    ///
    /// # Returns
    ///
    /// - `*mut OhBufferHandle` - Buffer handle pointer or null.
    pub fn OH_NativeWindow_GetBufferHandleFromNative(
        buffer: *mut OhNativeWindowBuffer,
    ) -> *mut OhBufferHandle;
}

/// Converts a HarmonyOS `HarmonyAvoidArea` (in physical pixels) into logical `SafeAreaInsets` respecting device form factor.
///
/// # Arguments
///
/// - `HarmonyDeviceType` - Active HarmonyOS device form factor.
/// - `HarmonyAvoidArea` - Physical-pixel avoid area reported by `@ohos.window`.
/// - `f32` - Active display density (`vp -> px`).
/// - `u32` - Logical viewport width in `vp`.
/// - `u32` - Logical viewport height in `vp`.
/// - `bool` - Whether edge-to-edge immersive fullscreen mode is active.
///
/// # Returns
///
/// - `SafeAreaInsets` - Sanitized safe-area insets in logical `vp`.
#[must_use]
pub fn resolve_harmony_avoid_area(
    device_type: HarmonyDeviceType,
    avoid: HarmonyAvoidArea,
    density: f32,
    logical_width: u32,
    logical_height: u32,
    immersive_fullscreen: bool,
) -> SafeAreaInsets {
    let scale: f32 = if density.is_finite() && density >= 0.75 {
        density
    } else {
        1.0
    };
    let kb_vp: f32 = (avoid.get_keyboard_px() as f32) / scale;
    if immersive_fullscreen {
        return SafeAreaInsets::new(0.0, 0.0, kb_vp, 0.0);
    }
    let top_vp: f32 = (avoid.get_top_px() as f32) / scale;
    let right_vp: f32 = (avoid.get_right_px() as f32) / scale;
    let bottom_vp: f32 = ((avoid.get_bottom_px() as f32) / scale).max(kb_vp);
    let left_vp: f32 = (avoid.get_left_px() as f32) / scale;
    match device_type {
        HarmonyDeviceType::Watch => {
            let round_safe: SafeAreaInsets = compute_wearable_safe_area(
                WearableShape::Round,
                logical_width.max(1) as f32,
                logical_height.max(1) as f32,
                0.0,
            );
            SafeAreaInsets::new(
                top_vp.max(round_safe.get_top()),
                right_vp.max(round_safe.get_right()),
                bottom_vp.max(round_safe.get_bottom()),
                left_vp.max(round_safe.get_left()),
            )
        }
        HarmonyDeviceType::Tv => SafeAreaInsets::new(
            top_vp.max(HARMONY_TV_OVERSCAN_VP),
            right_vp.max(HARMONY_TV_OVERSCAN_VP),
            bottom_vp.max(HARMONY_TV_OVERSCAN_VP),
            left_vp.max(HARMONY_TV_OVERSCAN_VP),
        ),
        HarmonyDeviceType::Automotive => SafeAreaInsets::new(
            top_vp.max(HARMONY_CAR_DOCK_VP),
            right_vp,
            bottom_vp.max(HARMONY_CAR_DOCK_VP),
            left_vp,
        ),
        HarmonyDeviceType::Phone | HarmonyDeviceType::Foldable => SafeAreaInsets::new(
            top_vp.max(HARMONY_PHONE_SAFE_TOP_VP),
            right_vp,
            bottom_vp.max(HARMONY_PHONE_SAFE_BOTTOM_VP),
            left_vp,
        ),
        HarmonyDeviceType::Tablet | HarmonyDeviceType::Pc2In1 => {
            SafeAreaInsets::new(top_vp, right_vp, bottom_vp, left_vp)
        }
    }
}

/// Maps an OpenHarmony `OH_NativeXComponent` key code (`KEYCODE_*`) into a unified EUV `KeyCode`.
///
/// # Arguments
///
/// - `i32` - OpenHarmony NDK key code.
///
/// # Returns
///
/// - `KeyCode` - Normalized EUV key code.
#[must_use]
pub const fn harmony_keycode_to_euv(ohos_code: i32) -> KeyCode {
    match ohos_code {
        HARMONY_KEYCODE_BACK => KeyCode::Back,
        HARMONY_KEYCODE_DPAD_UP => KeyCode::ArrowUp,
        HARMONY_KEYCODE_DPAD_DOWN => KeyCode::ArrowDown,
        HARMONY_KEYCODE_DPAD_LEFT => KeyCode::ArrowLeft,
        HARMONY_KEYCODE_DPAD_RIGHT => KeyCode::ArrowRight,
        HARMONY_KEYCODE_DPAD_CENTER | HARMONY_KEYCODE_ENTER => KeyCode::Enter,
        HARMONY_KEYCODE_TAB => KeyCode::Tab,
        HARMONY_KEYCODE_SPACE => KeyCode::Space,
        HARMONY_KEYCODE_DEL => KeyCode::Backspace,
        HARMONY_KEYCODE_FORWARD_DEL => KeyCode::Delete,
        HARMONY_KEYCODE_ESCAPE => KeyCode::Escape,
        _ => KeyCode::Unknown,
    }
}

/// Maps an OpenHarmony `AbilityConstant.MemoryLevel` integer into a normalized `MemoryPressure`.
///
/// # Arguments
///
/// - `i32` - OpenHarmony memory level (`0`=MODERATE, `1`=LOW, `2`=CRITICAL).
///
/// # Returns
///
/// - `MemoryPressure` - Normalized memory pressure severity.
#[must_use]
pub const fn harmony_memory_level_to_pressure(level: i32) -> MemoryPressure {
    match level {
        HARMONY_MEMORY_CRITICAL => MemoryPressure::Critical,
        HARMONY_MEMORY_MODERATE | HARMONY_MEMORY_LOW => MemoryPressure::Warning,
        _ => MemoryPressure::Normal,
    }
}

/// Presents an RGBA8 `Framebuffer` directly to an OpenHarmony `OHNativeWindow*` when running on `target_env = "ohos"`.
///
/// # Arguments
///
/// - `usize` - Raw `OHNativeWindow*` pointer (`0` returns `Ok(())` for offscreen hosts).
/// - `&Framebuffer` - Rendered RGBA8 framebuffer.
/// - `&mut u32` - Cached surface width avoiding redundant `SET_BUFFER_GEOMETRY` calls.
/// - `&mut u32` - Cached surface height avoiding redundant `SET_BUFFER_GEOMETRY` calls.
///
/// # Returns
///
/// - `Result<(), PlatformError>` - Presentation status.
pub(crate) fn harmony_present_native_window(
    native_window: usize,
    framebuffer: &Framebuffer,
    cached_w: &mut u32,
    cached_h: &mut u32,
) -> Result<(), PlatformError> {
    if native_window == 0 {
        return Ok(());
    }
    #[cfg(target_env = "ohos")]
    {
        let fb_w: u32 = framebuffer.get_width();
        let fb_h: u32 = framebuffer.get_height();
        let win: *mut OhNativeWindow = native_window as *mut OhNativeWindow;
        // SAFETY: Invokes OpenHarmony `libnative_window.so` producer buffer lifecycle with verified pointers.
        unsafe {
            if *cached_w != fb_w || *cached_h != fb_h {
                let _: i32 = OH_NativeWindow_NativeWindowHandleOpt(
                    win,
                    HARMONY_NW_OPT_SET_BUFFER_GEOMETRY,
                    fb_w as i32,
                    fb_h as i32,
                );
                let _: i32 = OH_NativeWindow_NativeWindowHandleOpt(
                    win,
                    HARMONY_NW_OPT_SET_FORMAT,
                    HARMONY_PIXEL_FMT_RGBA_8888,
                );
                *cached_w = fb_w;
                *cached_h = fb_h;
            }
            let mut buffer: *mut OhNativeWindowBuffer = null_mut();
            let mut fence_fd: i32 = -1;
            let req_rc: i32 =
                OH_NativeWindow_NativeWindowRequestBuffer(win, &mut buffer, &mut fence_fd);
            if req_rc != 0 || buffer.is_null() {
                return Err(PlatformError::SurfaceError(
                    ERR_HARMONY_SURFACE_POST.to_string(),
                ));
            }
            let region: OhRegion = OhRegion {
                rects: null(),
                rect_number: 0,
            };
            let flush_rc: i32 = OH_NativeWindow_NativeWindowFlushBuffer(win, buffer, -1, region);
            if flush_rc != 0 {
                let _: i32 = OH_NativeWindow_NativeWindowAbortBuffer(win, buffer);
                return Err(PlatformError::SurfaceError(
                    ERR_HARMONY_SURFACE_POST.to_string(),
                ));
            }
        }
        Ok(())
    }
    #[cfg(not(target_env = "ohos"))]
    {
        let _: (&Framebuffer, &mut u32, &mut u32) = (framebuffer, cached_w, cached_h);
        Ok(())
    }
}