1use 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
15pub 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 #[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 pub const UITOUCH_PHASE_BEGAN: u8 = 0;
32 pub const UITOUCH_PHASE_MOVED: u8 = 1;
34 pub const UITOUCH_PHASE_STATIONARY: u8 = 2;
36 pub const UITOUCH_PHASE_ENDED: u8 = 3;
38 pub const UITOUCH_PHASE_CANCELLED: u8 = 4;
40
41 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 #[inline]
65 pub fn set_retina_scale(&mut self, scale: i16) {
66 unsafe { &mut *self.app }.set_dpi_scale(scale);
67 }
68
69 #[inline]
71 pub fn on_drawable_resized(&mut self, width: i16, height: i16) {
72 unsafe { &mut *self.app }.resize(width, height);
73 }
74
75 #[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 #[inline]
83 pub fn set_orientation(&mut self, orientation: DeviceOrientation) {
84 unsafe { &mut *self.app }.set_orientation(orientation);
85 }
86
87 #[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 #[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 #[inline]
103 pub fn on_interactive_pop_gesture(&mut self) -> bool {
104 unsafe { &mut *self.app }.handle_back()
105 }
106
107 #[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 #[inline]
115 pub fn rgba_slice(&self) -> &[u8] {
116 unsafe { &*self.app }.rgba_bytes()
117 }
118
119 #[inline]
121 pub fn dirty_rects(&self) -> &[CDirtyRect] {
122 unsafe { &*self.app }.dirty_rects()
123 }
124
125 #[inline]
127 pub fn embed_app(&self) -> &MobileEmbedApp {
128 unsafe { &*self.app }
129 }
130
131 #[inline]
133 pub fn embed_app_mut(&mut self) -> &mut MobileEmbedApp {
134 unsafe { &mut *self.app }
135 }
136
137 #[inline]
139 pub fn is_gpu_backend(&self) -> bool {
140 unsafe { &*self.app }.backend().is_gpu()
141 }
142
143 #[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
162pub 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
222pub 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
344pub 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
383pub 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#[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}