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,
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    /// Register a custom protocol handler for the web view.
99    ///
100    /// # Arguments
101    ///
102    /// * `protocol` - The protocol to register the handler for.
103    /// * `handle` - The handler to register.
104    ///
105    /// ```ignore
106    /// let web = Web::new("web_tag".to_string());
107    ///
108    /// let handler = CustomProtocolHandler::new();
109    /// handler.on_request_start(|request, handle| {
110    ///     handle.receive_data("Hello, world!");
111    ///     true
112    /// });
113    /// handler.on_request_stop(|request| {
114    ///     println!("Request stopped: {:?}", request);
115    /// });
116    ///
117    /// web.custom_protocol("custom", handler).unwrap();
118    /// ```
119    pub fn custom_protocol<S>(
120        &self,
121        protocol: S,
122        handle: CustomProtocolHandler,
123    ) -> Result<bool, ArkWebError>
124    where
125        S: Into<String>,
126    {
127        let protocol: String = protocol.into();
128
129        let tag = CString::new(self.web_tag.clone()).unwrap();
130        let protocol = CString::new(protocol).unwrap();
131
132        let ret = unsafe {
133            OH_ArkWeb_SetSchemeHandler(protocol.as_ptr().cast(), tag.as_ptr().cast(), handle.raw())
134        };
135        let _ = Box::leak(Box::new(handle));
136        Ok(ret)
137    }
138}