1use 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#[repr(u8)]
28#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
29pub enum MobileOs {
30 #[default]
32 Android = 0,
33 Ios = 1,
35 HarmonyOs = 2,
37}
38
39impl MobileOs {
40 #[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 #[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 #[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#[repr(u8)]
79#[derive(Copy, Clone, PartialEq, Eq, Debug)]
80pub enum TouchPhase {
81 Began = 0,
83 Moved = 1,
85 Ended = 2,
87 Cancelled = 3,
89}
90
91impl TouchPhase {
92 #[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 #[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 #[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#[repr(u8)]
128#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
129pub enum DeviceOrientation {
130 #[default]
132 Portrait = 0,
133 LandscapeLeft = 1,
135 LandscapeRight = 2,
137 PortraitUpsideDown = 3,
139}
140
141#[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
151pub type MobilePlatform<const W: usize = 240, const H: usize = 360> =
153 TestingPlatform<W, H, Rgba8888>;
154
155pub 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 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 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 #[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 #[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 #[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 #[inline]
234 pub const fn with_os(mut self, os: MobileOs) -> Self {
235 self.os = os;
236 self
237 }
238
239 #[inline(always)]
241 pub const fn os(&self) -> MobileOs {
242 self.os
243 }
244
245 #[inline]
247 pub fn with_backend(mut self, backend: super::DesktopRenderBackend) -> Self {
248 self.backend = backend;
249 self
250 }
251
252 #[inline]
254 pub fn set_backend(&mut self, backend: super::DesktopRenderBackend) {
255 self.backend = backend;
256 }
257
258 #[inline(always)]
260 pub const fn backend(&self) -> super::DesktopRenderBackend {
261 self.backend
262 }
263
264 #[inline(always)]
266 pub const fn orientation(&self) -> DeviceOrientation {
267 self.orientation
268 }
269
270 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 #[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 #[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 #[cfg(feature = "gpu")]
299 pub fn detach_gpu_window(&mut self) {
300 self.gpu_window = None;
301 }
302
303 #[cfg(feature = "gpu")]
305 #[inline]
306 pub fn has_active_gpu_window(&self) -> bool {
307 self.gpu_window.is_some()
308 }
309
310 #[cfg(not(feature = "gpu"))]
312 #[inline]
313 pub const fn has_active_gpu_window(&self) -> bool {
314 false
315 }
316
317 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 #[inline(always)]
336 pub const fn dpi_scale(&self) -> i16 {
337 self.dpi_scale
338 }
339
340 #[inline(always)]
342 pub const fn physical_width(&self) -> i16 {
343 self.width.saturating_mul(self.dpi_scale)
344 }
345
346 #[inline(always)]
348 pub const fn physical_height(&self) -> i16 {
349 self.height.saturating_mul(self.dpi_scale)
350 }
351
352 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 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 pub fn handle_back(&mut self) -> bool {
401 self.engine.dispatch_navigate_back()
402 }
403
404 pub fn set_safe_area(&mut self, safe_area: SafeAreaInsets) {
406 self.engine.set_safe_area(safe_area);
407 }
408
409 pub fn set_keyboard_inset(&mut self, height_px: i16) {
411 self.engine.set_keyboard_inset(height_px);
412 }
413
414 pub fn set_async_waker(&mut self, waker: impl Fn() + Send + Sync + 'static) {
417 self.engine.set_async_waker(waker);
418 }
419
420 #[inline]
422 pub fn poll_async_tasks(&mut self) -> bool {
423 self.engine.poll_async_tasks()
424 }
425
426 #[inline]
428 pub fn needs_redraw(&self) -> bool {
429 self.engine.needs_redraw()
430 }
431
432 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 ® 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 #[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 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 ® 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 ® 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 #[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 #[inline(always)]
524 pub fn dirty_rects(&self) -> &[CDirtyRect] {
525 self.dirty_rects.as_slice()
526 }
527}
528
529pub mod ffi {
531 use std::boxed::Box;
532
533 use super::{CDirtyRect, MobileEmbedApp, TouchPhase};
534 use crate::pod::SafeAreaInsets;
535
536 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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}