Skip to main content

ohos_arkui_binding/common/
handle.rs

1//! Module common::handle wrappers and related types.
2
3use std::{os::raw::c_void, ptr::NonNull};
4
5#[cfg(feature = "napi")]
6use ohos_arkui_sys::OH_ArkUI_GetNodeContentFromNapiValue;
7use ohos_arkui_sys::{
8    ArkUI_NodeContentHandle, OH_ArkUI_NodeContent_AddNode, OH_ArkUI_NodeContent_InsertNode,
9    OH_ArkUI_NodeContent_RemoveNode,
10};
11
12#[cfg(feature = "napi")]
13use napi_ohos::bindgen_prelude::{check_status, FromNapiValue, TypeName, ValidateNapiValue};
14#[cfg(feature = "napi")]
15use napi_sys_ohos as sys;
16
17use crate::{check_arkui_status, ArkUINode, ArkUIResult};
18
19#[derive(Clone, Copy)]
20/// Opaque handle for ArkUI node content.
21///
22/// This wrapper owns no memory by itself. It provides safe method wrappers
23/// around `ArkUI_NodeContentHandle` operations.
24pub struct ArkUIHandle {
25    raw: NonNull<c_void>,
26}
27
28impl ArkUIHandle {
29    /// Construct from a raw ArkUI handle.
30    pub(crate) fn from_raw(raw: ArkUI_NodeContentHandle) -> Option<Self> {
31        NonNull::new(raw.cast()).map(|raw| Self { raw })
32    }
33
34    /// Return the underlying raw handle.
35    pub(crate) fn raw(&self) -> ArkUI_NodeContentHandle {
36        self.raw.as_ptr().cast()
37    }
38
39    pub(crate) fn add_node(&self, node: &ArkUINode) -> ArkUIResult<()> {
40        unsafe { check_arkui_status!(OH_ArkUI_NodeContent_AddNode(self.raw(), node.raw())) }
41    }
42
43    pub(crate) fn remove_node(&self, node: &ArkUINode) -> ArkUIResult<()> {
44        unsafe { check_arkui_status!(OH_ArkUI_NodeContent_RemoveNode(self.raw(), node.raw())) }
45    }
46
47    pub(crate) fn insert_node(&self, node: &ArkUINode, position: i32) -> ArkUIResult<()> {
48        unsafe {
49            check_arkui_status!(OH_ArkUI_NodeContent_InsertNode(
50                self.raw(),
51                node.raw(),
52                position
53            ))
54        }
55    }
56}
57
58#[cfg(feature = "napi")]
59impl TypeName for ArkUIHandle {
60    fn type_name() -> &'static str {
61        "ArkUIHandle"
62    }
63    fn value_type() -> napi_ohos::ValueType {
64        napi_ohos::ValueType::Object
65    }
66}
67
68#[cfg(feature = "napi")]
69impl ValidateNapiValue for ArkUIHandle {}
70
71#[cfg(feature = "napi")]
72impl FromNapiValue for ArkUIHandle {
73    unsafe fn from_napi_value(
74        env: sys::napi_env,
75        napi_val: sys::napi_value,
76    ) -> napi_ohos::Result<Self> {
77        let mut slot = std::ptr::null_mut();
78        unsafe {
79            check_status!(
80                OH_ArkUI_GetNodeContentFromNapiValue(env, napi_val, &mut slot),
81                "Get Node Content Slot failed."
82            )?
83        };
84        ArkUIHandle::from_raw(slot).ok_or_else(|| {
85            napi_ohos::Error::from_reason("OH_ArkUI_GetNodeContentFromNapiValue returned null")
86        })
87    }
88}