Skip to main content

velox_engine/platform/
ios.rs

1//! Apple iOS / iPadOS(`UIKit` / `CADisplayLink` / `CAMetalLayer` / Swift `xcframework`)专属平台宿主桥接层。
2//!
3//! 通过启用 `velox-engine/ios` 或 `velox-kit/ios` Feature 按需引入:
4//! - [`IosHostBridge<V>`]:泛型封装任意 [`View`] 的 iOS 宿主生命周期管理(灵动岛 `59pt` + Home Indicator `34pt` `safeAreaInsets`、`UIKeyboardWillChangeFrameNotification` 软键盘高度、`UITouchPhase` 触控、Retina `@2x`/`@3x` 缩放、左边缘右滑返回消费);
5//! - [`export_ios_app!`](crate::export_ios_app):一行宏为业务 [`View`] 自动生成完整 C ABI (`velox_ios_app_*`) 符号供 Xcode / Swift / Objective-C 调用。
6
7use std::boxed::Box;
8
9use crate::element::View;
10use crate::platform::mobile::{
11    CDirtyRect, DeviceOrientation, MobileEmbedApp, MobileOs, TouchPhase,
12};
13use crate::pod::{Handle, SafeAreaInsets};
14
15/// 泛型 iOS `UIKit` / `CADisplayLink` / `CAMetalLayer` 宿主桥接器(将任意业务 [`View`] 挂载至 [`MobileEmbedApp`])。
16pub struct IosHostBridge<V: View + 'static> {
17    app: *mut MobileEmbedApp,
18    pub root_handle: Handle<V>,
19}
20
21impl<V: View + Default + 'static> IosHostBridge<V> {
22    /// 使用 `V::default()` 创建指定逻辑点尺寸(Points)与灵动岛/Home Indicator 安全区的 iOS 应用实例。
23    #[inline]
24    pub fn new(width: i16, height: i16, safe_top: i16, safe_bottom: i16) -> Self {
25        Self::with_root(width, height, safe_top, safe_bottom, V::default())
26    }
27}
28
29impl<V: View + 'static> IosHostBridge<V> {
30    /// `UITouchPhase.began`。
31    pub const UITOUCH_PHASE_BEGAN: u8 = 0;
32    /// `UITouchPhase.moved`。
33    pub const UITOUCH_PHASE_MOVED: u8 = 1;
34    /// `UITouchPhase.stationary`。
35    pub const UITOUCH_PHASE_STATIONARY: u8 = 2;
36    /// `UITouchPhase.ended`。
37    pub const UITOUCH_PHASE_ENDED: u8 = 3;
38    /// `UITouchPhase.cancelled`。
39    pub const UITOUCH_PHASE_CANCELLED: u8 = 4;
40
41    /// 使用给定根视图 `root_view` 创建指定逻辑点尺寸(Points)与安全区的 iOS 应用实例。
42    pub fn with_root(
43        width: i16,
44        height: i16,
45        safe_top: i16,
46        safe_bottom: i16,
47        root_view: V,
48    ) -> Self {
49        let safe_area = SafeAreaInsets::new(safe_top, 0, safe_bottom, 0);
50        let mut embed = Box::new(MobileEmbedApp::new_for_os(
51            MobileOs::Ios,
52            width,
53            height,
54            safe_area,
55        ));
56        let root_handle = embed.engine.mount_root(root_view);
57        Self {
58            app: Box::into_raw(embed),
59            root_handle,
60        }
61    }
62
63    /// 设置 iOS Retina 屏幕像素缩放倍率(`@2x` / `@3x`,对应 `UIScreen.main.scale`)。
64    #[inline]
65    pub fn set_retina_scale(&mut self, scale: i16) {
66        unsafe { &mut *self.app }.set_dpi_scale(scale);
67    }
68
69    /// 响应 `UIView.layoutSubviews` 或屏幕旋转后的逻辑尺寸变化。
70    #[inline]
71    pub fn on_drawable_resized(&mut self, width: i16, height: i16) {
72        unsafe { &mut *self.app }.resize(width, height);
73    }
74
75    /// 同步 `UIView.safeAreaInsetsDidChange` 安全区内边距。
76    #[inline]
77    pub fn on_safe_area_insets_changed(&mut self, top: i16, right: i16, bottom: i16, left: i16) {
78        unsafe { &mut *self.app }.set_safe_area(SafeAreaInsets::new(top, right, bottom, left));
79    }
80
81    /// 切换 iOS 设备屏幕朝向并应用对应朝向的标准灵动岛/Home Indicator 安全区。
82    #[inline]
83    pub fn set_orientation(&mut self, orientation: DeviceOrientation) {
84        unsafe { &mut *self.app }.set_orientation(orientation);
85    }
86
87    /// 同步 `UIKeyboardWillChangeFrameNotification` 软键盘底部遮挡高度(Points)。
88    #[inline]
89    pub fn on_keyboard_frame_changed(&mut self, keyboard_height_pt: i16) {
90        unsafe { &mut *self.app }.set_keyboard_inset(keyboard_height_pt);
91    }
92
93    /// 分发 iOS `UITouch` 事件(自动将 `UITouchPhase` 映射为 [`TouchPhase`])。
94    #[inline]
95    pub fn on_ui_touch(&mut self, touch_id: u32, ui_touch_phase: u8, x: i16, y: i16) {
96        let phase = TouchPhase::from_ios_phase(ui_touch_phase);
97        unsafe { &mut *self.app }.push_touch(touch_id, phase, x, y);
98    }
99
100    /// 分发 iOS `UIScreenEdgePanGestureRecognizer` 左边缘返回事件:
101    /// 返回 `true` 表示应用内部已消费(关闭 Action Sheet 或 pop 二级视图)。
102    #[inline]
103    pub fn on_interactive_pop_gesture(&mut self) -> bool {
104        unsafe { &mut *self.app }.handle_back()
105    }
106
107    /// 响应 `CADisplayLink` 垂直同步回调推进一帧,返回本帧脏矩形个数。
108    #[inline]
109    pub fn on_display_link(&mut self, dt_ms: u16) -> usize {
110        unsafe { &mut *self.app }.step_frame(dt_ms)
111    }
112
113    /// 获取 `RGBA8888` 像素缓冲区的只读字节切片(可直接上传至 `MTLTexture` 或 `CGDataProvider`)。
114    #[inline]
115    pub fn rgba_slice(&self) -> &[u8] {
116        unsafe { &*self.app }.rgba_bytes()
117    }
118
119    /// 获取本帧脏矩形切片(供 `MTLTexture.replaceRegion` 局部纹理更新使用)。
120    #[inline]
121    pub fn dirty_rects(&self) -> &[CDirtyRect] {
122        unsafe { &*self.app }.dirty_rects()
123    }
124
125    /// 访问底层 [`MobileEmbedApp`] 只读引用。
126    #[inline]
127    pub fn embed_app(&self) -> &MobileEmbedApp {
128        unsafe { &*self.app }
129    }
130
131    /// 访问底层 [`MobileEmbedApp`] 可变引用。
132    #[inline]
133    pub fn embed_app_mut(&mut self) -> &mut MobileEmbedApp {
134        unsafe { &mut *self.app }
135    }
136
137    /// 查询当前 iOS 宿主实例是否启用了基于轻量 `wgpu` (Apple Metal) 2D SDF 的硬件 GPU 渲染后端。
138    #[inline]
139    pub fn is_gpu_backend(&self) -> bool {
140        unsafe { &*self.app }.backend().is_gpu()
141    }
142
143    /// 取出内部裸指针供 FFI 使用(调用后不再由 `Drop` 自动释放)。
144    #[inline]
145    pub fn into_raw(mut self) -> *mut MobileEmbedApp {
146        let ptr = self.app;
147        self.app = core::ptr::null_mut();
148        ptr
149    }
150}
151
152impl<V: View + 'static> Drop for IosHostBridge<V> {
153    fn drop(&mut self) {
154        if !self.app.is_null() {
155            unsafe {
156                let _ = Box::from_raw(self.app);
157            }
158        }
159    }
160}
161
162/// 框架内置的标准 iOS C 桥接头文件(`velox_ios.h`)模板。
163pub const IOS_VELOX_HEADER_H: &str = r#"#ifndef VELOX_IOS_H
164#define VELOX_IOS_H
165
166#include <stdbool.h>
167#include <stddef.h>
168#include <stdint.h>
169
170#ifdef __cplusplus
171extern "C" {
172#endif
173
174typedef struct MobileEmbedApp MobileEmbedApp;
175
176typedef struct {
177    int16_t x;
178    int16_t y;
179    int16_t w;
180    int16_t h;
181} CDirtyRect;
182
183MobileEmbedApp* velox_ios_app_create(
184    int16_t width,
185    int16_t height,
186    int16_t safe_top,
187    int16_t safe_bottom
188);
189
190void velox_ios_app_destroy(MobileEmbedApp* app);
191bool velox_ios_app_backend_is_gpu(const MobileEmbedApp* app);
192void velox_ios_app_resize(MobileEmbedApp* app, int16_t width, int16_t height);
193void velox_ios_app_set_dpi_scale(MobileEmbedApp* app, int16_t scale);
194void velox_ios_app_set_safe_area(
195    MobileEmbedApp* app,
196    int16_t top,
197    int16_t right,
198    int16_t bottom,
199    int16_t left
200);
201void velox_ios_app_set_keyboard_inset(MobileEmbedApp* app, int16_t height_pt);
202void velox_ios_app_push_touch(
203    MobileEmbedApp* app,
204    uint32_t touch_id,
205    uint8_t ui_touch_phase,
206    int16_t x,
207    int16_t y
208);
209bool velox_ios_app_handle_back(MobileEmbedApp* app);
210size_t velox_ios_app_step_frame(MobileEmbedApp* app, uint16_t dt_ms);
211const uint8_t* velox_ios_app_framebuffer_ptr(const MobileEmbedApp* app);
212const CDirtyRect* velox_ios_app_dirty_rects_ptr(const MobileEmbedApp* app);
213size_t velox_ios_app_dirty_rects_count(const MobileEmbedApp* app);
214
215#ifdef __cplusplus
216}
217#endif
218
219#endif /* VELOX_IOS_H */
220"#;
221
222/// 框架内置的标准 iOS Swift `UIView` + `CAMetalLayer` + 120Hz `CADisplayLink` 宿主视图(`VeloxMetalView.swift`)源码模板。
223pub const IOS_METAL_VIEW_SWIFT: &str = r#"import UIKit
224import QuartzCore
225
226/// iOS 原生宿主视图封装(由 `velox-engine::platform::ios` 自动生成,对接 `velox-kit` C ABI 接口)。
227final class VeloxMetalView: UIView {
228    private var appHandle: OpaquePointer?
229    private var displayLink: CADisplayLink?
230
231    override class var layerClass: AnyClass {
232        return CAMetalLayer.self
233    }
234
235    override init(frame: CGRect) {
236        super.init(frame: frame)
237        setupView()
238    }
239
240    required init?(coder: NSCoder) {
241        super.init(coder: coder)
242        setupView()
243    }
244
245    private func setupView() {
246        isMultipleTouchEnabled = true
247        contentScaleFactor = UIScreen.main.scale
248
249        let w = Int16(max(1, bounds.width))
250        let h = Int16(max(1, bounds.height))
251        appHandle = velox_ios_app_create(w, h, 59, 34)
252        if let handle = appHandle {
253            velox_ios_app_set_dpi_scale(handle, Int16(max(1, Int(UIScreen.main.scale.rounded()))))
254        }
255
256        let link = CADisplayLink(target: self, selector: #selector(onDisplayLink(_:)))
257        if #available(iOS 15.0, *) {
258            link.preferredFrameRateRange = CAFrameRateRange(minimum: 60, maximum: 120, __preferred: 120)
259        }
260        link.add(to: .main, forMode: .common)
261        displayLink = link
262
263        NotificationCenter.default.addObserver(
264            self,
265            selector: #selector(onKeyboardFrameChanged(_:)),
266            name: UIResponder.keyboardWillChangeFrameNotification,
267            object: nil
268        )
269    }
270
271    deinit {
272        displayLink?.invalidate()
273        if let handle = appHandle {
274            velox_ios_app_destroy(handle)
275            appHandle = nil
276        }
277    }
278
279    override func layoutSubviews() {
280        super.layoutSubviews()
281        guard let handle = appHandle else { return }
282        velox_ios_app_resize(handle, Int16(max(1, bounds.width)), Int16(max(1, bounds.height)))
283    }
284
285    override func safeAreaInsetsDidChange() {
286        super.safeAreaInsetsDidChange()
287        guard let handle = appHandle else { return }
288        let insets = safeAreaInsets
289        velox_ios_app_set_safe_area(
290            handle,
291            Int16(insets.top.rounded()),
292            Int16(insets.right.rounded()),
293            Int16(insets.bottom.rounded()),
294            Int16(insets.left.rounded())
295        )
296    }
297
298    @objc private func onKeyboardFrameChanged(_ notification: Notification) {
299        guard let handle = appHandle,
300              let endFrame = notification.userInfo?[UIResponder.keyboardFrameEndUserInfoKey] as? CGRect else {
301            return
302        }
303        let converted = convert(endFrame, from: window)
304        let overlap = max(0, bounds.maxY - converted.minY)
305        velox_ios_app_set_keyboard_inset(handle, Int16(overlap.rounded()))
306    }
307
308    @objc private func onDisplayLink(_ link: CADisplayLink) {
309        guard let handle = appHandle else { return }
310        let dtMs = UInt16(max(1, min(100, Int((link.targetTimestamp - link.timestamp) * 1000.0))))
311        let dirtyCount = velox_ios_app_step_frame(handle, dtMs)
312        if dirtyCount > 0 {
313            setNeedsDisplay()
314        }
315    }
316
317    private func forwardTouches(_ touches: Set<UITouch>, phase: UInt8) {
318        guard let handle = appHandle else { return }
319        for touch in touches {
320            let pt = touch.location(in: self)
321            let id = UInt32(truncatingIfNeeded: touch.hash)
322            velox_ios_app_push_touch(handle, id, phase, Int16(pt.x.rounded()), Int16(pt.y.rounded()))
323        }
324    }
325
326    override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
327        forwardTouches(touches, phase: 0)
328    }
329
330    override func touchesMoved(_ touches: Set<UITouch>, with event: UIEvent?) {
331        forwardTouches(touches, phase: 1)
332    }
333
334    override func touchesEnded(_ touches: Set<UITouch>, with event: UIEvent?) {
335        forwardTouches(touches, phase: 3)
336    }
337
338    override func touchesCancelled(_ touches: Set<UITouch>, with event: UIEvent?) {
339        forwardTouches(touches, phase: 4)
340    }
341}
342"#;
343
344/// 生成 iOS `Info.plist` 宿主配置清单。
345pub fn generate_ios_info_plist(bundle_id: &str, app_name: &str) -> std::string::String {
346    std::format!(
347        r#"<?xml version="1.0" encoding="UTF-8"?>
348<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
349<plist version="1.0">
350<dict>
351    <key>CFBundleDevelopmentRegion</key>
352    <string>en</string>
353    <key>CFBundleExecutable</key>
354    <string>VeloxIosApp</string>
355    <key>CFBundleIdentifier</key>
356    <string>{bundle_id}</string>
357    <key>CFBundleInfoDictionaryVersion</key>
358    <string>6.0</string>
359    <key>CFBundleName</key>
360    <string>{app_name}</string>
361    <key>CFBundlePackageType</key>
362    <string>APPL</string>
363    <key>CFBundleShortVersionString</key>
364    <string>0.1.0</string>
365    <key>CFBundleVersion</key>
366    <string>1</string>
367    <key>CADisableMinimumFrameDurationOnPhone</key>
368    <true/>
369    <key>UILaunchScreen</key>
370    <dict/>
371    <key>UISupportedInterfaceOrientations</key>
372    <array>
373        <string>UIInterfaceOrientationPortrait</string>
374        <string>UIInterfaceOrientationLandscapeLeft</string>
375        <string>UIInterfaceOrientationLandscapeRight</string>
376    </array>
377</dict>
378</plist>
379"#
380    )
381}
382
383/// 将框架内置的 iOS 宿主胶水文件(`include/velox_ios.h`、`VeloxMetalView.swift`、`Info.plist`)一键输出至目标目录。
384pub fn emit_ios_host_project(
385    out_dir: &std::path::Path,
386    bundle_id: &str,
387    app_name: &str,
388) -> std::io::Result<()> {
389    let inc_dir = out_dir.join("include");
390    std::fs::create_dir_all(&inc_dir)?;
391    std::fs::write(inc_dir.join("velox_ios.h"), IOS_VELOX_HEADER_H)?;
392    std::fs::write(out_dir.join("VeloxMetalView.swift"), IOS_METAL_VIEW_SWIFT)?;
393    std::fs::write(
394        out_dir.join("Info.plist"),
395        generate_ios_info_plist(bundle_id, app_name),
396    )?;
397    Ok(())
398}
399
400/// 为指定业务视图类型一键导出完整的 iOS C ABI (`velox_ios_app_*`) 符号(对接 `VeloxMetalView.swift` / `velox_ios.h`)。
401#[macro_export]
402macro_rules! export_ios_app {
403    ($app_ty:ty) => {
404        #[unsafe(no_mangle)]
405        pub extern "C" fn velox_ios_app_create(
406            width: i16,
407            height: i16,
408            safe_top: i16,
409            safe_bottom: i16,
410        ) -> *mut $crate::platform::mobile::MobileEmbedApp {
411            $crate::platform::ios::IosHostBridge::<$app_ty>::new(
412                width,
413                height,
414                safe_top,
415                safe_bottom,
416            )
417            .into_raw()
418        }
419
420        #[unsafe(no_mangle)]
421        pub unsafe extern "C" fn velox_ios_app_destroy(
422            app: *mut $crate::platform::mobile::MobileEmbedApp,
423        ) {
424            unsafe {
425                $crate::platform::mobile::ffi::destroy(app);
426            }
427        }
428
429        #[unsafe(no_mangle)]
430        pub unsafe extern "C" fn velox_ios_app_backend_is_gpu(
431            app: *const $crate::platform::mobile::MobileEmbedApp,
432        ) -> bool {
433            unsafe { $crate::platform::mobile::ffi::backend_is_gpu(app) }
434        }
435
436        #[unsafe(no_mangle)]
437        pub unsafe extern "C" fn velox_ios_app_resize(
438            app: *mut $crate::platform::mobile::MobileEmbedApp,
439            width: i16,
440            height: i16,
441        ) {
442            unsafe {
443                $crate::platform::mobile::ffi::resize(app, width, height);
444            }
445        }
446
447        #[unsafe(no_mangle)]
448        pub unsafe extern "C" fn velox_ios_app_set_dpi_scale(
449            app: *mut $crate::platform::mobile::MobileEmbedApp,
450            scale: i16,
451        ) {
452            unsafe {
453                $crate::platform::mobile::ffi::set_dpi_scale(app, scale);
454            }
455        }
456
457        #[unsafe(no_mangle)]
458        pub unsafe extern "C" fn velox_ios_app_set_safe_area(
459            app: *mut $crate::platform::mobile::MobileEmbedApp,
460            top: i16,
461            right: i16,
462            bottom: i16,
463            left: i16,
464        ) {
465            unsafe {
466                $crate::platform::mobile::ffi::set_safe_area(app, top, right, bottom, left);
467            }
468        }
469
470        #[unsafe(no_mangle)]
471        pub unsafe extern "C" fn velox_ios_app_set_keyboard_inset(
472            app: *mut $crate::platform::mobile::MobileEmbedApp,
473            height_pt: i16,
474        ) {
475            unsafe {
476                $crate::platform::mobile::ffi::set_keyboard_inset(app, height_pt);
477            }
478        }
479
480        #[unsafe(no_mangle)]
481        pub unsafe extern "C" fn velox_ios_app_push_touch(
482            app: *mut $crate::platform::mobile::MobileEmbedApp,
483            touch_id: u32,
484            ui_touch_phase: u8,
485            x: i16,
486            y: i16,
487        ) {
488            let phase = $crate::platform::mobile::TouchPhase::from_ios_phase(ui_touch_phase);
489            unsafe {
490                $crate::platform::mobile::ffi::push_touch(app, touch_id, phase, x, y);
491            }
492        }
493
494        #[unsafe(no_mangle)]
495        pub unsafe extern "C" fn velox_ios_app_handle_back(
496            app: *mut $crate::platform::mobile::MobileEmbedApp,
497        ) -> bool {
498            unsafe { $crate::platform::mobile::ffi::handle_back(app) }
499        }
500
501        #[unsafe(no_mangle)]
502        pub unsafe extern "C" fn velox_ios_app_step_frame(
503            app: *mut $crate::platform::mobile::MobileEmbedApp,
504            dt_ms: u16,
505        ) -> usize {
506            unsafe { $crate::platform::mobile::ffi::step_frame(app, dt_ms) }
507        }
508
509        #[unsafe(no_mangle)]
510        pub unsafe extern "C" fn velox_ios_app_framebuffer_ptr(
511            app: *const $crate::platform::mobile::MobileEmbedApp,
512        ) -> *const u8 {
513            unsafe { $crate::platform::mobile::ffi::framebuffer_ptr(app) }
514        }
515
516        #[unsafe(no_mangle)]
517        pub unsafe extern "C" fn velox_ios_app_dirty_rects_ptr(
518            app: *const $crate::platform::mobile::MobileEmbedApp,
519        ) -> *const $crate::platform::mobile::CDirtyRect {
520            unsafe { $crate::platform::mobile::ffi::dirty_rects_ptr(app) }
521        }
522
523        #[unsafe(no_mangle)]
524        pub unsafe extern "C" fn velox_ios_app_dirty_rects_count(
525            app: *const $crate::platform::mobile::MobileEmbedApp,
526        ) -> usize {
527            unsafe { $crate::platform::mobile::ffi::dirty_rects_count(app) }
528        }
529    };
530}