ohos_web_binding/js/
proxy.rs1use std::ffi::{c_void, CString};
2
3use crate::{ArkWebError, JsApiCallbackContext, ARK_WEB_CONTROLLER_API};
4use ohos_web_sys::{ArkWeb_ProxyMethod, ArkWeb_ProxyObject};
5
6use super::ark_web_proxy_method;
7
8pub struct WebProxy {
9 web_tag: String,
10 #[allow(dead_code)]
11 object_name: String,
12}
13
14impl WebProxy {
15 pub fn new(web_tag: String, object_name: String) -> Self {
16 Self {
17 web_tag,
18 object_name,
19 }
20 }
21
22 pub fn refresh(&self) -> Result<(), ArkWebError> {
26 ARK_WEB_CONTROLLER_API.refresh(self.web_tag.clone())?;
27
28 Ok(())
29 }
30}
31
32struct ArkWebProxyMethod {
33 js_name: CString, user_data: *mut c_void,
35}
36
37pub struct WebProxyBuilder {
51 web_tag: String,
52 object_name: String,
53
54 js_methods: Vec<ArkWebProxyMethod>,
55}
56
57impl WebProxyBuilder {
58 pub fn new<S: Into<String>>(web_tag: S, object_name: S) -> Self {
59 Self {
60 web_tag: web_tag.into(),
61 object_name: object_name.into(),
62 js_methods: Vec::new(),
63 }
64 }
65
66 pub fn add_method<S, F>(self, js_name: S, callback: F) -> WebProxyBuilder
74 where
75 S: Into<String>,
76 F: FnMut(String, Vec<String>),
77 {
78 let js_name =
79 CString::new(js_name.into()).expect("Failed to create CString for method name");
80
81 let cb: Box<dyn FnMut(String, Vec<String>)> = unsafe {
82 std::mem::transmute::<
83 Box<dyn FnMut(String, Vec<String>)>,
84 Box<dyn FnMut(String, Vec<String>) + 'static>,
85 >(Box::new(callback))
86 };
87
88 let ctx: Box<JsApiCallbackContext> = Box::new(JsApiCallbackContext { callback: cb });
89 let user_data = Box::into_raw(ctx) as *mut c_void;
90
91 let method = ArkWebProxyMethod { js_name, user_data };
92
93 let mut methods = self.js_methods;
94 methods.push(method);
95
96 WebProxyBuilder {
97 js_methods: methods,
98 ..self
99 }
100 }
101
102 pub fn build(self) -> Result<WebProxy, ArkWebError> {
103 let obj_name = CString::new(self.object_name.clone())
104 .expect("Failed to create CString for object name");
105
106 let method_list = self
107 .js_methods
108 .iter()
109 .map(|method| ArkWeb_ProxyMethod {
110 methodName: method.js_name.as_ptr().cast(),
111 callback: Some(ark_web_proxy_method),
112 userData: method.user_data,
113 })
114 .collect::<Vec<_>>();
115
116 let obj = ArkWeb_ProxyObject {
117 objName: obj_name.as_ptr().cast(),
118 methodList: method_list.as_ptr().cast(),
119 size: method_list.len(),
120 };
121
122 ARK_WEB_CONTROLLER_API
123 .register_javascript_proxy(self.web_tag.clone(), &obj as *const ArkWeb_ProxyObject)?;
124
125 Ok(WebProxy {
126 web_tag: self.web_tag,
127 object_name: self.object_name,
128 })
129 }
130}