1use 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#[repr(u8)]
23#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
24pub enum MobileOs {
25 #[default]
27 Android = 0,
28 Ios = 1,
30 HarmonyOs = 2,
32}
33
34impl MobileOs {
35 #[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 #[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 #[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#[repr(u8)]
74#[derive(Copy, Clone, PartialEq, Eq, Debug)]
75pub enum TouchPhase {
76 Began = 0,
78 Moved = 1,
80 Ended = 2,
82 Cancelled = 3,
84}
85
86impl TouchPhase {
87 #[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 #[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 #[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#[repr(u8)]
123#[derive(Copy, Clone, PartialEq, Eq, Debug, Default)]
124pub enum DeviceOrientation {
125 #[default]
127 Portrait = 0,
128 LandscapeLeft = 1,
130 LandscapeRight = 2,
132 PortraitUpsideDown = 3,
134}
135
136#[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
146pub type MobilePlatform<const W: usize = 240, const H: usize = 360> =
148 TestingPlatform<W, H, Rgba8888>;
149
150pub 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 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 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 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 #[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 #[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 #[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 #[inline]
230 pub const fn with_os(mut self, os: MobileOs) -> Self {
231 self.os = os;
232 self
233 }
234
235 #[inline(always)]
237 pub const fn os(&self) -> MobileOs {
238 self.os
239 }
240
241 #[inline]
243 pub fn with_backend(mut self, backend: super::DesktopRenderBackend) -> Self {
244 self.backend = backend;
245 self
246 }
247
248 #[inline]
250 pub fn set_backend(&mut self, backend: super::DesktopRenderBackend) {
251 self.backend = backend;
252 }
253
254 #[inline(always)]
256 pub const fn backend(&self) -> super::DesktopRenderBackend {
257 self.backend
258 }
259
260 #[inline(always)]
262 pub const fn orientation(&self) -> DeviceOrientation {
263 self.orientation
264 }
265
266 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 #[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 #[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 #[cfg(feature = "gpu")]
303 pub fn detach_gpu_window(&mut self) {
304 self.gpu_window = None;
305 }
306
307 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 #[inline]
325 pub fn cpu_framebuffer_bytes(&self) -> usize {
326 self.framebuffer.capacity() * core::mem::size_of::<Rgba8888>()
327 }
328
329 #[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 #[cfg(feature = "gpu")]
352 #[inline]
353 pub fn has_active_gpu_window(&self) -> bool {
354 self.gpu_window.is_some()
355 }
356
357 #[cfg(not(feature = "gpu"))]
359 #[inline]
360 pub const fn has_active_gpu_window(&self) -> bool {
361 false
362 }
363
364 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 #[inline(always)]
385 pub const fn dpi_scale(&self) -> i16 {
386 self.dpi_scale
387 }
388
389 #[inline(always)]
391 pub const fn physical_width(&self) -> i16 {
392 self.width.saturating_mul(self.dpi_scale)
393 }
394
395 #[inline(always)]
397 pub const fn physical_height(&self) -> i16 {
398 self.height.saturating_mul(self.dpi_scale)
399 }
400
401 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 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 pub fn handle_back(&mut self) -> bool {
452 self.engine.dispatch_navigate_back()
453 }
454
455 pub fn set_safe_area(&mut self, safe_area: SafeAreaInsets) {
457 self.engine.set_safe_area(safe_area);
458 }
459
460 pub fn set_keyboard_inset(&mut self, height_px: i16) {
462 self.engine.set_keyboard_inset(height_px);
463 }
464
465 pub fn set_async_waker(&mut self, waker: impl Fn() + Send + Sync + 'static) {
468 self.engine.set_async_waker(waker);
469 }
470
471 #[inline]
473 pub fn poll_async_tasks(&mut self) -> bool {
474 self.engine.poll_async_tasks()
475 }
476
477 #[inline]
479 pub fn needs_redraw(&self) -> bool {
480 self.engine.needs_redraw()
481 }
482
483 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 ® 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 #[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 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 ® 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 ® 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 #[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 #[inline(always)]
568 pub fn dirty_rects(&self) -> &[CDirtyRect] {
569 self.dirty_rects.as_slice()
570 }
571}
572
573pub mod ffi {
575 use std::boxed::Box;
576
577 use super::{CDirtyRect, MobileEmbedApp, TouchPhase};
578 use crate::pod::SafeAreaInsets;
579
580 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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 #[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}