Skip to main content

ohos_web_binding/
web.rs

1use std::ffi::{c_void, CString};
2
3use ohos_web_sys::OH_ArkWeb_SetSchemeHandler;
4
5use crate::{
6    callback::{OnControllerAttachContext, OnDestroyContext, OnPageBeginContext, OnPageEndContext},
7    error::ArkWebError,
8    CustomProtocolHandler, ARK_WEB_COMPONENT_API, ARK_WEB_CONTROLLER_API,
9};
10
11#[derive(Debug, Clone)]
12pub struct Web {
13    web_tag: String,
14}
15
16impl Web {
17    pub fn new(web_tag: String) -> Self {
18        Self { web_tag }
19    }
20
21    pub fn on_controller_attach<F>(&self, mut callback: F) -> Result<(), ArkWebError>
22    where
23        F: FnMut(),
24    {
25        let cb = unsafe {
26            std::mem::transmute::<Box<dyn FnMut()>, Box<dyn FnMut() + 'static>>(Box::new(
27                move || {
28                    callback();
29                },
30            ))
31        };
32
33        let ctx: Box<OnControllerAttachContext> =
34            Box::new(OnControllerAttachContext { callback: cb });
35        let user_data = Box::into_raw(ctx) as *mut c_void;
36
37        ARK_WEB_COMPONENT_API.on_controller_attached(self.web_tag.clone(), user_data)?;
38        Ok(())
39    }
40
41    pub fn on_page_begin<F>(&self, mut callback: F) -> Result<(), ArkWebError>
42    where
43        F: FnMut(),
44    {
45        let cb = unsafe {
46            std::mem::transmute::<Box<dyn FnMut()>, Box<dyn FnMut() + 'static>>(Box::new(
47                move || {
48                    callback();
49                },
50            ))
51        };
52
53        let ctx: Box<OnPageBeginContext> = Box::new(OnPageBeginContext { callback: cb });
54        let user_data = Box::into_raw(ctx) as *mut c_void;
55
56        ARK_WEB_COMPONENT_API.on_page_begin(self.web_tag.clone(), user_data)?;
57        Ok(())
58    }
59
60    pub fn on_page_end<F>(&self, mut callback: F) -> Result<(), ArkWebError>
61    where
62        F: FnMut(),
63    {
64        let cb = unsafe {
65            std::mem::transmute::<Box<dyn FnMut()>, Box<dyn FnMut() + 'static>>(Box::new(
66                move || {
67                    callback();
68                },
69            ))
70        };
71
72        let ctx: Box<OnPageEndContext> = Box::new(OnPageEndContext { callback: cb });
73        let user_data = Box::into_raw(ctx) as *mut c_void;
74
75        ARK_WEB_COMPONENT_API.on_page_end(self.web_tag.clone(), user_data)?;
76        Ok(())
77    }
78
79    pub fn on_destroy<F>(&self, mut callback: F) -> Result<(), ArkWebError>
80    where
81        F: FnMut(),
82    {
83        let cb = unsafe {
84            std::mem::transmute::<Box<dyn FnMut()>, Box<dyn FnMut() + 'static>>(Box::new(
85                move || {
86                    callback();
87                },
88            ))
89        };
90
91        let ctx: Box<OnDestroyContext> = Box::new(OnDestroyContext { callback: cb });
92        let user_data = Box::into_raw(ctx) as *mut c_void;
93
94        ARK_WEB_COMPONENT_API.on_destroy(self.web_tag.clone(), user_data)?;
95        Ok(())
96    }
97
98    /// Evaluates `js_code` in the page currently displayed by this `Web` component
99    /// and invokes `callback` once with the result bytes (`None` if ArkWeb supplies
100    /// no bridge payload). ArkWeb may invoke `callback` on an internal worker thread.
101    pub fn run_javascript<F>(&self, js_code: &str, callback: F) -> Result<(), ArkWebError>
102    where
103        F: FnOnce(Option<&[u8]>) + Send + 'static,
104    {
105        ARK_WEB_CONTROLLER_API.run_javascript(&self.web_tag, js_code, callback)
106    }
107
108    /// Register a custom protocol handler for the web view.
109    ///
110    /// # Arguments
111    ///
112    /// * `protocol` - The protocol to register the handler for.
113    /// * `handle` - The handler to register.
114    ///
115    /// ```ignore
116    /// let web = Web::new("web_tag".to_string());
117    ///
118    /// let handler = CustomProtocolHandler::new();
119    /// handler.on_request_start(|request, handle| {
120    ///     handle.receive_data("Hello, world!");
121    ///     true
122    /// });
123    /// handler.on_request_stop(|request| {
124    ///     println!("Request stopped: {:?}", request);
125    /// });
126    ///
127    /// web.custom_protocol("custom", handler).unwrap();
128    /// ```
129    pub fn custom_protocol<S>(
130        &self,
131        protocol: S,
132        handle: CustomProtocolHandler,
133    ) -> Result<bool, ArkWebError>
134    where
135        S: Into<String>,
136    {
137        let protocol: String = protocol.into();
138
139        let tag = CString::new(self.web_tag.clone()).unwrap();
140        let protocol = CString::new(protocol).unwrap();
141
142        let ret = unsafe {
143            OH_ArkWeb_SetSchemeHandler(protocol.as_ptr().cast(), tag.as_ptr().cast(), handle.raw())
144        };
145        let _ = Box::leak(Box::new(handle));
146        Ok(ret)
147    }
148}