Skip to main content

velox_engine/platform/
harmony.rs

1//! 华为鸿蒙 HarmonyOS NEXT / OpenHarmony(`OH_NativeXComponent` / `OHNativeWindow` / ArkTS N-API)专属平台宿主桥接层。
2//!
3//! 通过启用 `velox-engine/harmony` 或 `velox-kit/harmony` Feature 按需引入:
4//! - [`HarmonyHostBridge<V>`]:泛型封装任意 [`View`] 的鸿蒙宿主生命周期管理(`AvoidAreaType.TYPE_SYSTEM` `38vp` + `TYPE_NAVIGATION_INDICATOR` `28vp`、`TYPE_KEYBOARD` 软键盘避让、`OH_NativeXComponent` 触控、`onBackPress(): boolean` 返回消费、折叠屏开合与横竖屏旋转);
5//! - [`step_and_blit_harmony_window`]:支持 `wgpu` (HarmonyOS Vulkan) 硬件 Swapchain 直通或 `OHNativeWindow` 缓冲区提交;
6//! - [`export_harmony_app!`](crate::export_harmony_app):一行宏为业务 [`View`] 自动生成完整 C ABI (`velox_harmony_app_*`) 符号供 ArkTS Stage 模型与 `XComponent` 调用。
7
8use 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
16/// 泛型鸿蒙 HarmonyOS NEXT `OH_NativeXComponent` / `OHNativeWindow` / ArkTS N-API 宿主桥接器。
17pub 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    /// 使用 `V::default()` 创建指定逻辑视口尺寸与鸿蒙系统避让区(`TYPE_SYSTEM` / `TYPE_NAVIGATION_INDICATOR`)的应用实例。
24    #[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    /// `OH_NATIVEXCOMPONENT_DOWN`。
32    pub const OH_TOUCH_DOWN: u8 = 0;
33    /// `OH_NATIVEXCOMPONENT_UP`。
34    pub const OH_TOUCH_UP: u8 = 1;
35    /// `OH_NATIVEXCOMPONENT_MOVE`。
36    pub const OH_TOUCH_MOVE: u8 = 2;
37    /// `OH_NATIVEXCOMPONENT_CANCEL`。
38    pub const OH_TOUCH_CANCEL: u8 = 3;
39
40    /// 使用给定根视图 `root_view` 创建指定逻辑视口尺寸与鸿蒙系统避让区的应用实例。
41    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    /// 设置鸿蒙屏幕像素密度缩放倍率(`display.getDefaultDisplaySync().densityPixels`)。
63    #[inline]
64    pub fn set_density_scale(&mut self, scale: i16) {
65        unsafe { &mut *self.app }.set_dpi_scale(scale);
66    }
67
68    /// 响应 `OH_NativeXComponent_Callback.OnSurfaceChanged` 或折叠屏展开/分屏尺寸变化。
69    #[inline]
70    pub fn on_surface_changed(&mut self, width: i16, height: i16) {
71        unsafe { &mut *self.app }.resize(width, height);
72    }
73
74    /// 同步鸿蒙 `window.on('avoidAreaChange')` (`TYPE_SYSTEM` / `TYPE_CUTOUT` / `TYPE_NAVIGATION_INDICATOR`) 避让区内边距。
75    #[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    /// 切换鸿蒙设备屏幕朝向并应用对应朝向的标准避让区域。
81    #[inline]
82    pub fn set_orientation(&mut self, orientation: DeviceOrientation) {
83        unsafe { &mut *self.app }.set_orientation(orientation);
84    }
85
86    /// 同步鸿蒙 `AvoidAreaType.TYPE_KEYBOARD` 软键盘底部像素高度。
87    #[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    /// 分发鸿蒙 `OH_NativeXComponent_GetTouchEvent` 触控事件。
93    #[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    /// 分发鸿蒙 ArkTS `@Entry onBackPress(): boolean` 页面级返回事件:
100    /// 返回 `true` 表示应用内部已消费(关闭元服务抽屉或回退二级页),返回 `false` 表示交由 `UIAbility` 处理。
101    #[inline]
102    pub fn on_back_press(&mut self) -> bool {
103        unsafe { &mut *self.app }.handle_back()
104    }
105
106    /// 响应 `OH_NativeXComponent_RegisterOnFrameCallback` 推进一帧,返回本帧脏矩形个数。
107    #[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    /// 获取 `RGBA8888` 像素缓冲区的只读字节切片(可直接写入 `OHNativeWindowBuffer`)。
113    #[inline]
114    pub fn rgba_slice(&self) -> &[u8] {
115        unsafe { &*self.app }.rgba_bytes()
116    }
117
118    /// 获取本帧脏矩形切片(供 `OH_NativeWindow_NativeWindowFlushBuffer` `Region` 局部刷新使用)。
119    #[inline]
120    pub fn dirty_rects(&self) -> &[CDirtyRect] {
121        unsafe { &*self.app }.dirty_rects()
122    }
123
124    /// 访问底层 [`MobileEmbedApp`] 只读引用。
125    #[inline]
126    pub fn embed_app(&self) -> &MobileEmbedApp {
127        unsafe { &*self.app }
128    }
129
130    /// 访问底层 [`MobileEmbedApp`] 可变引用。
131    #[inline]
132    pub fn embed_app_mut(&mut self) -> &mut MobileEmbedApp {
133        unsafe { &mut *self.app }
134    }
135
136    /// 查询当前鸿蒙宿主实例是否启用了基于轻量 `wgpu` (HarmonyOS Vulkan) 2D SDF 的硬件 GPU 渲染后端。
137    #[inline]
138    pub fn is_gpu_backend(&self) -> bool {
139        unsafe { &*self.app }.backend().is_gpu()
140    }
141
142    /// 取出内部裸指针供 FFI 使用(调用后不再由 `Drop` 自动释放)。
143    #[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
161/// 推进一帧 [`MobileEmbedApp`] 并将像素提交至鸿蒙 `OHNativeWindow`。
162///
163/// # Safety
164/// `app` 必须为有效的 [`MobileEmbedApp`] 指针或空指针。
165pub 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
184/// 框架内置的鸿蒙 HarmonyOS NEXT `UIAbility` (`EntryAbility.ets`) 源码模板。
185pub 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
197/// 框架内置的鸿蒙 HarmonyOS NEXT N-API TypeScript 声明文件(`index.d.ts`)模板。
198pub 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
209/// 框架内置的鸿蒙 HarmonyOS NEXT Stage 模型 `module.json5` 模板。
210pub 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
246/// 生成加载指定原生库名 `lib_name`(如 `"harmony_app"`)的鸿蒙 ArkTS `Index.ets` 页面源码。
247pub 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
337/// 将框架内置的鸿蒙 HarmonyOS NEXT 宿主胶水文件(`module.json5`、`Index.ets`、`EntryAbility.ets`、`index.d.ts`)一键输出至目标目录。
338pub 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/// 为指定业务视图类型一键导出完整的鸿蒙 HarmonyOS NEXT C ABI (`velox_harmony_app_*`) 符号。
362#[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}