Skip to main content

velox_engine/platform/
mobile.rs

1//! 移动端(Android `Surface` / `Choreographer` / JNI、iOS `UIKit` / `CADisplayLink` / `CAMetalLayer` 与鸿蒙 HarmonyOS NEXT `XComponent` / `OHNativeWindow` / N-API)跨平台适配层。
2//!
3//! 设计特点:
4//! - **三大移动生态统一内核(Android + iOS + HarmonyOS NEXT)**:通过 [`MobileOs`] 统一抽象平台安全区域预设(Android 状态栏/手势横条、iOS 灵动岛/Home Indicator、鸿蒙 `AvoidArea`)、原生触控事件映射与 GPU Swapchain API(Vulkan / Metal);
5//! - **无全局单例(Multi-Instance View)**:每个 [`MobileEmbedApp`] 实例独立维护状态、帧缓冲与脏矩形队列,
6//!   既可作为独立全屏移动应用运行,也可作为原生视图(Android `SurfaceView`、iOS `UIView`、鸿蒙 `XComponent`)在同一个宿主 App 的多个页面中并行嵌入;
7//! - **多点触控主手指追踪(Primary Touch Tracking)**:自动跟踪首个按下的手指 `touch_id`,过滤多指干扰,支持左边缘右滑返回手势;
8//! - **异形屏安全区域与软键盘避让(`SafeAreaInsets` & `KeyboardInset`)**:实时同步状态栏、灵动岛/刘海屏/挖孔屏、底部导航横条与软键盘高度;
9//! - **单路径渲染后端分发**:当挂载了 [`WgpuWindowRenderer`](crate::renderers::wgpu::WgpuWindowRenderer) 硬件 Swapchain 时直接零拷贝呈现至 GPU,否则按激活后端(`Wgpu` / `Software`)单路径渲染至 `Rgba8888` 缓冲区。
10
11use std::vec::Vec;
12
13use crate::arena::SmallVec;
14use crate::display::Rgba8888;
15use crate::engine::VeloxEngine;
16use crate::platform::testing::TestingPlatform;
17use crate::pod::InputEvent;
18use crate::pod::SafeAreaInsets;
19use crate::solver::Region;
20
21/// 移动端操作系统生态枚举(Android、iOS、鸿蒙 HarmonyOS NEXT / OpenHarmony)。
22#[repr(u8)]
23#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
24pub enum MobileOs {
25    /// Google Android(`ANativeWindow` / `Choreographer` / JNI / Vulkan)。
26    #[default]
27    Android = 0,
28    /// Apple iOS / iPadOS(`UIView` / `CADisplayLink` / `CAMetalLayer` / Metal)。
29    Ios = 1,
30    /// 华为鸿蒙 HarmonyOS NEXT / OpenHarmony(`OH_NativeXComponent` / `OHNativeWindow` / ArkTS N-API / Vulkan)。
31    HarmonyOs = 2,
32}
33
34impl MobileOs {
35    /// 获取当前移动操作系统的人类可读名称。
36    #[inline(always)]
37    pub const fn name(self) -> &'static str {
38        match self {
39            Self::Android => "Android",
40            Self::Ios => "iOS",
41            Self::HarmonyOs => "HarmonyOS NEXT",
42        }
43    }
44
45    /// 获取当前移动操作系统对应的原生低开销硬件加速图形 API 名称。
46    #[inline(always)]
47    pub const fn gpu_api_name(self) -> &'static str {
48        match self {
49            Self::Android | Self::HarmonyOs => "Vulkan",
50            Self::Ios => "Metal",
51        }
52    }
53
54    /// 获取当前移动操作系统在指定屏幕朝向下的标准安全区域预设。
55    #[inline(always)]
56    pub const fn default_safe_area(self, orientation: DeviceOrientation) -> SafeAreaInsets {
57        let is_portrait = matches!(
58            orientation,
59            DeviceOrientation::Portrait | DeviceOrientation::PortraitUpsideDown
60        );
61        match (self, is_portrait) {
62            (Self::Android, true) => SafeAreaInsets::android_portrait(),
63            (Self::Android, false) => SafeAreaInsets::android_landscape(),
64            (Self::Ios, true) => SafeAreaInsets::ios_portrait(),
65            (Self::Ios, false) => SafeAreaInsets::ios_landscape(),
66            (Self::HarmonyOs, true) => SafeAreaInsets::harmony_portrait(),
67            (Self::HarmonyOs, false) => SafeAreaInsets::harmony_landscape(),
68        }
69    }
70}
71
72/// 移动端触摸事件阶段(对齐 Android `MotionEvent.ACTION_*`、iOS `UITouchPhase` 与鸿蒙 `OH_NativeXComponent_TouchEventType`)。
73#[repr(u8)]
74#[derive(Copy, Clone, PartialEq, Eq, Debug)]
75pub enum TouchPhase {
76    /// 手指接触屏幕(`ACTION_DOWN` / `UITouchPhaseBegan` / `OH_NATIVEXCOMPONENT_DOWN`)。
77    Began = 0,
78    /// 手指在屏幕上移动(`ACTION_MOVE` / `UITouchPhaseMoved` / `OH_NATIVEXCOMPONENT_MOVE`)。
79    Moved = 1,
80    /// 手指离开屏幕(`ACTION_UP` / `UITouchPhaseEnded` / `OH_NATIVEXCOMPONENT_UP`)。
81    Ended = 2,
82    /// 触摸被系统手势或来电中断取消(`ACTION_CANCEL` / `UITouchPhaseCancelled` / `OH_NATIVEXCOMPONENT_CANCEL`)。
83    Cancelled = 3,
84}
85
86impl TouchPhase {
87    /// 将 Android `MotionEvent.getActionMasked()` (`0=DOWN, 1=UP, 2=MOVE, 3=CANCEL`) 映射为 [`TouchPhase`]。
88    #[inline(always)]
89    pub const fn from_android_action(action: u8) -> Self {
90        match action {
91            0 => Self::Began,
92            1 => Self::Ended,
93            2 => Self::Moved,
94            _ => Self::Cancelled,
95        }
96    }
97
98    /// 将 iOS `UITouchPhase` (`0=Began, 1=Moved, 2=Stationary, 3=Ended, 4=Cancelled`) 映射为 [`TouchPhase`]。
99    #[inline(always)]
100    pub const fn from_ios_phase(phase: u8) -> Self {
101        match phase {
102            0 => Self::Began,
103            1 | 2 => Self::Moved,
104            3 => Self::Ended,
105            _ => Self::Cancelled,
106        }
107    }
108
109    /// 将鸿蒙 `OH_NativeXComponent_TouchEventType` (`0=DOWN, 1=UP, 2=MOVE, 3=CANCEL`) 映射为 [`TouchPhase`]。
110    #[inline(always)]
111    pub const fn from_harmony_touch_type(touch_type: u8) -> Self {
112        match touch_type {
113            0 => Self::Began,
114            1 => Self::Ended,
115            2 => Self::Moved,
116            _ => Self::Cancelled,
117        }
118    }
119}
120
121/// 移动设备屏幕朝向枚举。
122#[repr(u8)]
123#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
124pub enum DeviceOrientation {
125    /// 竖屏正立(默认)。
126    #[default]
127    Portrait = 0,
128    /// 横屏(顶部在左)。
129    LandscapeLeft = 1,
130    /// 横屏(顶部在右)。
131    LandscapeRight = 2,
132    /// 竖屏倒置。
133    PortraitUpsideDown = 3,
134}
135
136/// 供跨语言桥接(Android JNI / iOS Swift / 鸿蒙 ArkTS N-API / WebAssembly)零拷贝读取的紧凑脏矩形结构。
137#[repr(C)]
138#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
139pub struct CDirtyRect {
140    pub x: i16,
141    pub y: i16,
142    pub w: i16,
143    pub h: i16,
144}
145
146/// `#![no_std]` 固定分辨率移动端无头测试平台别名(统一复用泛型 [`TestingPlatform`],消除重复结构体)。
147pub type MobilePlatform<const W: usize = 240, const H: usize = 360> =
148    TestingPlatform<W, H, Rgba8888>;
149
150/// 面向 Android (`SurfaceView` / `ANativeWindow` Vulkan / JNI)、iOS (`UIView` / `CAMetalLayer` / Swift `xcframework`)
151/// 与鸿蒙 HarmonyOS NEXT (`XComponent` / `OHNativeWindow` Vulkan / ArkTS N-API) 嵌入场景的动态分辨率宿主实例。
152pub struct MobileEmbedApp {
153    pub engine: VeloxEngine,
154    os: MobileOs,
155    width: i16,
156    height: i16,
157    dpi_scale: i16,
158    orientation: DeviceOrientation,
159    backend: super::DesktopRenderBackend,
160    framebuffer: Vec<Rgba8888>,
161    dirty_rects: Vec<CDirtyRect>,
162    active_touch_id: Option<u32>,
163    #[cfg(feature = "gpu")]
164    gpu_offscreen: Option<crate::renderers::wgpu::WgpuOffscreenRenderer>,
165    #[cfg(feature = "gpu")]
166    gpu_window: Option<crate::renderers::wgpu::WgpuWindowRenderer>,
167}
168
169impl MobileEmbedApp {
170    /// 创建一个可嵌入原生移动视图层级的独立引擎实例(默认采用 `Wgpu` 2D SDF 硬件加速后端)。
171    pub fn new(width: i16, height: i16, safe_area: SafeAreaInsets) -> Self {
172        Self::new_for_os(MobileOs::Android, width, height, safe_area)
173    }
174
175    /// 按指定移动端操作系统生态([`MobileOs`])与安全区域创建独立引擎实例。
176    pub fn new_for_os(os: MobileOs, width: i16, height: i16, safe_area: SafeAreaInsets) -> Self {
177        let w = width.max(1);
178        let h = height.max(1);
179        let mut engine = VeloxEngine::new(w, h);
180        engine.set_safe_area(safe_area);
181        Self {
182            engine,
183            os,
184            width: w,
185            height: h,
186            dpi_scale: 1,
187            orientation: DeviceOrientation::Portrait,
188            backend: super::DesktopRenderBackend::default_desktop(),
189            // 按需懒分配:走原生 GPU Swapchain 直出时保持 0 字节,避免无条件常驻整屏 CPU 帧缓冲。
190            framebuffer: Vec::new(),
191            dirty_rects: Vec::with_capacity(8),
192            active_touch_id: None,
193            #[cfg(feature = "gpu")]
194            gpu_offscreen: None,
195            #[cfg(feature = "gpu")]
196            gpu_window: None,
197        }
198    }
199
200    /// 创建搭载 Android 默认竖屏安全区(状态栏 `48px`、手势导航条 `34px`)的实例。
201    #[inline]
202    pub fn new_android(width: i16, height: i16) -> Self {
203        Self::new_for_os(
204            MobileOs::Android,
205            width,
206            height,
207            SafeAreaInsets::android_portrait(),
208        )
209    }
210
211    /// 创建搭载 iOS 默认竖屏安全区(灵动岛 `59pt`、Home Indicator `34pt`)的实例。
212    #[inline]
213    pub fn new_ios(width: i16, height: i16) -> Self {
214        Self::new_for_os(MobileOs::Ios, width, height, SafeAreaInsets::ios_portrait())
215    }
216
217    /// 创建搭载鸿蒙 HarmonyOS NEXT 默认竖屏避让区(状态栏 `38vp`、导航指示条 `28vp`)的实例。
218    #[inline]
219    pub fn new_harmony(width: i16, height: i16) -> Self {
220        Self::new_for_os(
221            MobileOs::HarmonyOs,
222            width,
223            height,
224            SafeAreaInsets::harmony_portrait(),
225        )
226    }
227
228    /// 配置当前实例所属的移动操作系统生态类型。
229    #[inline]
230    pub const fn with_os(mut self, os: MobileOs) -> Self {
231        self.os = os;
232        self
233    }
234
235    /// 获取当前实例所属的移动操作系统生态类型。
236    #[inline(always)]
237    pub const fn os(&self) -> MobileOs {
238        self.os
239    }
240
241    /// 配置移动端渲染后端类型(`Wgpu` 或 `Software`)。
242    #[inline]
243    pub fn with_backend(mut self, backend: super::DesktopRenderBackend) -> Self {
244        self.backend = backend;
245        self
246    }
247
248    /// 动态切换移动端渲染后端类型。
249    #[inline]
250    pub fn set_backend(&mut self, backend: super::DesktopRenderBackend) {
251        self.backend = backend;
252    }
253
254    /// 获取当前激活的移动端渲染后端类型。
255    #[inline(always)]
256    pub const fn backend(&self) -> super::DesktopRenderBackend {
257        self.backend
258    }
259
260    /// 获取当前设备屏幕朝向。
261    #[inline(always)]
262    pub const fn orientation(&self) -> DeviceOrientation {
263        self.orientation
264    }
265
266    /// 切换设备屏幕朝向并自动应用当前移动操作系统(Android / iOS / HarmonyOS)对应朝向的默认安全区域。
267    pub fn set_orientation(&mut self, orientation: DeviceOrientation) {
268        self.orientation = orientation;
269        let insets = self.os.default_safe_area(orientation);
270        self.engine.set_safe_area(insets);
271    }
272
273    /// 获取最近一帧离屏渲染编译生成的轻量级 2D SDF GPU 场景图元统计引用。
274    #[cfg(feature = "gpu")]
275    #[inline]
276    pub fn gpu_scene(&self) -> Option<&crate::renderers::wgpu::WgpuScene> {
277        self.gpu_offscreen.as_ref().map(|r| &r.scene)
278    }
279
280    /// 绑定原生移动端窗口句柄(Android `ANativeWindow` / iOS `UIView` `CAMetalLayer` / HarmonyOS `OHNativeWindow`),
281    /// 开启轻量级 `wgpu` (Vulkan / Metal) 2D SDF 120Hz 零拷贝 Swapchain 直通硬件加速渲染。
282    ///
283    /// 绑定成功后会自动释放不再需要的 CPU `framebuffer` 与离屏渲染器内存。
284    #[cfg(feature = "gpu")]
285    pub fn attach_gpu_window<T>(&mut self, window_handle: T) -> bool
286    where
287        T: Into<crate::renderers::wgpu::wgpu::SurfaceTarget<'static>> + Clone,
288    {
289        let pw = self.physical_width().max(1) as u32;
290        let ph = self.physical_height().max(1) as u32;
291        self.gpu_window = crate::renderers::wgpu::WgpuWindowRenderer::new(window_handle, pw, ph);
292        if self.gpu_window.is_some() {
293            self.framebuffer = Vec::new();
294            self.gpu_offscreen = None;
295            true
296        } else {
297            false
298        }
299    }
300
301    /// 解绑/挂起移动端 GPU Swapchain 表面。
302    #[cfg(feature = "gpu")]
303    pub fn detach_gpu_window(&mut self) {
304        self.gpu_window = None;
305    }
306
307    /// 后台化或收到系统内存压力回调(`onTrimMemory` / `didReceiveMemoryWarning`)时释放闲置 CPU 帧缓冲与 GPU 离屏显存。
308    pub fn trim_memory(&mut self) {
309        self.framebuffer = Vec::new();
310        self.engine.resize(self.width, self.height);
311        #[cfg(feature = "gpu")]
312        {
313            if let Some(off) = &mut self.gpu_offscreen {
314                off.trim_cpu_buffers();
315                off.trim_gpu_memory();
316            }
317            if let Some(win) = &mut self.gpu_window {
318                win.trim_gpu_memory();
319            }
320        }
321    }
322
323    /// 返回当前移动端实例 CPU 侧 `framebuffer` 占用的字节容量(原生 GPU Swapchain 路径下为 `0`)。
324    #[inline]
325    pub fn cpu_framebuffer_bytes(&self) -> usize {
326        self.framebuffer.capacity() * core::mem::size_of::<Rgba8888>()
327    }
328
329    /// 返回当前移动端实例在 CPU 侧持有的像素缓冲总字节容量(包含 `framebuffer` 与离屏渲染器内部缓冲)。
330    #[inline]
331    pub fn cpu_memory_bytes(&self) -> usize {
332        #[allow(unused_mut)]
333        let mut total = self.cpu_framebuffer_bytes();
334        #[cfg(feature = "gpu")]
335        if let Some(off) = &self.gpu_offscreen {
336            total = total.saturating_add(off.cpu_memory_bytes());
337        }
338        total
339    }
340
341    fn ensure_cpu_framebuffer(&mut self) {
342        let pw = self.physical_width().max(1) as usize;
343        let ph = self.physical_height().max(1) as usize;
344        let needed = pw.saturating_mul(ph);
345        if self.framebuffer.len() != needed {
346            self.framebuffer.resize(needed, Rgba8888(0));
347        }
348    }
349
350    /// 检查当前是否已挂载并激活硬件 GPU Swapchain 表面。
351    #[cfg(feature = "gpu")]
352    #[inline]
353    pub fn has_active_gpu_window(&self) -> bool {
354        self.gpu_window.is_some()
355    }
356
357    /// 检查当前是否已挂载并激活硬件 GPU Swapchain 表面。
358    #[cfg(not(feature = "gpu"))]
359    #[inline]
360    pub const fn has_active_gpu_window(&self) -> bool {
361        false
362    }
363
364    /// 设置移动端物理像素 HiDPI 缩放倍率。
365    pub fn set_dpi_scale(&mut self, scale: i16) {
366        let s = scale.max(1);
367        if s != self.dpi_scale {
368            self.dpi_scale = s;
369            self.engine.set_dpi_scale(s);
370            let pw = (self.width as usize) * (s as usize);
371            let ph = (self.height as usize) * (s as usize);
372            if !self.framebuffer.is_empty() && !self.has_active_gpu_window() {
373                self.framebuffer.resize(pw * ph, Rgba8888(0));
374            }
375            #[cfg(feature = "gpu")]
376            if let Some(gpu_win) = &mut self.gpu_window {
377                gpu_win.resize(pw.max(1) as u32, ph.max(1) as u32);
378            }
379            self.engine.resize(self.width, self.height);
380        }
381    }
382
383    /// 获取当前 HiDPI 缩放倍率。
384    #[inline(always)]
385    pub const fn dpi_scale(&self) -> i16 {
386        self.dpi_scale
387    }
388
389    /// 获取物理像素帧缓冲宽度(`logical_width * dpi_scale`)。
390    #[inline(always)]
391    pub const fn physical_width(&self) -> i16 {
392        self.width.saturating_mul(self.dpi_scale)
393    }
394
395    /// 获取物理像素帧缓冲高度(`logical_height * dpi_scale`)。
396    #[inline(always)]
397    pub const fn physical_height(&self) -> i16 {
398        self.height.saturating_mul(self.dpi_scale)
399    }
400
401    /// 调整视图逻辑宽高(如屏幕旋转或分屏窗口大小改变),保留全部组件状态。
402    pub fn resize(&mut self, width: i16, height: i16) {
403        let w = width.max(1);
404        let h = height.max(1);
405        if w != self.width || h != self.height {
406            self.width = w;
407            self.height = h;
408            let pw = (w as usize) * (self.dpi_scale as usize);
409            let ph = (h as usize) * (self.dpi_scale as usize);
410            if !self.framebuffer.is_empty() && !self.has_active_gpu_window() {
411                self.framebuffer.resize(pw * ph, Rgba8888(0));
412            }
413            #[cfg(feature = "gpu")]
414            if let Some(gpu_win) = &mut self.gpu_window {
415                gpu_win.resize(pw.max(1) as u32, ph.max(1) as u32);
416            }
417            self.engine.resize(w, h);
418        }
419    }
420
421    /// 注入触摸事件(自动锁定并跟踪主触控手指 `touch_id`)。
422    pub fn push_touch(&mut self, touch_id: u32, phase: TouchPhase, x: i16, y: i16) {
423        match phase {
424            TouchPhase::Began => {
425                if self.active_touch_id.is_none() {
426                    self.active_touch_id = Some(touch_id);
427                    self.engine.dispatch_touch_down(x, y);
428                }
429            }
430            TouchPhase::Moved => {
431                if self.active_touch_id == Some(touch_id) {
432                    self.engine.dispatch_event(InputEvent::PointerMove { x, y });
433                }
434            }
435            TouchPhase::Ended => {
436                if self.active_touch_id == Some(touch_id) {
437                    self.active_touch_id = None;
438                    self.engine.dispatch_event(InputEvent::PointerUp { x, y });
439                }
440            }
441            TouchPhase::Cancelled => {
442                if self.active_touch_id == Some(touch_id) {
443                    self.active_touch_id = None;
444                    self.engine.dispatch_event(InputEvent::PointerCancel);
445                }
446            }
447        }
448    }
449
450    /// 处理系统返回键/返回手势,返回是否被 Velox 视图消费。
451    pub fn handle_back(&mut self) -> bool {
452        self.engine.dispatch_navigate_back()
453    }
454
455    /// 动态更新异形屏安全区域内边距(状态栏、灵动岛/刘海、底部 Home Indicator)。
456    pub fn set_safe_area(&mut self, safe_area: SafeAreaInsets) {
457        self.engine.set_safe_area(safe_area);
458    }
459
460    /// 动态更新软键盘弹出高度(像素)。
461    pub fn set_keyboard_inset(&mut self, height_px: i16) {
462        self.engine.set_keyboard_inset(height_px);
463    }
464
465    /// 注入原生移动端事件循环唤醒器(例如 Android `ALooper_wake` / iOS `CFRunLoopWakeUp` / 鸿蒙 `OH_NativeVSync` 请求帧),
466    /// 实现后台异步任务完成与定时器到期时的零轮询精准唤醒。
467    pub fn set_async_waker(&mut self, waker: impl Fn() + Send + Sync + 'static) {
468        self.engine.set_async_waker(waker);
469    }
470
471    /// 在移动端 UI 主线程排空所有已就绪的前景异步协程与 `defer` 回调。
472    #[inline]
473    pub fn poll_async_tasks(&mut self) -> bool {
474        self.engine.poll_async_tasks()
475    }
476
477    /// 检查当前引擎是否存在待重绘脏视图、动画或已就绪异步任务(用于决定 `Choreographer` / `CADisplayLink` 是否休眠)。
478    #[inline]
479    pub fn needs_redraw(&self) -> bool {
480        self.engine.needs_redraw()
481    }
482
483    /// 推进一帧,按当前激活的 `backend` 单路径执行渲染(消除三重重复渲染),返回本帧重绘的脏矩形数量。
484    pub fn step_frame(&mut self, dt_ms: u16) -> usize {
485        self.dirty_rects.clear();
486        let mut regions: SmallVec<Region, 8> = SmallVec::new();
487        for &r in self.engine.step_frame_dt(dt_ms) {
488            regions.push(r);
489        }
490        if regions.is_empty() {
491            return 0;
492        }
493        let s = self.dpi_scale.max(1);
494        for &reg in regions.as_slice() {
495            self.dirty_rects.push(CDirtyRect {
496                x: reg.x.saturating_mul(s),
497                y: reg.y.saturating_mul(s),
498                w: reg.w.saturating_mul(s),
499                h: reg.h.saturating_mul(s),
500            });
501        }
502
503        // 1. 若已绑定原生 GPU 窗口 Swapchain,直接通过 WgpuWindowRenderer 上屏并返回,不再执行离屏/软件光栅
504        #[cfg(feature = "gpu")]
505        if self.backend == super::DesktopRenderBackend::Wgpu {
506            if let Some(gpu_win) = &mut self.gpu_window {
507                let viewport = self.engine.viewport_region();
508                let ops = self.engine.cached_draw_ops();
509                if gpu_win.render(ops, viewport, s) {
510                    return self.dirty_rects.len();
511                }
512            }
513        }
514
515        let _pw = self.physical_width().max(1) as usize;
516        let _ph = self.physical_height().max(1) as usize;
517        self.ensure_cpu_framebuffer();
518
519        // 2. 离屏 / ANativeWindow 缓冲区模式:按选定后端单路径直写 `self.framebuffer`,消除多余整屏 CPU 副本
520        match self.backend {
521            super::DesktopRenderBackend::Wgpu => {
522                #[cfg(feature = "gpu")]
523                {
524                    use crate::renderers::wgpu::WgpuOffscreenRenderer;
525                    let offscreen = self
526                        .gpu_offscreen
527                        .get_or_insert_with(|| WgpuOffscreenRenderer::new_lazy(_pw, _ph));
528                    let _ = offscreen.render_draw_ops_rgba8888_into(
529                        self.engine.cached_draw_ops(),
530                        self.engine.viewport_region(),
531                        s,
532                        regions.as_slice(),
533                        self.framebuffer.as_mut_slice(),
534                    );
535                }
536                #[cfg(not(feature = "gpu"))]
537                {
538                    for &reg in regions.as_slice() {
539                        self.engine
540                            .rasterize_region(reg, self.framebuffer.as_mut_slice());
541                    }
542                }
543            }
544            super::DesktopRenderBackend::Software => {
545                for &reg in regions.as_slice() {
546                    self.engine
547                        .rasterize_region(reg, self.framebuffer.as_mut_slice());
548                }
549            }
550        }
551
552        self.dirty_rects.len()
553    }
554
555    /// 获取 `RGBA8888` 像素缓冲区的只读字节切片。
556    #[inline(always)]
557    pub fn rgba_bytes(&self) -> &[u8] {
558        unsafe {
559            core::slice::from_raw_parts(
560                self.framebuffer.as_ptr() as *const u8,
561                self.framebuffer.len() * 4,
562            )
563        }
564    }
565
566    /// 获取本帧脏矩形切片。
567    #[inline(always)]
568    pub fn dirty_rects(&self) -> &[CDirtyRect] {
569        self.dirty_rects.as_slice()
570    }
571}
572
573/// 供 Android JNI、iOS Swift `xcframework` 与鸿蒙 ArkTS N-API 共享复用的底层 C ABI 辅助函数模块。
574pub mod ffi {
575    use std::boxed::Box;
576
577    use super::{CDirtyRect, MobileEmbedApp, TouchPhase};
578    use crate::pod::SafeAreaInsets;
579
580    /// 销毁通过 FFI 创建的 [`MobileEmbedApp`] 实例。
581    #[inline]
582    pub unsafe fn destroy(app: *mut MobileEmbedApp) {
583        if !app.is_null() {
584            unsafe {
585                drop(Box::from_raw(app));
586            }
587        }
588    }
589
590    /// 查询当前移动端实例是否启用了基于轻量 `wgpu` 2D SDF 的硬件 GPU 渲染后端。
591    #[inline]
592    pub unsafe fn backend_is_gpu(app: *const MobileEmbedApp) -> bool {
593        if let Some(app_ref) = unsafe { app.as_ref() } {
594            app_ref.backend().is_gpu()
595        } else {
596            false
597        }
598    }
599
600    /// 调整屏幕旋转或窗口分屏后的逻辑尺寸。
601    #[inline]
602    pub unsafe fn resize(app: *mut MobileEmbedApp, width: i16, height: i16) {
603        if let Some(app_ref) = unsafe { app.as_mut() } {
604            app_ref.resize(width, height);
605        }
606    }
607
608    /// 设置屏幕整数倍像素缩放因子(`@1x` / `@2x` / `@3x`)。
609    #[inline]
610    pub unsafe fn set_dpi_scale(app: *mut MobileEmbedApp, scale: i16) {
611        if let Some(app_ref) = unsafe { app.as_mut() } {
612            app_ref.set_dpi_scale(scale);
613        }
614    }
615
616    /// 更新移动端异形屏安全区域内边距。
617    #[inline]
618    pub unsafe fn set_safe_area(
619        app: *mut MobileEmbedApp,
620        top: i16,
621        right: i16,
622        bottom: i16,
623        left: i16,
624    ) {
625        if let Some(app_ref) = unsafe { app.as_mut() } {
626            app_ref.set_safe_area(SafeAreaInsets::new(top, right, bottom, left));
627        }
628    }
629
630    /// 更新移动端软键盘底部遮挡高度。
631    #[inline]
632    pub unsafe fn set_keyboard_inset(app: *mut MobileEmbedApp, height_px: i16) {
633        if let Some(app_ref) = unsafe { app.as_mut() } {
634            app_ref.set_keyboard_inset(height_px);
635        }
636    }
637
638    /// 注入已归一化的 [`TouchPhase`] 触控事件。
639    #[inline]
640    pub unsafe fn push_touch(
641        app: *mut MobileEmbedApp,
642        touch_id: u32,
643        phase: TouchPhase,
644        x: i16,
645        y: i16,
646    ) {
647        if let Some(app_ref) = unsafe { app.as_mut() } {
648            app_ref.push_touch(touch_id, phase, x, y);
649        }
650    }
651
652    /// 注入原始数值编码(`0=Began, 1=Moved, 2=Ended, 3=Cancelled`)的触控事件。
653    #[inline]
654    pub unsafe fn push_touch_raw(
655        app: *mut MobileEmbedApp,
656        touch_id: u32,
657        phase: u8,
658        x: i16,
659        y: i16,
660    ) {
661        let p = match phase {
662            0 => TouchPhase::Began,
663            1 => TouchPhase::Moved,
664            2 => TouchPhase::Ended,
665            _ => TouchPhase::Cancelled,
666        };
667        unsafe {
668            push_touch(app, touch_id, p, x, y);
669        }
670    }
671
672    /// 触发系统返回手势或返回按键,返回 `true` 表示已被应用内部消费。
673    #[inline]
674    pub unsafe fn handle_back(app: *mut MobileEmbedApp) -> bool {
675        if let Some(app_ref) = unsafe { app.as_mut() } {
676            app_ref.handle_back()
677        } else {
678            false
679        }
680    }
681
682    /// 在移动端 UI 主线程排空所有已就绪的前景异步协程与 `defer` 回调。
683    #[inline]
684    pub unsafe fn poll_async_tasks(app: *mut MobileEmbedApp) -> bool {
685        if let Some(app_ref) = unsafe { app.as_mut() } {
686            app_ref.poll_async_tasks()
687        } else {
688            false
689        }
690    }
691
692    /// 检查当前实例是否存在待重绘脏区、活跃动画或已就绪异步任务。
693    #[inline]
694    pub unsafe fn needs_redraw(app: *const MobileEmbedApp) -> bool {
695        if let Some(app_ref) = unsafe { app.as_ref() } {
696            app_ref.needs_redraw()
697        } else {
698            false
699        }
700    }
701
702    /// 推进一帧(`dt_ms` 毫秒),返回本帧脏矩形数量。
703    #[inline]
704    pub unsafe fn step_frame(app: *mut MobileEmbedApp, dt_ms: u16) -> usize {
705        if let Some(app_ref) = unsafe { app.as_mut() } {
706            app_ref.step_frame(dt_ms)
707        } else {
708            0
709        }
710    }
711
712    /// 获取 `RGBA8888` 像素缓冲区的只读首地址。
713    #[inline]
714    pub unsafe fn framebuffer_ptr(app: *const MobileEmbedApp) -> *const u8 {
715        if let Some(app_ref) = unsafe { app.as_ref() } {
716            app_ref.rgba_bytes().as_ptr()
717        } else {
718            core::ptr::null()
719        }
720    }
721
722    /// 获取本帧脏矩形数组的首地址。
723    #[inline]
724    pub unsafe fn dirty_rects_ptr(app: *const MobileEmbedApp) -> *const CDirtyRect {
725        if let Some(app_ref) = unsafe { app.as_ref() } {
726            app_ref.dirty_rects().as_ptr()
727        } else {
728            core::ptr::null()
729        }
730    }
731
732    /// 获取本帧脏矩形数组的元素个数。
733    #[inline]
734    pub unsafe fn dirty_rects_count(app: *const MobileEmbedApp) -> usize {
735        if let Some(app_ref) = unsafe { app.as_ref() } {
736            app_ref.dirty_rects().len()
737        } else {
738            0
739        }
740    }
741}