1use std::boxed::Box;
9
10use crate::element::View;
11use crate::platform::mobile::{
12 CDirtyRect, DeviceOrientation, MobileEmbedApp, MobileOs, TouchPhase,
13};
14use crate::pod::{Handle, SafeAreaInsets};
15
16pub struct HarmonyHostBridge<V: View + 'static> {
18 app: *mut MobileEmbedApp,
19 pub root_handle: Handle<V>,
20}
21
22impl<V: View + Default + 'static> HarmonyHostBridge<V> {
23 #[inline]
25 pub fn new(width: i16, height: i16, avoid_top: i16, avoid_bottom: i16) -> Self {
26 Self::with_root(width, height, avoid_top, avoid_bottom, V::default())
27 }
28}
29
30impl<V: View + 'static> HarmonyHostBridge<V> {
31 pub const OH_TOUCH_DOWN: u8 = 0;
33 pub const OH_TOUCH_UP: u8 = 1;
35 pub const OH_TOUCH_MOVE: u8 = 2;
37 pub const OH_TOUCH_CANCEL: u8 = 3;
39
40 pub fn with_root(
42 width: i16,
43 height: i16,
44 avoid_top: i16,
45 avoid_bottom: i16,
46 root_view: V,
47 ) -> Self {
48 let safe_area = SafeAreaInsets::new(avoid_top, 0, avoid_bottom, 0);
49 let mut embed = Box::new(MobileEmbedApp::new_for_os(
50 MobileOs::HarmonyOs,
51 width,
52 height,
53 safe_area,
54 ));
55 let root_handle = embed.engine.mount_root(root_view);
56 Self {
57 app: Box::into_raw(embed),
58 root_handle,
59 }
60 }
61
62 #[inline]
64 pub fn set_density_scale(&mut self, scale: i16) {
65 unsafe { &mut *self.app }.set_dpi_scale(scale);
66 }
67
68 #[inline]
70 pub fn on_surface_changed(&mut self, width: i16, height: i16) {
71 unsafe { &mut *self.app }.resize(width, height);
72 }
73
74 #[inline]
76 pub fn on_avoid_area_changed(&mut self, top: i16, right: i16, bottom: i16, left: i16) {
77 unsafe { &mut *self.app }.set_safe_area(SafeAreaInsets::new(top, right, bottom, left));
78 }
79
80 #[inline]
82 pub fn set_orientation(&mut self, orientation: DeviceOrientation) {
83 unsafe { &mut *self.app }.set_orientation(orientation);
84 }
85
86 #[inline]
88 pub fn on_keyboard_avoid_area(&mut self, keyboard_bottom_px: i16) {
89 unsafe { &mut *self.app }.set_keyboard_inset(keyboard_bottom_px);
90 }
91
92 #[inline]
94 pub fn on_touch_event(&mut self, pointer_id: u32, oh_touch_type: u8, x: i16, y: i16) {
95 let phase = TouchPhase::from_harmony_touch_type(oh_touch_type);
96 unsafe { &mut *self.app }.push_touch(pointer_id, phase, x, y);
97 }
98
99 #[inline]
102 pub fn on_back_press(&mut self) -> bool {
103 unsafe { &mut *self.app }.handle_back()
104 }
105
106 #[inline]
108 pub fn on_frame_callback(&mut self, dt_ms: u16) -> usize {
109 unsafe { &mut *self.app }.step_frame(dt_ms)
110 }
111
112 #[inline]
114 pub fn rgba_slice(&self) -> &[u8] {
115 unsafe { &*self.app }.rgba_bytes()
116 }
117
118 #[inline]
120 pub fn dirty_rects(&self) -> &[CDirtyRect] {
121 unsafe { &*self.app }.dirty_rects()
122 }
123
124 #[inline]
126 pub fn embed_app(&self) -> &MobileEmbedApp {
127 unsafe { &*self.app }
128 }
129
130 #[inline]
132 pub fn embed_app_mut(&mut self) -> &mut MobileEmbedApp {
133 unsafe { &mut *self.app }
134 }
135
136 #[inline]
138 pub fn is_gpu_backend(&self) -> bool {
139 unsafe { &*self.app }.backend().is_gpu()
140 }
141
142 #[inline]
144 pub fn into_raw(mut self) -> *mut MobileEmbedApp {
145 let ptr = self.app;
146 self.app = core::ptr::null_mut();
147 ptr
148 }
149}
150
151impl<V: View + 'static> Drop for HarmonyHostBridge<V> {
152 fn drop(&mut self) {
153 if !self.app.is_null() {
154 unsafe {
155 let _ = Box::from_raw(self.app);
156 }
157 }
158 }
159}
160
161pub unsafe fn step_and_blit_harmony_window(
166 app: *mut MobileEmbedApp,
167 oh_native_window: *mut core::ffi::c_void,
168 dt_ms: u16,
169) -> i32 {
170 let Some(app_ref) = (unsafe { app.as_mut() }) else {
171 return 0;
172 };
173 let dirty = app_ref.step_frame(dt_ms.max(1));
174 if dirty == 0 || oh_native_window.is_null() {
175 return dirty as i32;
176 }
177 if app_ref.has_active_gpu_window() {
178 return dirty as i32;
179 }
180 let _ = oh_native_window;
181 dirty as i32
182}
183
184pub const HARMONY_ENTRY_ABILITY_ETS: &str = r#"import UIAbility from '@ohos.app.ability.UIAbility';
186import window from '@ohos.window';
187
188export default class EntryAbility extends UIAbility {
189 onWindowStageCreate(windowStage: window.WindowStage): void {
190 const mainWin = windowStage.getMainWindowSync();
191 mainWin.setWindowLayoutFullScreen(true);
192 windowStage.loadContent('pages/Index');
193 }
194}
195"#;
196
197pub const HARMONY_NAPI_INDEX_DTS: &str = r#"export const create: (width: number, height: number, avoidTop: number, avoidBottom: number) => number;
199export const destroy: (handle: number) => void;
200export const resize: (handle: number, width: number, height: number) => void;
201export const setDpiScale: (handle: number, scale: number) => void;
202export const setSafeArea: (handle: number, top: number, right: number, bottom: number, left: number) => void;
203export const setKeyboardInset: (handle: number, heightVp: number) => void;
204export const pushTouch: (handle: number, pointerId: number, touchType: number, x: number, y: number) => void;
205export const handleBack: (handle: number) => boolean;
206export const stepFrame: (handle: number, dtMs: number) => number;
207"#;
208
209pub const HARMONY_MODULE_JSON5: &str = r#"{
211 "module": {
212 "name": "entry",
213 "type": "entry",
214 "description": "Velox HarmonyOS NEXT Native XComponent Application",
215 "mainElement": "EntryAbility",
216 "deviceTypes": [
217 "phone",
218 "tablet",
219 "2in1"
220 ],
221 "deliveryWithInstall": true,
222 "installationFree": false,
223 "pages": "$profile:main_pages",
224 "abilities": [
225 {
226 "name": "EntryAbility",
227 "srcEntry": "./ets/entryability/EntryAbility.ets",
228 "description": "Velox HarmonyOS NEXT UIAbility",
229 "exported": true,
230 "skills": [
231 {
232 "entities": [
233 "entity.system.home"
234 ],
235 "actions": [
236 "action.system.home"
237 ]
238 }
239 ]
240 }
241 ]
242 }
243}
244"#;
245
246pub fn generate_harmony_index_ets(lib_name: &str) -> std::string::String {
248 std::format!(
249 r#"import window from '@ohos.window';
250import display from '@ohos.display';
251import veloxHarmony from 'lib{lib_name}.so';
252
253/**
254 * 鸿蒙 HarmonyOS NEXT ArkTS 主页面(由 `velox-engine::platform::harmony` 自动生成,挂载 `XComponent` Native 渲染表面)。
255 */
256@Entry
257@Component
258struct Index {{
259 private xComponentContext: Record<string, () => void> | undefined = undefined;
260 private nativeHandle: number = 0;
261
262 aboutToAppear(): void {{
263 window.getLastWindow(getContext(this)).then((win) => {{
264 win.setWindowLayoutFullScreen(true);
265 const sysArea = win.getWindowAvoidArea(window.AvoidAreaType.TYPE_SYSTEM);
266 const navArea = win.getWindowAvoidArea(window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR);
267 if (this.nativeHandle !== 0) {{
268 veloxHarmony.setSafeArea(
269 this.nativeHandle,
270 px2vp(sysArea.topRect.height),
271 0,
272 px2vp(navArea.bottomRect.height),
273 0
274 );
275 }}
276
277 win.on('avoidAreaChange', (data) => {{
278 if (this.nativeHandle === 0) {{
279 return;
280 }}
281 if (data.type === window.AvoidAreaType.TYPE_KEYBOARD) {{
282 veloxHarmony.setKeyboardInset(this.nativeHandle, px2vp(data.area.bottomRect.height));
283 }} else if (
284 data.type === window.AvoidAreaType.TYPE_SYSTEM ||
285 data.type === window.AvoidAreaType.TYPE_NAVIGATION_INDICATOR
286 ) {{
287 veloxHarmony.setSafeArea(
288 this.nativeHandle,
289 px2vp(data.area.topRect.height),
290 px2vp(data.area.rightRect.width),
291 px2vp(data.area.bottomRect.height),
292 px2vp(data.area.leftRect.width)
293 );
294 }}
295 }});
296 }});
297 }}
298
299 onBackPress(): boolean {{
300 if (this.nativeHandle !== 0) {{
301 return veloxHarmony.handleBack(this.nativeHandle);
302 }}
303 return false;
304 }}
305
306 build() {{
307 Stack() {{
308 XComponent({{
309 id: 'velox_harmony_xcomponent',
310 type: XComponentType.SURFACE,
311 libraryname: '{lib_name}'
312 }})
313 .onLoad((context) => {{
314 this.xComponentContext = context as Record<string, () => void>;
315 const disp = display.getDefaultDisplaySync();
316 const scale = Math.max(1, Math.round(disp.densityPixels));
317 this.nativeHandle = veloxHarmony.create(384, 832, 38, 28);
318 veloxHarmony.setDpiScale(this.nativeHandle, scale);
319 }})
320 .onDestroy(() => {{
321 if (this.nativeHandle !== 0) {{
322 veloxHarmony.destroy(this.nativeHandle);
323 this.nativeHandle = 0;
324 }}
325 }})
326 .width('100%')
327 .height('100%')
328 }}
329 .width('100%')
330 .height('100%')
331 }}
332}}
333"#
334 )
335}
336
337pub fn emit_harmony_host_project(
339 out_dir: &std::path::Path,
340 lib_name: &str,
341) -> std::io::Result<()> {
342 let pages_dir = out_dir.join("ets").join("pages");
343 let ability_dir = out_dir.join("ets").join("entryability");
344 let types_dir = out_dir.join("types").join(std::format!("lib{lib_name}"));
345 std::fs::create_dir_all(&pages_dir)?;
346 std::fs::create_dir_all(&ability_dir)?;
347 std::fs::create_dir_all(&types_dir)?;
348 std::fs::write(out_dir.join("module.json5"), HARMONY_MODULE_JSON5)?;
349 std::fs::write(
350 pages_dir.join("Index.ets"),
351 generate_harmony_index_ets(lib_name),
352 )?;
353 std::fs::write(
354 ability_dir.join("EntryAbility.ets"),
355 HARMONY_ENTRY_ABILITY_ETS,
356 )?;
357 std::fs::write(types_dir.join("index.d.ts"), HARMONY_NAPI_INDEX_DTS)?;
358 Ok(())
359}
360
361#[macro_export]
363macro_rules! export_harmony_app {
364 ($app_ty:ty) => {
365 #[unsafe(no_mangle)]
366 pub extern "C" fn velox_harmony_app_create(
367 width: i16,
368 height: i16,
369 avoid_top: i16,
370 avoid_bottom: i16,
371 ) -> *mut $crate::platform::mobile::MobileEmbedApp {
372 $crate::platform::harmony::HarmonyHostBridge::<$app_ty>::new(
373 width,
374 height,
375 avoid_top,
376 avoid_bottom,
377 )
378 .into_raw()
379 }
380
381 #[unsafe(no_mangle)]
382 pub unsafe extern "C" fn velox_harmony_app_destroy(
383 app: *mut $crate::platform::mobile::MobileEmbedApp,
384 ) {
385 unsafe {
386 $crate::platform::mobile::ffi::destroy(app);
387 }
388 }
389
390 #[unsafe(no_mangle)]
391 pub unsafe extern "C" fn velox_harmony_app_backend_is_gpu(
392 app: *const $crate::platform::mobile::MobileEmbedApp,
393 ) -> bool {
394 unsafe { $crate::platform::mobile::ffi::backend_is_gpu(app) }
395 }
396
397 #[unsafe(no_mangle)]
398 pub unsafe extern "C" fn velox_harmony_app_resize(
399 app: *mut $crate::platform::mobile::MobileEmbedApp,
400 width: i16,
401 height: i16,
402 ) {
403 unsafe {
404 $crate::platform::mobile::ffi::resize(app, width, height);
405 }
406 }
407
408 #[unsafe(no_mangle)]
409 pub unsafe extern "C" fn velox_harmony_app_set_dpi_scale(
410 app: *mut $crate::platform::mobile::MobileEmbedApp,
411 scale: i16,
412 ) {
413 unsafe {
414 $crate::platform::mobile::ffi::set_dpi_scale(app, scale);
415 }
416 }
417
418 #[unsafe(no_mangle)]
419 pub unsafe extern "C" fn velox_harmony_app_set_safe_area(
420 app: *mut $crate::platform::mobile::MobileEmbedApp,
421 top: i16,
422 right: i16,
423 bottom: i16,
424 left: i16,
425 ) {
426 unsafe {
427 $crate::platform::mobile::ffi::set_safe_area(app, top, right, bottom, left);
428 }
429 }
430
431 #[unsafe(no_mangle)]
432 pub unsafe extern "C" fn velox_harmony_app_set_keyboard_inset(
433 app: *mut $crate::platform::mobile::MobileEmbedApp,
434 height_px: i16,
435 ) {
436 unsafe {
437 $crate::platform::mobile::ffi::set_keyboard_inset(app, height_px);
438 }
439 }
440
441 #[unsafe(no_mangle)]
442 pub unsafe extern "C" fn velox_harmony_app_push_touch(
443 app: *mut $crate::platform::mobile::MobileEmbedApp,
444 pointer_id: u32,
445 oh_touch_type: u8,
446 x: i16,
447 y: i16,
448 ) {
449 let phase =
450 $crate::platform::mobile::TouchPhase::from_harmony_touch_type(oh_touch_type);
451 unsafe {
452 $crate::platform::mobile::ffi::push_touch(app, pointer_id, phase, x, y);
453 }
454 }
455
456 #[unsafe(no_mangle)]
457 pub unsafe extern "C" fn velox_harmony_app_handle_back(
458 app: *mut $crate::platform::mobile::MobileEmbedApp,
459 ) -> bool {
460 unsafe { $crate::platform::mobile::ffi::handle_back(app) }
461 }
462
463 #[unsafe(no_mangle)]
464 pub unsafe extern "C" fn velox_harmony_app_step_frame(
465 app: *mut $crate::platform::mobile::MobileEmbedApp,
466 dt_ms: u16,
467 ) -> usize {
468 unsafe { $crate::platform::mobile::ffi::step_frame(app, dt_ms) }
469 }
470
471 #[unsafe(no_mangle)]
472 pub unsafe extern "C" fn velox_harmony_app_framebuffer_ptr(
473 app: *const $crate::platform::mobile::MobileEmbedApp,
474 ) -> *const u8 {
475 unsafe { $crate::platform::mobile::ffi::framebuffer_ptr(app) }
476 }
477
478 #[unsafe(no_mangle)]
479 pub unsafe extern "C" fn velox_harmony_app_dirty_rects_ptr(
480 app: *const $crate::platform::mobile::MobileEmbedApp,
481 ) -> *const $crate::platform::mobile::CDirtyRect {
482 unsafe { $crate::platform::mobile::ffi::dirty_rects_ptr(app) }
483 }
484
485 #[unsafe(no_mangle)]
486 pub unsafe extern "C" fn velox_harmony_app_dirty_rects_count(
487 app: *const $crate::platform::mobile::MobileEmbedApp,
488 ) -> usize {
489 unsafe { $crate::platform::mobile::ffi::dirty_rects_count(app) }
490 }
491
492 #[unsafe(no_mangle)]
493 pub unsafe extern "C" fn velox_harmony_app_step_and_blit_window(
494 app: *mut $crate::platform::mobile::MobileEmbedApp,
495 oh_native_window: *mut core::ffi::c_void,
496 dt_ms: u16,
497 ) -> i32 {
498 unsafe {
499 $crate::platform::harmony::step_and_blit_harmony_window(
500 app,
501 oh_native_window,
502 dt_ms,
503 )
504 }
505 }
506 };
507}