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