1use super::*;
2
3#[must_use]
14pub fn default_showcase_render_config(mode: RenderMode, prefer_direct_gpu: bool) -> RenderConfig {
15 match mode {
16 RenderMode::Software => RenderConfig::software(),
17 RenderMode::Hardware => {
18 if prefer_direct_gpu {
19 RenderConfig::hardware_direct()
20 } else {
21 RenderConfig::hardware()
22 }
23 }
24 RenderMode::Hybrid => RenderConfig::hybrid(),
25 RenderMode::Auto => RenderConfig::default(),
26 }
27}
28
29pub fn create_showcase_app_default(headless: bool) -> Result<(App, ShowcaseState), PlatformError> {
39 create_showcase_app(headless, RenderMode::Auto)
40}
41
42fn host_platform_matrix_index(platform: PlatformKind) -> usize {
52 match platform {
53 PlatformKind::Ios => 0,
54 PlatformKind::IpadOs => 1,
55 PlatformKind::Android | PlatformKind::HarmonyOs | PlatformKind::Wearable => 2,
56 PlatformKind::MacOs => 3,
57 PlatformKind::Windows => 4,
58 PlatformKind::Linux | PlatformKind::Terminal | PlatformKind::TerminalCli => 5,
59 PlatformKind::Web
60 | PlatformKind::MiniApp
61 | PlatformKind::QuickApp
62 | PlatformKind::Headless => 6,
63 }
64}
65
66pub fn create_showcase_app_with_viewport(
80 headless: bool,
81 mode: RenderMode,
82 logical_width: u32,
83 logical_height: u32,
84 initial_scale: f32,
85) -> Result<(App, ShowcaseState), PlatformError> {
86 EuvOverlayStack::clear();
87 reset_fullscreen_state();
88 clear_provided_theme();
89 let init_w: u32 = logical_width.max(320);
90 let init_h: u32 = logical_height.max(320);
91 let init_scale: f32 = if initial_scale.is_finite() && initial_scale > 0.0 {
92 initial_scale.clamp(0.5, 6.0)
93 } else {
94 1.0
95 };
96 let prefer_direct_gpu: bool = headless || cfg!(target_os = "macos");
97 let render_cfg: RenderConfig = default_showcase_render_config(mode, prefer_direct_gpu);
98 let mut window_cfg: WindowConfig = WindowConfig::default();
99 window_cfg
100 .set_title(SHOWCASE_WINDOW_TITLE.to_string())
101 .set_size(init_w, init_h)
102 .set_render(render_cfg)
103 .set_icon(Some(euv_brand_logo_image()));
104 let mut app_cfg: AppConfig = AppConfig::default();
105 app_cfg.set_window(window_cfg);
106 let mut app: App = if headless {
107 App::headless(app_cfg)?
108 } else {
109 App::new(app_cfg)?
110 };
111 if (init_scale - 1.0).abs() > 0.005 {
112 let phys_w: u32 = ((init_w as f64) * (init_scale as f64)).round().max(1.0) as u32;
113 let phys_h: u32 = ((init_h as f64) * (init_scale as f64)).round().max(1.0) as u32;
114 app.set_exact_physical_viewport(phys_w, phys_h, init_scale);
115 }
116 let enable_bg_workers: bool = !headless && cfg!(not(target_arch = "wasm32"));
117 if enable_bg_workers {
118 precompile_shaders_async(default_native_gpu_backend());
119 }
120 let state: ShowcaseState =
121 ShowcaseState::new_with_hub(app.get_dynamic_hub().clone(), enable_bg_workers);
122 state.set_default_host_platform_idx(host_platform_matrix_index(app.platform_kind()));
123 app.attach_game_host(state.get_game_host().clone());
124 app.attach_game_host(state.get_game3d_host().clone());
125 app.attach_game_host(state.get_water_host().clone());
126 let mount_state: ShowcaseState = state.clone();
127 let _: NodeId = app.mount(move || mount_showcase_root(&mount_state));
128 state.sync_adaptive_from_app(&mut app);
129 if !headless {
130 bootstrap_showcase_hot_updates(state.get_dynamic_hub());
131 }
132 Ok((app, state))
133}
134
135pub fn create_showcase_app(
146 headless: bool,
147 mode: RenderMode,
148) -> Result<(App, ShowcaseState), PlatformError> {
149 create_showcase_app_with_viewport(
150 headless,
151 mode,
152 SHOWCASE_WINDOW_WIDTH,
153 SHOWCASE_WINDOW_HEIGHT,
154 1.0,
155 )
156}
157
158pub fn create_showcase_app_for_platform(
169 platform: PlatformKind,
170 mode: RenderMode,
171) -> Result<(App, ShowcaseState), PlatformError> {
172 create_showcase_app_for_platform_with_viewport(
173 platform,
174 mode,
175 SHOWCASE_WINDOW_WIDTH,
176 SHOWCASE_WINDOW_HEIGHT,
177 1.0,
178 SafeAreaInsets::default(),
179 )
180}
181
182pub fn create_showcase_app_for_platform_with_viewport(
199 platform: PlatformKind,
200 mode: RenderMode,
201 logical_width: u32,
202 logical_height: u32,
203 initial_scale: f32,
204 safe_area: SafeAreaInsets,
205) -> Result<(App, ShowcaseState), PlatformError> {
206 EuvOverlayStack::clear();
207 reset_fullscreen_state();
208 clear_provided_theme();
209 let init_w: u32 = logical_width.max(HOST_MIN_VIEWPORT_DIM);
210 let init_h: u32 = logical_height.max(HOST_MIN_VIEWPORT_DIM);
211 let init_scale: f32 = if initial_scale.is_finite() && initial_scale > 0.0 {
212 initial_scale.clamp(0.5, 6.0)
213 } else {
214 1.0
215 };
216 let render_cfg: RenderConfig = default_showcase_render_config(mode, false);
217 let mut window_cfg: WindowConfig = WindowConfig::default();
218 window_cfg
219 .set_title(SHOWCASE_WINDOW_TITLE.to_string())
220 .set_size(init_w, init_h)
221 .set_render(render_cfg)
222 .set_icon(Some(euv_brand_logo_image()));
223 let mut app_cfg: AppConfig = AppConfig::default();
224 app_cfg.set_window(window_cfg);
225 let backend: Box<dyn PlatformBackend> =
226 Box::new(HeadlessPlatform::emulating(platform, init_scale, safe_area));
227 let mut app: App = App::with_platform(app_cfg, backend)?;
228 let phys_w: u32 = ((init_w as f64) * (init_scale as f64)).round().max(1.0) as u32;
229 let phys_h: u32 = ((init_h as f64) * (init_scale as f64)).round().max(1.0) as u32;
230 app.set_exact_physical_viewport(phys_w, phys_h, init_scale);
231 let wid: WindowId = app.get_window_state().get_id();
232 app.dispatch_window_event(WindowEvent::SafeAreaChanged(wid, safe_area));
233 app.dispatch_window_event(WindowEvent::System(SystemEvent::SafeAreaChanged(safe_area)));
234 let state: ShowcaseState = ShowcaseState::new_with_hub(app.get_dynamic_hub().clone(), false);
235 state.set_default_host_platform_idx(host_platform_matrix_index(app.platform_kind()));
236 app.attach_game_host(state.get_game_host().clone());
237 app.attach_game_host(state.get_game3d_host().clone());
238 app.attach_game_host(state.get_water_host().clone());
239 let mount_state: ShowcaseState = state.clone();
240 let _: NodeId = app.mount(move || mount_showcase_root(&mount_state));
241 state.sync_adaptive_from_app(&mut app);
242 if matches!(platform, PlatformKind::Ios)
243 || matches!(platform, PlatformKind::IpadOs)
244 || matches!(platform, PlatformKind::Android)
245 || matches!(platform, PlatformKind::MacOs)
246 || matches!(platform, PlatformKind::Windows)
247 || matches!(platform, PlatformKind::Linux)
248 {
249 bootstrap_showcase_hot_updates(state.get_dynamic_hub());
250 }
251 Ok((app, state))
252}
253
254pub fn run_headless_smoke(mode: RenderMode) -> Result<FrameStats, PlatformError> {
264 let (mut app, _): (App, ShowcaseState) = create_showcase_app(true, mode)?;
265 app.step_frame()
266}
267
268#[cfg(not(target_arch = "wasm32"))]
282fn dump_rgba_frame(
283 app: &mut App,
284 out_dir: &Path,
285 name: &str,
286 manifest: &mut String,
287 count: &mut usize,
288) -> Result<(), PlatformError> {
289 let _: FrameStats = app.step_frame()?;
290 for _ in 0..20 {
291 if !app.has_active_animations() {
292 break;
293 }
294 let _: FrameStats = app.step_game_frame(1.0 / 60.0)?;
295 }
296 if let Some(frame_pixels) = app.get_renderer().framebuffer() {
297 let file_name: String = format!("{name}.rgba");
298 let file_path: PathBuf = out_dir.join(&file_name);
299 fs::write(&file_path, frame_pixels.get_pixels().as_slice())
300 .map_err(|err: Error| PlatformError::SurfaceError(err.to_string()))?;
301 manifest.push_str(&format!(
302 "{name} {} {}\n",
303 frame_pixels.get_width(),
304 frame_pixels.get_height()
305 ));
306 *count += 1;
307 }
308 Ok(())
309}
310
311#[cfg(not(target_arch = "wasm32"))]
321pub fn capture_showcase_screenshots(out_dir: &Path) -> Result<usize, PlatformError> {
322 reset_reactive_runtime();
323 EuvOverlayStack::clear();
324 reset_fullscreen_state();
325 clear_provided_theme();
326 fs::create_dir_all(out_dir)
327 .map_err(|err: Error| PlatformError::InitializationFailed(err.to_string()))?;
328 let mut window_cfg: WindowConfig = WindowConfig::default();
329 window_cfg
330 .set_title(SHOWCASE_WINDOW_TITLE.to_string())
331 .set_size(1200, 800)
332 .set_render(RenderConfig::software())
333 .set_icon(Some(euv_brand_logo_image()));
334 let mut app_cfg: AppConfig = AppConfig::default();
335 app_cfg.set_window(window_cfg);
336 let backend: Box<dyn PlatformBackend> = Box::new(HeadlessPlatform::emulating(
337 PlatformKind::Headless,
338 2.0,
339 SafeAreaInsets::default(),
340 ));
341 let mut app: App = App::with_platform(app_cfg, backend)?;
342 let state: ShowcaseState = ShowcaseState::new_with_hub(app.get_dynamic_hub().clone(), false);
343 app.attach_game_host(state.get_game_host().clone());
344 app.attach_game_host(state.get_game3d_host().clone());
345 app.attach_game_host(state.get_water_host().clone());
346 let mount_state: ShowcaseState = state.clone();
347 let _: NodeId = app.mount(move || mount_showcase_root(&mount_state));
348 app.get_mut_renderer()
349 .get_mut_software()
350 .set_font_provider(NativeSystemFont::system());
351 let wid: WindowId = app.get_window_state().get_id();
352 let mut manifest: String = String::new();
353 let mut count: usize = 0;
354 app.dispatch_window_event(WindowEvent::Resized(wid, 1200, 800, 2.0));
355 let desktop_routes: [(&str, &str); 12] = [
356 (ROUTE_OVERVIEW, "01_overview_desktop"),
357 (ROUTE_REACTIVE, "02_reactive_desktop"),
358 (ROUTE_RENDER, "03_render_desktop"),
359 (ROUTE_WINDOW, "04_window_desktop"),
360 (ROUTE_FORMS, "05_forms_desktop"),
361 (ROUTE_THEMES, "06_themes_desktop"),
362 (ROUTE_DATA, "07_data_desktop"),
363 (ROUTE_GAME, "08_game_desktop"),
364 (ROUTE_GAME_3D, "08b_game3d_desktop"),
365 (ROUTE_MEDIA, "08c_media_desktop"),
366 (ROUTE_OVERLAYS, "09_overlays_desktop"),
367 (ROUTE_DYNAMIC, "10_dynamic_desktop"),
368 ];
369 for (route, label) in desktop_routes.iter() {
370 let _: bool = state.get_route().set_if_changed((*route).to_string());
371 if *route == ROUTE_OVERVIEW {
372 app.dispatch_window_event(WindowEvent::PointerMove(
373 wid,
374 PointerEvent::mouse(100.0, 108.0),
375 ));
376 }
377 dump_rgba_frame(&mut app, out_dir, label, &mut manifest, &mut count)?;
378 }
379 let _: bool = state.get_route().set_if_changed(ROUTE_FORMS.to_string());
380 let _: FrameStats = app.step_frame()?;
381 app.dispatch_window_event(WindowEvent::PointerMove(
382 wid,
383 PointerEvent::mouse(600.0, 400.0),
384 ));
385 app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(0.0, 420.0)));
386 dump_rgba_frame(
387 &mut app,
388 out_dir,
389 "05b_forms_scrolled",
390 &mut manifest,
391 &mut count,
392 )?;
393 let _: bool = state.get_route().set_if_changed(ROUTE_DATA.to_string());
394 let _: FrameStats = app.step_frame()?;
395 app.dispatch_window_event(WindowEvent::PointerMove(
396 wid,
397 PointerEvent::mouse(600.0, 400.0),
398 ));
399 app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(0.0, 460.0)));
400 dump_rgba_frame(
401 &mut app,
402 out_dir,
403 "07b_data_vlist_scrolled",
404 &mut manifest,
405 &mut count,
406 )?;
407 app.dispatch_window_event(WindowEvent::PointerMove(
408 wid,
409 PointerEvent::mouse(320.0, 120.0),
410 ));
411 app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(0.0, 720.0)));
412 dump_rgba_frame(
413 &mut app,
414 out_dir,
415 "07c_data_bottom",
416 &mut manifest,
417 &mut count,
418 )?;
419 let _: bool = state.get_route().set_if_changed(ROUTE_OVERVIEW.to_string());
420 let _: FrameStats = app.step_frame()?;
421 app.dispatch_window_event(WindowEvent::PointerMove(
422 wid,
423 PointerEvent::mouse(100.0, 108.0),
424 ));
425 dump_rgba_frame(
426 &mut app,
427 out_dir,
428 "01b_overview_hovered",
429 &mut manifest,
430 &mut count,
431 )?;
432 let _: bool = state.get_route().set_if_changed(ROUTE_OVERLAYS.to_string());
433 let _: bool = state.get_modal_open().set_if_changed(true);
434 dump_rgba_frame(
435 &mut app,
436 out_dir,
437 "09b_overlays_modal",
438 &mut manifest,
439 &mut count,
440 )?;
441 let _: bool = state.get_modal_open().set_if_changed(false);
442 let _: bool = state.get_alert_dialog_open().set_if_changed(true);
443 dump_rgba_frame(
444 &mut app,
445 out_dir,
446 "09c_overlays_alert",
447 &mut manifest,
448 &mut count,
449 )?;
450 let _: bool = state.get_alert_dialog_open().set_if_changed(false);
451 let _: bool = state.get_hover_card_open().set_if_changed(true);
452 dump_rgba_frame(
453 &mut app,
454 out_dir,
455 "09d_overlays_hovercard",
456 &mut manifest,
457 &mut count,
458 )?;
459 let _: bool = state.get_hover_card_open().set_if_changed(false);
460 let _: bool = state.get_route().set_if_changed(ROUTE_THEMES.to_string());
461 state.toggle_theme_mode();
462 dump_rgba_frame(
463 &mut app,
464 out_dir,
465 "06b_themes_dark",
466 &mut manifest,
467 &mut count,
468 )?;
469 state.toggle_theme_mode();
470 let _: bool = state.get_route().set_if_changed(ROUTE_OVERVIEW.to_string());
471 app.dispatch_window_event(WindowEvent::Resized(wid, 768, 1024, 2.0));
472 dump_rgba_frame(
473 &mut app,
474 out_dir,
475 "11_overview_tablet",
476 &mut manifest,
477 &mut count,
478 )?;
479 app.dispatch_window_event(WindowEvent::Resized(wid, 390, 844, 2.0));
480 dump_rgba_frame(
481 &mut app,
482 out_dir,
483 "12_overview_mobile",
484 &mut manifest,
485 &mut count,
486 )?;
487 app.dispatch_window_event(WindowEvent::PointerDown(
488 wid,
489 PointerEvent::mouse(350.0, 26.0),
490 ));
491 app.dispatch_window_event(WindowEvent::PointerUp(
492 wid,
493 PointerEvent::mouse(350.0, 26.0),
494 ));
495 dump_rgba_frame(
496 &mut app,
497 out_dir,
498 "12b_mobile_menu_open",
499 &mut manifest,
500 &mut count,
501 )?;
502 app.dispatch_window_event(WindowEvent::PointerDown(
503 wid,
504 PointerEvent::mouse(240.0, 26.0),
505 ));
506 app.dispatch_window_event(WindowEvent::PointerUp(
507 wid,
508 PointerEvent::mouse(240.0, 26.0),
509 ));
510 let _: bool = state.get_route().set_if_changed(ROUTE_FORMS.to_string());
511 dump_rgba_frame(
512 &mut app,
513 out_dir,
514 "13_forms_mobile",
515 &mut manifest,
516 &mut count,
517 )?;
518 fs::write(out_dir.join("manifest.txt"), manifest)
519 .map_err(|err: Error| PlatformError::SurfaceError(err.to_string()))?;
520 Ok(count)
521}
522
523#[must_use]
533pub fn normalize_web_hash_route(raw_hash: &str) -> String {
534 resolve_web_hash_route(raw_hash, None)
535}
536
537#[must_use]
548pub fn resolve_web_hash_route(raw_hash: &str, hub: Option<&DynamicUpdateHub>) -> String {
549 let trimmed: &str = raw_hash.trim().trim_start_matches('#');
550 let without_query: &str = trimmed.split(['?', '#']).next().unwrap_or("").trim();
551 let segments: Vec<&str> = without_query
552 .split('/')
553 .filter(|seg: &&str| !seg.is_empty())
554 .collect();
555 if segments.is_empty() {
556 return ROUTE_OVERVIEW.to_string();
557 }
558 let candidate: String = format!("/{}", segments.join("/"));
559 let is_static: bool = SHOWCASE_ROUTES
560 .iter()
561 .any(|spec: &ShowcaseRouteSpec| spec.get_path() == candidate.as_str());
562 let is_dynamic: bool = hub
563 .map(|height_val: &DynamicUpdateHub| height_val.has_dynamic_page(&candidate))
564 .unwrap_or(false);
565 if is_static || is_dynamic {
566 candidate
567 } else {
568 ROUTE_OVERVIEW.to_string()
569 }
570}
571
572pub fn apply_showcase_history_route(
584 app: &mut App,
585 state: &ShowcaseState,
586 raw_hash: &str,
587) -> String {
588 let next: String = resolve_web_hash_route(raw_hash, Some(state.get_dynamic_hub()));
589 let _: usize = EuvOverlayStack::dismiss_all();
590 let _: bool = state.get_cmd_palette_open().set_if_changed(false);
591 if app.is_immersive_fullscreen() || is_fullscreen_active() || EuvOverlayStack::has_fullscreen()
592 {
593 let _: usize = sync_external_fullscreen_exit();
594 app.set_immersive_fullscreen(false);
595 }
596 let _: bool = state.get_route().set_if_changed(next.clone());
597 next
598}
599
600#[must_use]
612pub fn web_is_ime_composition_key(is_composing: bool, key: &str, key_code: u32) -> bool {
613 is_composing || key == WEB_KEY_PROCESS || key_code == WEB_KEY_CODE_IME_PROCESS
614}
615
616#[must_use]
628pub fn web_should_dispatch_text_input(ime_active: bool, mods: Modifiers, key: &str) -> bool {
629 !ime_active && !mods.get_ctrl() && !mods.get_meta() && key.chars().count() == 1
630}
631
632#[cfg(target_arch = "wasm32")]
634#[wasm_bindgen(start)]
635pub fn euv_web_boot() {
636 let external_host_mode: bool =
637 Reflect::get(&global(), &JsValue::from_str(HOST_GLOBAL_MODE_KEY))
638 .ok()
639 .and_then(|val: JsValue| val.as_string())
640 .map(|text_value: String| !text_value.is_empty())
641 .unwrap_or(false);
642 if external_host_mode {
643 return;
644 }
645 let Some(win): Option<Window> = window() else {
646 return;
647 };
648 let Some(doc): Option<Document> = win.document() else {
649 return;
650 };
651 let Ok(Some(el)) = doc.query_selector(WEB_SELECTOR_CANVAS) else {
652 return;
653 };
654 let Ok(canvas) = el.dyn_into::<HtmlCanvasElement>() else {
655 return;
656 };
657 let _: u64 = euv_example_web_start();
658 #[cfg(debug_assertions)]
659 web_attach_dev_automation_bridge(&win);
660 web_attach_ime_proxy(&doc);
661 register_native_action_bridge(web_native_action_bridge);
662 register_frame_wakeup(web_mark_needs_frame);
663 let _: bool = web_refresh_cached_viewport(&win, &canvas);
664 let _: bool = web_apply_cached_viewport(&canvas);
665 let on_move: Closure<dyn FnMut(web_sys::PointerEvent)> =
666 Closure::wrap(Box::new(move |point_coords: web_sys::PointerEvent| {
667 let ptype: String = point_coords.pointer_type();
668 if ptype == WEB_PTR_TYPE_TOUCH {
669 WEB_LAST_TOUCH_TS_MS
670 .with(|char_item: &Cell<f64>| char_item.set(point_coords.time_stamp()));
671 } else if point_coords.buttons() == 0
672 && (point_coords.time_stamp() - WEB_LAST_TOUCH_TS_MS.with(Cell::get)).abs() < 600.0
673 {
674 return;
675 }
676 let ptr: PointerEvent = web_pointer_from_dom(&point_coords, None);
677 web_queue_pointer_move_event(ptr);
678 }) as Box<dyn FnMut(web_sys::PointerEvent)>);
679 drop(canvas.add_event_listener_with_callback(
680 WEB_EVENT_POINTER_MOVE,
681 on_move.as_ref().unchecked_ref(),
682 ));
683 on_move.forget();
684 let canvas_down: HtmlCanvasElement = canvas.clone();
685 let on_down: Closure<dyn FnMut(web_sys::PointerEvent)> =
686 Closure::wrap(Box::new(move |cursor_point: web_sys::PointerEvent| {
687 if cursor_point.pointer_type() == WEB_PTR_TYPE_TOUCH {
688 WEB_LAST_TOUCH_TS_MS
689 .with(|color_item: &Cell<f64>| color_item.set(cursor_point.time_stamp()));
690 }
691 drop(canvas_down.set_pointer_capture(cursor_point.pointer_id()));
692 let ptr: PointerEvent = web_pointer_from_dom(&cursor_point, Some(true));
693 web_queue_pointer_down_event(ptr);
694 if !WEB_IME_ACTIVE.with(Cell::get) {
695 drop(canvas_down.focus());
696 }
697 }) as Box<dyn FnMut(web_sys::PointerEvent)>);
698 drop(canvas.add_event_listener_with_callback(
699 WEB_EVENT_POINTER_DOWN,
700 on_down.as_ref().unchecked_ref(),
701 ));
702 on_down.forget();
703 let canvas_up: HtmlCanvasElement = canvas.clone();
704 let on_up: Closure<dyn FnMut(web_sys::PointerEvent)> =
705 Closure::wrap(Box::new(move |sample_point: web_sys::PointerEvent| {
706 sample_point.stop_propagation();
707 if sample_point.pointer_type() == WEB_PTR_TYPE_TOUCH {
708 WEB_LAST_TOUCH_TS_MS
709 .with(|cell_item: &Cell<f64>| cell_item.set(sample_point.time_stamp()));
710 }
711 let ptr: PointerEvent = web_pointer_from_dom(&sample_point, Some(false));
712 web_queue_pointer_up_event(ptr);
713 drop(canvas_up.release_pointer_capture(sample_point.pointer_id()));
714 }) as Box<dyn FnMut(web_sys::PointerEvent)>);
715 drop(
716 canvas
717 .add_event_listener_with_callback(WEB_EVENT_POINTER_UP, on_up.as_ref().unchecked_ref()),
718 );
719 on_up.forget();
720 let on_cancel: Closure<dyn FnMut(web_sys::PointerEvent)> =
721 Closure::wrap(Box::new(move |ui_event: web_sys::PointerEvent| {
722 ui_event.stop_propagation();
723 web_queue_pointer_cancel(web_pointer_id_from_dom(&ui_event));
724 }) as Box<dyn FnMut(web_sys::PointerEvent)>);
725 drop(canvas.add_event_listener_with_callback(
726 WEB_EVENT_POINTER_CANCEL,
727 on_cancel.as_ref().unchecked_ref(),
728 ));
729 drop(canvas.add_event_listener_with_callback(
730 WEB_EVENT_LOST_POINTER_CAPTURE,
731 on_cancel.as_ref().unchecked_ref(),
732 ));
733 on_cancel.forget();
734 let on_win_up: Closure<dyn FnMut(web_sys::PointerEvent)> =
735 Closure::wrap(Box::new(move |dispatched_event: web_sys::PointerEvent| {
736 if dispatched_event.pointer_type() == WEB_PTR_TYPE_TOUCH {
737 WEB_LAST_TOUCH_TS_MS.with(|component_val: &Cell<f64>| {
738 component_val.set(dispatched_event.time_stamp())
739 });
740 }
741 let ptr: PointerEvent = web_pointer_from_dom(&dispatched_event, Some(false));
742 web_queue_pointer_up_event(ptr);
743 }) as Box<dyn FnMut(web_sys::PointerEvent)>);
744 drop(win.add_event_listener_with_callback(
745 WEB_EVENT_POINTER_UP,
746 on_win_up.as_ref().unchecked_ref(),
747 ));
748 on_win_up.forget();
749 let on_win_cancel: Closure<dyn FnMut(web_sys::PointerEvent)> =
750 Closure::wrap(Box::new(move |event_item: web_sys::PointerEvent| {
751 web_queue_pointer_cancel(web_pointer_id_from_dom(&event_item));
752 }) as Box<dyn FnMut(web_sys::PointerEvent)>);
753 drop(win.add_event_listener_with_callback(
754 WEB_EVENT_POINTER_CANCEL,
755 on_win_cancel.as_ref().unchecked_ref(),
756 ));
757 on_win_cancel.forget();
758 let on_touch_cancel: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
759 web_queue_pointer_cancel(0);
760 }) as Box<dyn FnMut(Event)>);
761 drop(canvas.add_event_listener_with_callback(
762 WEB_EVENT_TOUCH_CANCEL,
763 on_touch_cancel.as_ref().unchecked_ref(),
764 ));
765 drop(win.add_event_listener_with_callback(
766 WEB_EVENT_TOUCH_CANCEL,
767 on_touch_cancel.as_ref().unchecked_ref(),
768 ));
769 on_touch_cancel.forget();
770 let on_blur: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
771 web_queue_pointer_cancel(0);
772 web_dispatch_system_event(SystemEvent::FocusChanged(false));
773 }) as Box<dyn FnMut(Event)>);
774 drop(win.add_event_listener_with_callback(WEB_EVENT_BLUR, on_blur.as_ref().unchecked_ref()));
775 on_blur.forget();
776 web_attach_system_event_listeners(&win, &doc, &canvas);
777 let on_wheel: Closure<dyn FnMut(WheelEvent)> =
778 Closure::wrap(Box::new(move |ui_event_primary: WheelEvent| {
779 ui_event_primary.prevent_default();
780 let (left, top, _, _, _): (f64, f64, f64, f64, f32) =
781 WEB_CACHED_VIEWPORT.with(Cell::get);
782 let pos_x: f32 = (ui_event_primary.client_x() as f64 - left) as f32;
783 let pos_y: f32 = (ui_event_primary.client_y() as f64 - top) as f32;
784 let mult: f32 = match ui_event_primary.delta_mode() {
785 1 => 20.0,
786 2 => 320.0,
787 _ => 1.0,
788 };
789 web_queue_scroll_at(
790 pos_x,
791 pos_y,
792 (ui_event_primary.delta_x() as f32) * mult,
793 (ui_event_primary.delta_y() as f32) * mult,
794 );
795 }) as Box<dyn FnMut(WheelEvent)>);
796 web_add_non_passive_listener(
797 canvas.as_ref(),
798 WEB_EVENT_WHEEL,
799 on_wheel.as_ref().unchecked_ref(),
800 );
801 on_wheel.forget();
802 let on_key: Closure<dyn FnMut(KeyboardEvent)> =
803 Closure::wrap(Box::new(move |ui_event_secondary: KeyboardEvent| {
804 let key: String = ui_event_secondary.key();
805 if WEB_IME_COMPOSING.with(Cell::get)
806 || web_is_ime_composition_key(
807 ui_event_secondary.is_composing(),
808 &key,
809 ui_event_secondary.key_code(),
810 )
811 {
812 return;
813 }
814 let code_str: String = ui_event_secondary.code();
815 let mods: Modifiers = Modifiers::new(
816 ui_event_secondary.shift_key(),
817 ui_event_secondary.ctrl_key(),
818 ui_event_secondary.alt_key(),
819 ui_event_secondary.meta_key(),
820 );
821 let ime_active: bool = WEB_IME_ACTIVE.with(Cell::get);
822 let cmd_or_ctrl: bool = mods.get_ctrl() || mods.get_meta();
823 let is_nav_or_edit_key: bool = matches!(
824 key.as_str(),
825 WEB_KEY_ARROW_UP
826 | WEB_KEY_ARROW_DOWN
827 | WEB_KEY_ARROW_LEFT
828 | WEB_KEY_ARROW_RIGHT
829 | WEB_KEY_HOME
830 | WEB_KEY_END
831 | WEB_KEY_BACKSPACE
832 | WEB_KEY_DELETE
833 );
834 let should_prevent: bool = if cmd_or_ctrl {
835 matches!(code_str.as_str(), WEB_CODE_KEY_K | WEB_CODE_KEY_A)
836 || (ime_active && is_nav_or_edit_key)
837 } else if ime_active {
838 is_nav_or_edit_key || key.as_str() == WEB_KEY_TAB
839 } else {
840 is_nav_or_edit_key
841 || key.as_str() == WEB_KEY_PAGE_UP
842 || key.as_str() == WEB_KEY_PAGE_DOWN
843 || key.as_str() == WEB_KEY_SPACE
844 };
845 if should_prevent {
846 ui_event_secondary.prevent_default();
847 }
848 web_queue_key_down(&key, &code_str, mods, ui_event_secondary.repeat());
849 }) as Box<dyn FnMut(KeyboardEvent)>);
850 drop(win.add_event_listener_with_callback(WEB_EVENT_KEY_DOWN, on_key.as_ref().unchecked_ref()));
851 on_key.forget();
852 let on_key_up: Closure<dyn FnMut(KeyboardEvent)> =
853 Closure::wrap(Box::new(move |ui_event_next: KeyboardEvent| {
854 let key: String = ui_event_next.key();
855 let code_str: String = ui_event_next.code();
856 let mods: Modifiers = Modifiers::new(
857 ui_event_next.shift_key(),
858 ui_event_next.ctrl_key(),
859 ui_event_next.alt_key(),
860 ui_event_next.meta_key(),
861 );
862 web_queue_key_up(&key, &code_str, mods);
863 }) as Box<dyn FnMut(KeyboardEvent)>);
864 drop(
865 win.add_event_listener_with_callback(WEB_EVENT_KEY_UP, on_key_up.as_ref().unchecked_ref()),
866 );
867 on_key_up.forget();
868 let on_paste: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |ui_event_alt: Event| {
869 if let Some(pasted) = web_extract_paste_text(&ui_event_alt)
870 && !pasted.is_empty()
871 {
872 ui_event_alt.prevent_default();
873 web_queue_text_input(pasted);
874 }
875 }) as Box<dyn FnMut(Event)>);
876 drop(win.add_event_listener_with_callback(WEB_EVENT_PASTE, on_paste.as_ref().unchecked_ref()));
877 on_paste.forget();
878 let on_copy: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |ui_event_inner: Event| {
879 if web_is_copy_proxy_event(&ui_event_inner) {
880 return;
881 }
882 if let Some(selected) = web_selected_text_snapshot()
883 && web_write_copy_event_text(&ui_event_inner, &selected)
884 {
885 ui_event_inner.prevent_default();
886 }
887 }) as Box<dyn FnMut(Event)>);
888 drop(doc.add_event_listener_with_callback(WEB_EVENT_COPY, on_copy.as_ref().unchecked_ref()));
889 on_copy.forget();
890 let win_resize: Window = win.clone();
891 let canvas_resize: HtmlCanvasElement = canvas.clone();
892 let on_resize: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
893 web_apply_viewport_resize_immediate(&win_resize, &canvas_resize);
894 }) as Box<dyn FnMut(Event)>);
895 drop(
896 win.add_event_listener_with_callback(WEB_EVENT_RESIZE, on_resize.as_ref().unchecked_ref()),
897 );
898 if let Ok(vv) = Reflect::get(win.as_ref(), &JsValue::from_str(WEB_PROP_VISUAL_VIEWPORT))
899 && let Ok(vv_target) = vv.dyn_into::<EventTarget>()
900 {
901 drop(vv_target.add_event_listener_with_callback(
902 WEB_EVENT_RESIZE,
903 on_resize.as_ref().unchecked_ref(),
904 ));
905 }
906 on_resize.forget();
907 let win_ro: Window = win.clone();
908 let canvas_ro: HtmlCanvasElement = canvas.clone();
909 let on_ro: Closure<dyn FnMut(f64, f64)> = Closure::wrap(Box::new(move |pw: f64, ph: f64| {
910 let valid_dims: bool = pw.is_finite() && ph.is_finite();
911 if valid_dims && pw >= 64.0 && ph >= 64.0 {
912 let obs_w: u32 = pw.round().clamp(1.0, WEB_CANVAS_MAX_PHYS_DIM) as u32;
913 let obs_h: u32 = ph.round().clamp(1.0, WEB_CANVAS_MAX_PHYS_DIM) as u32;
914 WEB_OBSERVED_PHYS_SIZE.with(|cell: &Cell<(u32, u32)>| cell.set((obs_w, obs_h)));
915 }
916 web_apply_viewport_resize_immediate(&win_ro, &canvas_ro);
917 }) as Box<dyn FnMut(f64, f64)>);
918 let attach_ro_fn: Function =
919 Function::new_with_args(WEB_JS_ATTACH_RESIZE_ARGS, WEB_JS_ATTACH_RESIZE_OBSERVER);
920 drop(attach_ro_fn.call2(
921 &JsValue::NULL,
922 canvas.as_ref(),
923 on_ro.as_ref().unchecked_ref(),
924 ));
925 on_ro.forget();
926 let win_dpr: Window = win.clone();
927 let canvas_dpr: HtmlCanvasElement = canvas.clone();
928 let on_dpr: Closure<dyn FnMut()> = Closure::wrap(Box::new(move || {
929 web_apply_viewport_resize_immediate(&win_dpr, &canvas_dpr);
930 }) as Box<dyn FnMut()>);
931 let attach_dpr_fn: Function =
932 Function::new_with_args(WEB_JS_WATCH_DPR_ARGS, WEB_JS_WATCH_DPR_BODY);
933 drop(attach_dpr_fn.call1(&JsValue::NULL, on_dpr.as_ref().unchecked_ref()));
934 on_dpr.forget();
935 let win_raf: Window = win.clone();
936 let canvas_raf: HtmlCanvasElement = canvas.clone();
937 WEB_RAF_CALLBACK.with(|slot: &RefCell<Option<Closure<dyn FnMut(f64)>>>| {
938 if let Ok(mut guard) = slot.try_borrow_mut() {
939 *guard = Some(Closure::wrap(Box::new(move |timestamp_val: f64| {
940 WEB_RAF_ID.with(|id_cell: &Cell<Option<i32>>| id_cell.set(None));
941 if !web_should_pump_frames() {
942 WEB_RAF_LAST_TS.with(|ts_cell: &Cell<f64>| ts_cell.set(0.0));
943 WEB_RAF_ACCUM_SECS.with(|s_cell: &Cell<f32>| s_cell.set(0.0));
944 WEB_RAF_ACCUM_FRAMES.with(|f_cell: &Cell<u32>| f_cell.set(0));
945 return;
946 }
947 let prev_ts: f64 =
948 WEB_RAF_LAST_TS.with(|ts_cell: &Cell<f64>| ts_cell.replace(timestamp_val));
949 let mut dt: f32 = 1.0 / 60.0;
950 let mut valid_step: bool = false;
951 if prev_ts > 0.0 {
952 let raw_dt: f32 = ((timestamp_val - prev_ts) / 1000.0) as f32;
953 if (0.001..=0.1).contains(&raw_dt) {
954 valid_step = true;
955 }
956 dt = raw_dt.clamp(0.001, 0.05);
957 }
958 if valid_step {
959 let next_secs: f32 = WEB_RAF_ACCUM_SECS.with(Cell::get) + dt;
960 let next_frames: u32 = WEB_RAF_ACCUM_FRAMES.with(Cell::get).saturating_add(1);
961 if next_secs >= 0.35 && next_frames >= 8 {
962 let measured_hz: f32 = (next_frames as f32) / next_secs;
963 WEB_RAF_ACCUM_SECS.with(|s_cell: &Cell<f32>| s_cell.set(0.0));
964 WEB_RAF_ACCUM_FRAMES.with(|f_cell: &Cell<u32>| f_cell.set(0));
965 WEB_RAF_CALIBRATED
966 .with(|char_item_primary: &Cell<bool>| char_item_primary.set(true));
967 web_report_host_refresh_rate(measured_hz);
968 } else {
969 WEB_RAF_ACCUM_SECS.with(|s_cell: &Cell<f32>| s_cell.set(next_secs));
970 WEB_RAF_ACCUM_FRAMES.with(|f_cell: &Cell<u32>| f_cell.set(next_frames));
971 }
972 }
973 let live_dpr_raw: f64 = win_raf.device_pixel_ratio();
974 let live_dpr: f32 = if live_dpr_raw.is_finite() && live_dpr_raw > 0.0 {
975 (live_dpr_raw as f32).clamp(WEB_DPR_MIN, WEB_DPR_MAX)
976 } else {
977 1.0
978 };
979 let cached_dpr: f32 = WEB_CACHED_VIEWPORT.with(Cell::get).4;
980 if (live_dpr - cached_dpr).abs() > 0.005 {
981 let _: bool = web_refresh_cached_viewport(&win_raf, &canvas_raf);
982 }
983 let resized_or_scaled: bool =
984 if WEB_VIEWPORT_DIRTY.with(|flag: &Cell<bool>| flag.replace(false)) {
985 web_apply_cached_viewport(&canvas_raf)
986 } else {
987 false
988 };
989 let cur_route: String = euv_web_current_route();
990 let on_game: bool = cur_route == ROUTE_GAME
991 || cur_route == ROUTE_GAME_3D
992 || cur_route == ROUTE_WATER;
993 let animating: bool = web_has_active_animations();
994 let dirty: bool = WEB_NEEDS_FRAME.with(|flag: &Cell<bool>| flag.replace(false))
995 || is_frame_needed();
996 let needs_continuous: bool = resized_or_scaled || on_game;
997 let needs_redraw: bool = animating || dirty;
998 if needs_continuous || needs_redraw {
999 let _: u64 = web_flush_frame(dt);
1000 web_record_raf_submission_proxy_tick(&canvas_raf);
1001 }
1002 let calibrated: bool = WEB_RAF_CALIBRATED.with(Cell::get);
1003 let still_active: bool = on_game
1004 || web_has_active_animations()
1005 || WEB_NEEDS_FRAME.with(Cell::get)
1006 || is_frame_needed()
1007 || !calibrated;
1008 if still_active && web_should_pump_frames() {
1009 web_start_raf_pump(&win_raf);
1010 } else {
1011 WEB_RAF_LAST_TS.with(|ts_cell: &Cell<f64>| ts_cell.set(0.0));
1012 }
1013 }) as Box<dyn FnMut(f64)>));
1014 }
1015 });
1016 if doc.hidden() {
1017 web_dispatch_system_event(SystemEvent::Background);
1018 } else {
1019 web_start_raf_pump(&win);
1020 }
1021}
1022
1023#[cfg(target_arch = "wasm32")]
1029fn web_record_raf_submission_proxy_tick(canvas: &HtmlCanvasElement) {
1030 let pixel_bytes: u64 = u64::from(canvas.width())
1031 .saturating_mul(u64::from(canvas.height()))
1032 .saturating_mul(4);
1033 WEB_DUAL_CANVAS_COORDINATOR.with(|cell: &RefCell<ShowcaseWebDualCanvasCoordinator>| {
1034 if let Ok(mut coord) = cell.try_borrow_mut() {
1035 coord.record_raf_proxy_tick(pixel_bytes);
1036 }
1037 });
1038}
1039
1040#[cfg(target_arch = "wasm32")]
1052#[must_use]
1053pub fn web_begin_independent_canvas_switch(
1054 target: ShowcaseWebPresentationPath,
1055 width: u32,
1056 height: u32,
1057) -> bool {
1058 WEB_DUAL_CANVAS_COORDINATOR.with(|cell: &RefCell<ShowcaseWebDualCanvasCoordinator>| {
1059 cell.try_borrow_mut()
1060 .map(|mut coord: RefMut<'_, ShowcaseWebDualCanvasCoordinator>| {
1061 coord.begin_switch(target, width, height)
1062 })
1063 .unwrap_or(false)
1064 })
1065}
1066
1067#[cfg(target_arch = "wasm32")]
1079#[must_use]
1080pub fn web_commit_independent_canvas_switch(
1081 expected_width: u32,
1082 expected_height: u32,
1083 expected_scene_version: u64,
1084) -> bool {
1085 WEB_DUAL_CANVAS_COORDINATOR.with(|cell: &RefCell<ShowcaseWebDualCanvasCoordinator>| {
1086 cell.try_borrow_mut()
1087 .map(|mut coord: RefMut<'_, ShowcaseWebDualCanvasCoordinator>| {
1088 coord.commit_at_frame_boundary(
1089 expected_width,
1090 expected_height,
1091 expected_scene_version,
1092 )
1093 })
1094 .unwrap_or(false)
1095 })
1096}
1097
1098#[cfg(target_arch = "wasm32")]
1104#[must_use]
1105pub fn web_dual_canvas_snapshot() -> ShowcaseWebDualCanvasCoordinator {
1106 WEB_DUAL_CANVAS_COORDINATOR
1107 .with(|cell: &RefCell<ShowcaseWebDualCanvasCoordinator>| cell.borrow().clone())
1108}
1109
1110#[cfg(target_arch = "wasm32")]
1116fn web_should_pump_frames() -> bool {
1117 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1118 match slot.try_borrow() {
1119 Ok(guard) => {
1120 let pump: bool = guard
1121 .as_ref()
1122 .map(|(app, _): &(App, ShowcaseState)| app.should_pump_frames())
1123 .unwrap_or(false);
1124 WEB_SHOULD_PUMP.with(|flag: &Cell<bool>| flag.set(pump));
1125 pump
1126 }
1127 Err(_) => WEB_SHOULD_PUMP.with(Cell::get),
1128 }
1129 })
1130}
1131
1132#[cfg(target_arch = "wasm32")]
1138fn web_start_raf_pump(win: &Window) {
1139 if !web_should_pump_frames() {
1140 return;
1141 }
1142 let already_scheduled: bool =
1143 WEB_RAF_ID.with(|id_cell: &Cell<Option<i32>>| id_cell.get().is_some());
1144 if already_scheduled {
1145 return;
1146 }
1147 WEB_RAF_CALLBACK.with(|slot: &RefCell<Option<Closure<dyn FnMut(f64)>>>| {
1148 if let Ok(cb_ref) = slot.try_borrow()
1149 && let Some(callback_fn) = cb_ref.as_ref()
1150 {
1151 let func: &Function = callback_fn.as_ref().unchecked_ref();
1152 if let Ok(req_id) = win.request_animation_frame(func) {
1153 WEB_RAF_ID.with(|id_cell: &Cell<Option<i32>>| id_cell.set(Some(req_id)));
1154 }
1155 }
1156 });
1157}
1158
1159#[cfg(target_arch = "wasm32")]
1161fn web_stop_raf_pump() {
1162 let pending_id: Option<i32> = WEB_RAF_ID.with(|id_cell: &Cell<Option<i32>>| id_cell.take());
1163 if let Some(req_id) = pending_id
1164 && let Some(win) = window()
1165 {
1166 drop(win.cancel_animation_frame(req_id));
1167 }
1168 WEB_RAF_LAST_TS.with(|ts_cell: &Cell<f64>| ts_cell.set(0.0));
1169 WEB_RAF_ACCUM_SECS.with(|s_cell: &Cell<f32>| s_cell.set(0.0));
1170 WEB_RAF_ACCUM_FRAMES.with(|f_cell: &Cell<u32>| f_cell.set(0));
1171}
1172
1173#[cfg(target_arch = "wasm32")]
1179fn web_dispatch_system_event(event: SystemEvent) {
1180 let mut should_pump: bool = false;
1181 let mut handled: bool = false;
1182 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1183 if let Ok(mut borrow) = slot.try_borrow_mut()
1184 && let Some((app, _)) = borrow.as_mut()
1185 {
1186 app.dispatch_system_event(event);
1187 should_pump = app.should_pump_frames();
1188 handled = true;
1189 }
1190 });
1191 if !handled {
1192 return;
1193 }
1194 WEB_SHOULD_PUMP.with(|flag: &Cell<bool>| flag.set(should_pump));
1195 if !should_pump {
1196 web_stop_raf_pump();
1197 } else {
1198 WEB_RAF_LAST_TS.with(|ts_cell: &Cell<f64>| ts_cell.set(0.0));
1199 web_mark_needs_frame();
1200 if let Some(win) = window() {
1201 web_start_raf_pump(&win);
1202 }
1203 }
1204}
1205
1206#[cfg(target_arch = "wasm32")]
1216fn web_extract_paste_text(ui_event: &Event) -> Option<String> {
1217 let data: JsValue = Reflect::get(
1218 ui_event.as_ref(),
1219 &JsValue::from_str(WEB_PROP_CLIPBOARD_DATA),
1220 )
1221 .ok()?;
1222 if data.is_null() || data.is_undefined() {
1223 return None;
1224 }
1225 let get_fn_val: JsValue = Reflect::get(&data, &JsValue::from_str(WEB_PROP_GET_DATA)).ok()?;
1226 let get_fn: Function = get_fn_val.dyn_into::<Function>().ok()?;
1227 let result: JsValue = get_fn
1228 .call1(&data, &JsValue::from_str(WEB_MIME_TEXT_PLAIN))
1229 .ok()?;
1230 result
1231 .as_string()
1232 .filter(|text_value: &String| !text_value.is_empty())
1233}
1234
1235#[cfg(target_arch = "wasm32")]
1245fn web_is_copy_proxy_event(ui_event: &Event) -> bool {
1246 let Some(target) = ui_event.target() else {
1247 return false;
1248 };
1249 let Ok(el) = target.dyn_into::<Element>() else {
1250 return false;
1251 };
1252 el.get_attribute(WEB_ATTR_COPY_PROXY).as_deref() == Some(WEB_COPY_PROXY_FLAG)
1253}
1254
1255#[cfg(target_arch = "wasm32")]
1261fn web_selected_text_snapshot() -> Option<String> {
1262 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1263 let Ok(guard) = slot.try_borrow() else {
1264 return None;
1265 };
1266 let (app, _): &(App, ShowcaseState) = guard.as_ref()?;
1267 app.get_scene()
1268 .get_selected_text()
1269 .filter(|text_value: &String| !text_value.is_empty())
1270 })
1271}
1272
1273#[cfg(target_arch = "wasm32")]
1284fn web_write_copy_event_text(ui_event: &Event, text: &str) -> bool {
1285 let Ok(data) = Reflect::get(
1286 ui_event.as_ref(),
1287 &JsValue::from_str(WEB_PROP_CLIPBOARD_DATA),
1288 ) else {
1289 return false;
1290 };
1291 if data.is_null() || data.is_undefined() {
1292 return false;
1293 }
1294 let Ok(set_fn_val) = Reflect::get(&data, &JsValue::from_str(WEB_PROP_SET_DATA)) else {
1295 return false;
1296 };
1297 let Ok(set_fn) = set_fn_val.dyn_into::<Function>() else {
1298 return false;
1299 };
1300 set_fn
1301 .call2(
1302 &data,
1303 &JsValue::from_str(WEB_MIME_TEXT_PLAIN),
1304 &JsValue::from_str(text),
1305 )
1306 .is_ok()
1307}
1308
1309#[cfg(target_arch = "wasm32")]
1315fn web_sync_route_from_browser_history(win: &Window) {
1316 let raw_hash: String = win.location().hash().unwrap_or_default();
1317 let prev_guard: bool = WEB_SYNCING_FROM_HISTORY.with(|flag: &Cell<bool>| flag.replace(true));
1318 let mut updated: bool = false;
1319 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1320 if let Ok(mut borrow) = slot.try_borrow_mut()
1321 && let Some((app, state)) = borrow.as_mut()
1322 {
1323 let _: String = apply_showcase_history_route(app, state, &raw_hash);
1324 updated = true;
1325 }
1326 });
1327 WEB_SYNCING_FROM_HISTORY.with(|flag: &Cell<bool>| flag.set(prev_guard));
1328 if updated {
1329 let _: bool = web_sync_safe_area();
1330 web_mark_needs_frame();
1331 web_start_raf_pump(win);
1332 }
1333 if let Ok(href) = win.location().href() {
1334 web_dispatch_system_event(SystemEvent::DeepLink(href));
1335 }
1336}
1337
1338#[cfg(target_arch = "wasm32")]
1348fn web_doc_is_fullscreen(doc: &Document) -> bool {
1349 if doc.fullscreen_element().is_some() {
1350 return true;
1351 }
1352 Reflect::get(
1353 doc.as_ref(),
1354 &JsValue::from_str(WEB_PROP_WEBKIT_FULLSCREEN_ELEMENT),
1355 )
1356 .ok()
1357 .map(|item_val: JsValue| !item_val.is_null() && !item_val.is_undefined())
1358 .unwrap_or(false)
1359}
1360
1361#[cfg(target_arch = "wasm32")]
1369fn web_add_non_passive_listener(target: &EventTarget, event: &str, callback: &Function) {
1370 let opts: Object = Object::new();
1371 let _: Result<bool, JsValue> = Reflect::set(
1372 opts.as_ref(),
1373 &JsValue::from_str(WEB_OPT_PASSIVE),
1374 &JsValue::FALSE,
1375 );
1376 if let Ok(add_val) = Reflect::get(
1377 target.as_ref(),
1378 &JsValue::from_str(WEB_METHOD_ADD_EVENT_LISTENER),
1379 ) && let Ok(add_fn) = add_val.dyn_into::<Function>()
1380 && add_fn
1381 .call3(
1382 target.as_ref(),
1383 &JsValue::from_str(event),
1384 callback.as_ref(),
1385 opts.as_ref(),
1386 )
1387 .is_ok()
1388 {
1389 return;
1390 }
1391 drop(target.add_event_listener_with_callback(event, callback));
1392}
1393
1394#[cfg(target_arch = "wasm32")]
1396fn web_ensure_visible_foreground() {
1397 if WEB_SHOULD_PUMP.with(Cell::get) {
1398 return;
1399 }
1400 let is_hidden: bool = window()
1401 .and_then(|width_val: Window| width_val.document())
1402 .map(|delta_val: Document| delta_val.hidden())
1403 .unwrap_or(false);
1404 if !is_hidden {
1405 web_dispatch_system_event(SystemEvent::Foreground);
1406 }
1407}
1408
1409#[cfg(target_arch = "wasm32")]
1416fn web_apply_viewport_resize_immediate(win: &Window, canvas: &HtmlCanvasElement) {
1417 web_ensure_visible_foreground();
1418 let viewport_changed: bool = web_refresh_cached_viewport(win, canvas);
1419 let safe_changed: bool = web_sync_safe_area();
1420 let applied: bool = web_apply_cached_viewport(canvas);
1421 let changed_metrics: bool = viewport_changed || safe_changed;
1422 if changed_metrics || applied {
1423 WEB_VIEWPORT_DIRTY.with(|flag: &Cell<bool>| flag.set(false));
1424 let _: u64 = web_flush_frame(0.0);
1425 web_mark_needs_frame();
1426 web_start_raf_pump(win);
1427 }
1428}
1429
1430#[cfg(target_arch = "wasm32")]
1438fn web_sync_fullscreen_from_dom(win: &Window, doc: &Document, canvas: &HtmlCanvasElement) {
1439 web_ensure_visible_foreground();
1440 let dom_fs: bool = web_doc_is_fullscreen(doc);
1441 if !dom_fs {
1442 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1443 if let Ok(mut borrow) = slot.try_borrow_mut()
1444 && let Some((app, _)) = borrow.as_mut()
1445 && (app.is_immersive_fullscreen()
1446 || is_fullscreen_active()
1447 || EuvOverlayStack::has_fullscreen())
1448 {
1449 let _: usize = sync_external_fullscreen_exit();
1450 app.set_immersive_fullscreen(false);
1451 }
1452 });
1453 }
1454 let _: bool = web_refresh_cached_viewport(win, canvas);
1455 let _: bool = web_sync_safe_area();
1456 let _: bool = web_apply_cached_viewport(canvas);
1457 WEB_VIEWPORT_DIRTY.with(|flag: &Cell<bool>| flag.set(false));
1458 let _: u64 = web_flush_frame(0.0);
1459 web_mark_needs_frame();
1460 web_start_raf_pump(win);
1461}
1462
1463#[cfg(target_arch = "wasm32")]
1469fn web_dispatch_theme_changed(mode: ThemeMode) {
1470 let mut dispatched: bool = false;
1471 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1472 if let Ok(mut borrow) = slot.try_borrow_mut()
1473 && let Some((app, _)) = borrow.as_mut()
1474 {
1475 let wid: WindowId = app.get_window_state().get_id();
1476 app.dispatch_window_event(WindowEvent::ThemeChanged(wid, mode));
1477 dispatched = true;
1478 }
1479 });
1480 if dispatched {
1481 web_mark_needs_frame();
1482 }
1483}
1484
1485#[cfg(target_arch = "wasm32")]
1492fn web_handle_orientation_change(win: &Window, canvas: &HtmlCanvasElement) {
1493 web_apply_viewport_resize_immediate(win, canvas);
1494 let (_, _, css_w, css_h, _): (f64, f64, f64, f64, f32) = WEB_CACHED_VIEWPORT.with(Cell::get);
1495 let orient: ScreenOrientation = if css_w > css_h {
1496 ScreenOrientation::Landscape
1497 } else {
1498 ScreenOrientation::Portrait
1499 };
1500 web_dispatch_system_event(SystemEvent::OrientationChanged(orient));
1501 let _: u64 = web_flush_frame(0.0);
1502 web_mark_needs_frame();
1503 web_start_raf_pump(win);
1504}
1505
1506#[cfg(target_arch = "wasm32")]
1514fn web_attach_system_event_listeners(win: &Window, doc: &Document, canvas: &HtmlCanvasElement) {
1515 let doc_vis: Document = doc.clone();
1516 let win_vis: Window = win.clone();
1517 let canvas_vis: HtmlCanvasElement = canvas.clone();
1518 let on_vis: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1519 if doc_vis.hidden() {
1520 web_queue_pointer_cancel(0);
1521 web_dispatch_system_event(SystemEvent::Background);
1522 } else {
1523 let _: bool = web_refresh_cached_viewport(&win_vis, &canvas_vis);
1524 let _: bool = web_sync_safe_area();
1525 web_dispatch_system_event(SystemEvent::Foreground);
1526 }
1527 }) as Box<dyn FnMut(Event)>);
1528 drop(doc.add_event_listener_with_callback(
1529 WEB_EVENT_VISIBILITY_CHANGE,
1530 on_vis.as_ref().unchecked_ref(),
1531 ));
1532 on_vis.forget();
1533 let win_focus: Window = win.clone();
1534 let canvas_focus: HtmlCanvasElement = canvas.clone();
1535 let on_focus: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1536 let _: bool = web_refresh_cached_viewport(&win_focus, &canvas_focus);
1537 let _: bool = web_sync_safe_area();
1538 web_dispatch_system_event(SystemEvent::Foreground);
1539 web_dispatch_system_event(SystemEvent::FocusChanged(true));
1540 }) as Box<dyn FnMut(Event)>);
1541 drop(win.add_event_listener_with_callback(WEB_EVENT_FOCUS, on_focus.as_ref().unchecked_ref()));
1542 on_focus.forget();
1543 let win_ps: Window = win.clone();
1544 let canvas_ps: HtmlCanvasElement = canvas.clone();
1545 let on_pageshow: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1546 let _: bool = web_refresh_cached_viewport(&win_ps, &canvas_ps);
1547 let _: bool = web_sync_safe_area();
1548 web_sync_route_from_browser_history(&win_ps);
1549 web_dispatch_system_event(SystemEvent::Foreground);
1550 }) as Box<dyn FnMut(Event)>);
1551 drop(win.add_event_listener_with_callback(
1552 WEB_EVENT_PAGE_SHOW,
1553 on_pageshow.as_ref().unchecked_ref(),
1554 ));
1555 on_pageshow.forget();
1556 let on_pagehide: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1557 web_queue_pointer_cancel(0);
1558 web_dispatch_system_event(SystemEvent::Background);
1559 }) as Box<dyn FnMut(Event)>);
1560 drop(win.add_event_listener_with_callback(
1561 WEB_EVENT_PAGE_HIDE,
1562 on_pagehide.as_ref().unchecked_ref(),
1563 ));
1564 on_pagehide.forget();
1565 let on_unload: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1566 web_dispatch_system_event(SystemEvent::Terminate);
1567 }) as Box<dyn FnMut(Event)>);
1568 drop(win.add_event_listener_with_callback(
1569 WEB_EVENT_BEFORE_UNLOAD,
1570 on_unload.as_ref().unchecked_ref(),
1571 ));
1572 on_unload.forget();
1573 let on_online: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1574 web_dispatch_system_event(SystemEvent::NetworkStatusChanged(NetworkStatus::Online));
1575 }) as Box<dyn FnMut(Event)>);
1576 drop(
1577 win.add_event_listener_with_callback(WEB_EVENT_ONLINE, on_online.as_ref().unchecked_ref()),
1578 );
1579 on_online.forget();
1580 let on_offline: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1581 web_dispatch_system_event(SystemEvent::NetworkStatusChanged(NetworkStatus::Offline));
1582 }) as Box<dyn FnMut(Event)>);
1583 drop(
1584 win.add_event_listener_with_callback(
1585 WEB_EVENT_OFFLINE,
1586 on_offline.as_ref().unchecked_ref(),
1587 ),
1588 );
1589 on_offline.forget();
1590 if let Ok(Some(mql)) = win.match_media(WEB_MEDIA_PREFERS_DARK) {
1591 let mql_cb: MediaQueryList = mql.clone();
1592 let on_theme: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1593 let next_theme: ThemeMode = if mql_cb.matches() {
1594 ThemeMode::Dark
1595 } else {
1596 ThemeMode::Light
1597 };
1598 web_dispatch_theme_changed(next_theme);
1599 })
1600 as Box<dyn FnMut(Event)>);
1601 drop(
1602 mql.add_event_listener_with_callback(
1603 WEB_EVENT_CHANGE,
1604 on_theme.as_ref().unchecked_ref(),
1605 ),
1606 );
1607 on_theme.forget();
1608 }
1609 let win_hist: Window = win.clone();
1610 let on_history: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1611 web_sync_route_from_browser_history(&win_hist);
1612 }) as Box<dyn FnMut(Event)>);
1613 drop(win.add_event_listener_with_callback(
1614 WEB_EVENT_HASH_CHANGE,
1615 on_history.as_ref().unchecked_ref(),
1616 ));
1617 drop(win.add_event_listener_with_callback(
1618 WEB_EVENT_POP_STATE,
1619 on_history.as_ref().unchecked_ref(),
1620 ));
1621 on_history.forget();
1622 let win_fs: Window = win.clone();
1623 let doc_fs: Document = doc.clone();
1624 let canvas_fs: HtmlCanvasElement = canvas.clone();
1625 let on_fs_change: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1626 web_sync_fullscreen_from_dom(&win_fs, &doc_fs, &canvas_fs);
1627 }) as Box<dyn FnMut(Event)>);
1628 drop(doc.add_event_listener_with_callback(
1629 WEB_EVENT_FULLSCREEN_CHANGE,
1630 on_fs_change.as_ref().unchecked_ref(),
1631 ));
1632 drop(doc.add_event_listener_with_callback(
1633 WEB_EVENT_WEBKIT_FULLSCREEN_CHANGE,
1634 on_fs_change.as_ref().unchecked_ref(),
1635 ));
1636 on_fs_change.forget();
1637 let win_orient: Window = win.clone();
1638 let canvas_orient: HtmlCanvasElement = canvas.clone();
1639 let on_orient: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1640 web_handle_orientation_change(&win_orient, &canvas_orient);
1641 }) as Box<dyn FnMut(Event)>);
1642 drop(win.add_event_listener_with_callback(
1643 WEB_EVENT_ORIENTATION_CHANGE,
1644 on_orient.as_ref().unchecked_ref(),
1645 ));
1646 if let Ok(screen_val) = Reflect::get(win.as_ref(), &JsValue::from_str(WEB_PROP_SCREEN))
1647 && !screen_val.is_null()
1648 && !screen_val.is_undefined()
1649 && let Ok(orient_val) = Reflect::get(&screen_val, &JsValue::from_str(WEB_PROP_ORIENTATION))
1650 && let Ok(orient_target) = orient_val.dyn_into::<EventTarget>()
1651 {
1652 drop(orient_target.add_event_listener_with_callback(
1653 WEB_EVENT_CHANGE,
1654 on_orient.as_ref().unchecked_ref(),
1655 ));
1656 }
1657 on_orient.forget();
1658 let vv_key: JsValue = JsValue::from_str(WEB_PROP_VISUAL_VIEWPORT);
1659 if let Ok(vv_val) = Reflect::get(win.as_ref(), &vv_key)
1660 && let Ok(vv_target) = vv_val.clone().dyn_into::<EventTarget>()
1661 {
1662 let win_vv: Window = win.clone();
1663 let vv_obj: JsValue = vv_val;
1664 let on_vv_resize: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1665 let inner_h: f32 = win_vv
1666 .inner_height()
1667 .ok()
1668 .and_then(|item_val: JsValue| item_val.as_f64())
1669 .unwrap_or(0.0) as f32;
1670 let h_key: JsValue = JsValue::from_str(WEB_PROP_HEIGHT);
1671 let vv_h: f32 = Reflect::get(&vv_obj, &h_key)
1672 .ok()
1673 .and_then(|tex_v: JsValue| tex_v.as_f64())
1674 .unwrap_or(inner_h as f64) as f32;
1675 let kb_delta: f32 = (inner_h - vv_h).max(0.0);
1676 let visible: bool = kb_delta >= WEB_KEYBOARD_MIN_DELTA_PX;
1677 let height: f32 = if visible { kb_delta } else { 0.0 };
1678 web_dispatch_system_event(SystemEvent::KeyboardVisibilityChanged { visible, height });
1679 if web_sync_safe_area() {
1680 web_mark_needs_frame();
1681 }
1682 })
1683 as Box<dyn FnMut(Event)>);
1684 drop(vv_target.add_event_listener_with_callback(
1685 WEB_EVENT_RESIZE,
1686 on_vv_resize.as_ref().unchecked_ref(),
1687 ));
1688 on_vv_resize.forget();
1689 }
1690}
1691
1692#[cfg(target_arch = "wasm32")]
1703fn web_map_key(key: &str, code_str: &str) -> KeyCode {
1704 match code_str {
1705 WEB_CODE_KEY_W => return KeyCode::Character('w'),
1706 WEB_CODE_KEY_A => return KeyCode::Character('a'),
1707 WEB_CODE_KEY_S => return KeyCode::Character('s'),
1708 WEB_CODE_KEY_D => return KeyCode::Character('d'),
1709 WEB_CODE_KEY_E => return KeyCode::Character('e'),
1710 WEB_CODE_KEY_R => return KeyCode::Character('r'),
1711 WEB_CODE_KEY_P => return KeyCode::Character('p'),
1712 WEB_CODE_KEY_J => return KeyCode::Character('j'),
1713 WEB_CODE_KEY_C => return KeyCode::Character('c'),
1714 WEB_CODE_KEY_V => return KeyCode::Character('v'),
1715 WEB_CODE_KEY_X => return KeyCode::Character('x'),
1716 WEB_CODE_KEY_Z => return KeyCode::Character('z'),
1717 WEB_CODE_KEY_K => return KeyCode::Character('k'),
1718 WEB_CODE_SPACE => return KeyCode::Space,
1719 WEB_KEY_ARROW_LEFT => return KeyCode::ArrowLeft,
1720 WEB_KEY_ARROW_RIGHT => return KeyCode::ArrowRight,
1721 WEB_KEY_ARROW_UP => return KeyCode::ArrowUp,
1722 WEB_KEY_ARROW_DOWN => return KeyCode::ArrowDown,
1723 WEB_KEY_HOME => return KeyCode::Home,
1724 WEB_KEY_END => return KeyCode::End,
1725 WEB_KEY_PAGE_UP => return KeyCode::PageUp,
1726 WEB_KEY_PAGE_DOWN => return KeyCode::PageDown,
1727 _ => {}
1728 }
1729 match key {
1730 WEB_KEY_ENTER => KeyCode::Enter,
1731 WEB_KEY_BACKSPACE => KeyCode::Backspace,
1732 WEB_KEY_DELETE => KeyCode::Delete,
1733 WEB_KEY_ESCAPE => KeyCode::Escape,
1734 WEB_KEY_TAB => KeyCode::Tab,
1735 WEB_KEY_SPACE => KeyCode::Space,
1736 WEB_KEY_ARROW_LEFT => KeyCode::ArrowLeft,
1737 WEB_KEY_ARROW_RIGHT => KeyCode::ArrowRight,
1738 WEB_KEY_ARROW_UP => KeyCode::ArrowUp,
1739 WEB_KEY_ARROW_DOWN => KeyCode::ArrowDown,
1740 WEB_KEY_HOME => KeyCode::Home,
1741 WEB_KEY_END => KeyCode::End,
1742 WEB_KEY_PAGE_UP => KeyCode::PageUp,
1743 WEB_KEY_PAGE_DOWN => KeyCode::PageDown,
1744 other => other
1745 .chars()
1746 .next()
1747 .map(KeyCode::Character)
1748 .unwrap_or(KeyCode::Unknown),
1749 }
1750}
1751
1752#[cfg(target_arch = "wasm32")]
1758fn web_has_active_animations() -> bool {
1759 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1760 match slot.try_borrow() {
1761 Ok(guard) => guard
1762 .as_ref()
1763 .map(|(app, _): &(App, ShowcaseState)| app.has_active_animations())
1764 .unwrap_or(false),
1765 Err(_) => false,
1766 }
1767 })
1768}
1769
1770#[cfg(target_arch = "wasm32")]
1772fn web_mark_needs_frame() {
1773 WEB_NEEDS_FRAME.with(|flag: &Cell<bool>| flag.set(true));
1774 let idle: bool = WEB_RAF_ID.with(|id_cell: &Cell<Option<i32>>| id_cell.get().is_none());
1775 if idle && let Some(win) = window() {
1776 web_start_raf_pump(&win);
1777 }
1778}
1779
1780#[cfg(target_arch = "wasm32")]
1790fn web_pointer_id_from_dom(point_coords: &web_sys::PointerEvent) -> u64 {
1791 (point_coords.pointer_id() as i64)
1792 .unsigned_abs()
1793 .saturating_add(1)
1794}
1795
1796#[cfg(target_arch = "wasm32")]
1807fn web_pointer_from_dom(
1808 point_coords: &web_sys::PointerEvent,
1809 force_pressed: Option<bool>,
1810) -> PointerEvent {
1811 let (left, top, _, _, _): (f64, f64, f64, f64, f32) = WEB_CACHED_VIEWPORT.with(Cell::get);
1812 let pos_x: f32 = (point_coords.client_x() as f64 - left) as f32;
1813 let pos_y: f32 = (point_coords.client_y() as f64 - top) as f32;
1814 let pid: u64 = web_pointer_id_from_dom(point_coords);
1815 let ptype: String = point_coords.pointer_type();
1816 let device: PointerDevice = if ptype == WEB_PTR_TYPE_TOUCH {
1817 PointerDevice::Touch
1818 } else if ptype == WEB_PTR_TYPE_PEN {
1819 PointerDevice::Stylus
1820 } else {
1821 PointerDevice::Mouse
1822 };
1823 let is_pressed: bool = force_pressed
1824 .unwrap_or_else(|| point_coords.buttons() != 0 || device == PointerDevice::Touch);
1825 let pressure: f32 = if is_pressed { 1.0 } else { 0.0 };
1826 let mods: Modifiers = Modifiers::new(
1827 point_coords.shift_key(),
1828 point_coords.ctrl_key(),
1829 point_coords.alt_key(),
1830 point_coords.meta_key(),
1831 );
1832 PointerEvent::new(
1833 pid,
1834 device,
1835 Point::new(pos_x, pos_y),
1836 PointerButton::Primary,
1837 pressure,
1838 mods,
1839 )
1840}
1841
1842#[cfg(target_arch = "wasm32")]
1848fn web_queue_pointer_move_event(ptr: PointerEvent) {
1849 let mut needs_redraw: bool = false;
1850 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1851 if let Ok(mut borrow) = slot.try_borrow_mut()
1852 && let Some((app, _)) = borrow.as_mut()
1853 {
1854 let rev_before: u64 = app.get_scene().with_read(SceneTree::get_revision, 0);
1855 let cursor_before: CursorIcon = app.get_last_cursor();
1856 let wid: WindowId = app.get_window_state().get_id();
1857 app.dispatch_window_event(WindowEvent::PointerMove(wid, ptr));
1858 let rev_after: u64 = app.get_scene().with_read(SceneTree::get_revision, 0);
1859 let cursor_after: CursorIcon = app.get_last_cursor();
1860 let active_drag: bool =
1861 ptr.get_pressure() > 0.0 || ptr.get_device() != PointerDevice::Mouse;
1862 let has_anim: bool = app
1863 .get_scene()
1864 .with_read(SceneTree::has_active_transitions, false);
1865 needs_redraw = rev_after != rev_before
1866 || cursor_after != cursor_before
1867 || active_drag
1868 || has_anim
1869 || is_frame_needed();
1870 }
1871 });
1872 if needs_redraw {
1873 web_mark_needs_frame();
1874 }
1875}
1876
1877#[cfg(target_arch = "wasm32")]
1883fn web_queue_pointer_down_event(ptr: PointerEvent) {
1884 web_ensure_visible_foreground();
1885 let mut queued: bool = false;
1886 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1887 if let Ok(mut borrow) = slot.try_borrow_mut()
1888 && let Some((app, _)) = borrow.as_mut()
1889 {
1890 let wid: WindowId = app.get_window_state().get_id();
1891 app.dispatch_window_event(WindowEvent::PointerDown(wid, ptr));
1892 queued = true;
1893 }
1894 });
1895 if queued {
1896 web_mark_needs_frame();
1897 }
1898}
1899
1900#[cfg(target_arch = "wasm32")]
1906fn web_queue_pointer_up_event(ptr: PointerEvent) {
1907 let mut queued: bool = false;
1908 let mut fs_exited: bool = false;
1909 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1910 if let Ok(mut borrow) = slot.try_borrow_mut()
1911 && let Some((app, _)) = borrow.as_mut()
1912 {
1913 let was_fs: bool = app.is_immersive_fullscreen() || is_fullscreen_active();
1914 let wid: WindowId = app.get_window_state().get_id();
1915 app.dispatch_window_event(WindowEvent::PointerUp(wid, ptr));
1916 let now_fs: bool = app.is_immersive_fullscreen() || is_fullscreen_active();
1917 fs_exited = was_fs && !now_fs;
1918 queued = true;
1919 }
1920 });
1921 if fs_exited {
1922 let _: u64 = web_flush_frame(0.0);
1923 }
1924 if queued {
1925 web_mark_needs_frame();
1926 }
1927}
1928
1929#[cfg(target_arch = "wasm32")]
1935fn web_queue_pointer_cancel(pointer_id: u64) {
1936 let mut queued: bool = false;
1937 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1938 if let Ok(mut borrow) = slot.try_borrow_mut()
1939 && let Some((app, _)) = borrow.as_mut()
1940 {
1941 let wid: WindowId = app.get_window_state().get_id();
1942 app.dispatch_window_event(WindowEvent::PointerCancel(wid, pointer_id));
1943 queued = true;
1944 }
1945 });
1946 if queued {
1947 web_mark_needs_frame();
1948 }
1949}
1950
1951#[cfg(target_arch = "wasm32")]
1960fn web_queue_scroll_at(pos_x: f32, pos_y: f32, dx: f32, dy: f32) {
1961 web_ensure_visible_foreground();
1962 let mut queued: bool = false;
1963 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1964 if let Ok(mut borrow) = slot.try_borrow_mut()
1965 && let Some((app, _)) = borrow.as_mut()
1966 {
1967 let wid: WindowId = app.get_window_state().get_id();
1968 app.dispatch_window_event(WindowEvent::PointerMove(
1969 wid,
1970 PointerEvent::mouse(pos_x, pos_y),
1971 ));
1972 app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(dx, dy)));
1973 queued = true;
1974 }
1975 });
1976 if queued {
1977 web_mark_needs_frame();
1978 }
1979}
1980
1981#[cfg(target_arch = "wasm32")]
1990fn web_queue_key_down(key: &str, code_str: &str, mods: Modifiers, repeat: bool) {
1991 if WEB_IME_COMPOSING.with(Cell::get) {
1992 return;
1993 }
1994 web_ensure_visible_foreground();
1995 let ime_active: bool = WEB_IME_ACTIVE.with(Cell::get);
1996 let mut queued: bool = false;
1997 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1998 if let Ok(mut borrow) = slot.try_borrow_mut()
1999 && let Some((app, _)) = borrow.as_mut()
2000 {
2001 let wid: WindowId = app.get_window_state().get_id();
2002 let code: KeyCode = web_map_key(key, code_str);
2003 let key_ev: WindowEvent = WindowEvent::KeyDown(wid, KeyEvent::new(code, mods, repeat));
2004 app.dispatch_window_event(key_ev);
2005 if web_should_dispatch_text_input(ime_active, mods, key) {
2006 app.dispatch_window_event(WindowEvent::TextInput(wid, key.to_string()));
2007 }
2008 queued = true;
2009 }
2010 });
2011 if queued {
2012 web_mark_needs_frame();
2013 }
2014}
2015
2016#[cfg(target_arch = "wasm32")]
2022fn web_queue_text_input(text: String) {
2023 if text.is_empty() {
2024 return;
2025 }
2026 let mut queued: bool = false;
2027 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2028 if let Ok(mut borrow) = slot.try_borrow_mut()
2029 && let Some((app, _)) = borrow.as_mut()
2030 {
2031 let wid: WindowId = app.get_window_state().get_id();
2032 app.dispatch_window_event(WindowEvent::TextInput(wid, text));
2033 queued = true;
2034 }
2035 });
2036 if queued {
2037 web_mark_needs_frame();
2038 }
2039}
2040
2041#[cfg(target_arch = "wasm32")]
2048fn web_flush_ime_element(el: &HtmlElement, fallback: Option<String>) {
2049 let key: JsValue = JsValue::from_str(WEB_PROP_VALUE);
2050 let el_text: Option<String> = Reflect::get(el.as_ref(), &key)
2051 .ok()
2052 .and_then(|val: JsValue| val.as_string())
2053 .filter(|text_value: &String| !text_value.is_empty());
2054 let _: Result<bool, JsValue> = Reflect::set(el.as_ref(), &key, &JsValue::from_str(""));
2055 let committed: Option<String> =
2056 el_text.or_else(|| fallback.filter(|label_str: &String| !label_str.is_empty()));
2057 if let Some(text) = committed {
2058 web_queue_text_input(text);
2059 }
2060}
2061
2062#[cfg(target_arch = "wasm32")]
2072fn web_event_is_composing(ui_event: &Event) -> bool {
2073 Reflect::get(ui_event.as_ref(), &JsValue::from_str(WEB_PROP_IS_COMPOSING))
2074 .ok()
2075 .and_then(|val: JsValue| val.as_bool())
2076 .unwrap_or(false)
2077}
2078
2079#[cfg(target_arch = "wasm32")]
2089fn web_event_data_string(ui_event: &Event) -> Option<String> {
2090 Reflect::get(ui_event.as_ref(), &JsValue::from_str(WEB_PROP_DATA))
2091 .ok()
2092 .and_then(|val: JsValue| val.as_string())
2093 .filter(|text_value: &String| !text_value.is_empty())
2094}
2095
2096#[cfg(target_arch = "wasm32")]
2102fn web_attach_ime_proxy(doc: &Document) {
2103 let Ok(raw_el) = doc.create_element(WEB_IME_INPUT_TAG) else {
2104 return;
2105 };
2106 let el: Element = raw_el;
2107 drop(el.set_attribute(WEB_IME_ATTR_ID, WEB_IME_INPUT_ID));
2108 drop(el.set_attribute(WEB_IME_ATTR_TYPE, WEB_IME_ATTR_TEXT));
2109 drop(el.set_attribute(WEB_IME_ATTR_AUTOCOMPLETE, WEB_IME_ATTR_OFF));
2110 drop(el.set_attribute(WEB_IME_ATTR_AUTOCORRECT, WEB_IME_ATTR_OFF));
2111 drop(el.set_attribute(WEB_IME_ATTR_AUTOCAPITALIZE, WEB_IME_ATTR_OFF));
2112 drop(el.set_attribute(WEB_IME_ATTR_SPELLCHECK, WEB_IME_ATTR_FALSE));
2113 drop(el.set_attribute(WEB_IME_ATTR_ARIA_LABEL, WEB_IME_ARIA_LABEL));
2114 drop(el.set_attribute(WEB_IME_ATTR_STYLE, WEB_IME_STYLE));
2115 let Ok(html_el) = el.dyn_into::<HtmlElement>() else {
2116 return;
2117 };
2118 if let Some(body) = doc.body() {
2119 drop(body.append_child(&html_el));
2120 }
2121 let on_ime_focus: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
2122 WEB_IME_ACTIVE.with(|alpha_val: &Cell<bool>| alpha_val.set(true));
2123 }) as Box<dyn FnMut(Event)>);
2124 drop(
2125 html_el.add_event_listener_with_callback(
2126 WEB_EVENT_FOCUS,
2127 on_ime_focus.as_ref().unchecked_ref(),
2128 ),
2129 );
2130 on_ime_focus.forget();
2131 let comp_start: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
2132 WEB_IME_COMPOSING.with(|char_item: &Cell<bool>| char_item.set(true));
2133 }) as Box<dyn FnMut(Event)>);
2134 drop(html_el.add_event_listener_with_callback(
2135 WEB_EVENT_COMPOSITION_START,
2136 comp_start.as_ref().unchecked_ref(),
2137 ));
2138 comp_start.forget();
2139 let comp_update: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
2140 WEB_IME_COMPOSING.with(|color_item: &Cell<bool>| color_item.set(true));
2141 }) as Box<dyn FnMut(Event)>);
2142 drop(html_el.add_event_listener_with_callback(
2143 WEB_EVENT_COMPOSITION_UPDATE,
2144 comp_update.as_ref().unchecked_ref(),
2145 ));
2146 comp_update.forget();
2147 let comp_el: HtmlElement = html_el.clone();
2148 let comp_end: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |ui_event: Event| {
2149 WEB_IME_COMPOSING.with(|cell_item: &Cell<bool>| cell_item.set(false));
2150 let fallback: Option<String> = web_event_data_string(&ui_event);
2151 web_flush_ime_element(&comp_el, fallback);
2152 }) as Box<dyn FnMut(Event)>);
2153 drop(html_el.add_event_listener_with_callback(
2154 WEB_EVENT_COMPOSITION_END,
2155 comp_end.as_ref().unchecked_ref(),
2156 ));
2157 comp_end.forget();
2158 let inp_el: HtmlElement = html_el.clone();
2159 let on_input: Closure<dyn FnMut(Event)> =
2160 Closure::wrap(Box::new(move |dispatched_event: Event| {
2161 if !WEB_IME_COMPOSING.with(Cell::get) && !web_event_is_composing(&dispatched_event) {
2162 web_flush_ime_element(&inp_el, None);
2163 }
2164 }) as Box<dyn FnMut(Event)>);
2165 drop(
2166 html_el
2167 .add_event_listener_with_callback(WEB_EVENT_INPUT, on_input.as_ref().unchecked_ref()),
2168 );
2169 on_input.forget();
2170 let on_ime_blur: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
2171 WEB_IME_ACTIVE.with(|first_val: &Cell<bool>| first_val.set(false));
2172 WEB_IME_COMPOSING.with(|component_val: &Cell<bool>| component_val.set(false));
2173 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2174 if let Ok(mut borrow) = slot.try_borrow_mut()
2175 && let Some((app, _)) = borrow.as_mut()
2176 {
2177 let wid: WindowId = app.get_window_state().get_id();
2178 app.dispatch_window_event(WindowEvent::Ime(wid, ImeEvent::Disabled));
2179 }
2180 });
2181 }) as Box<dyn FnMut(Event)>);
2182 drop(
2183 html_el
2184 .add_event_listener_with_callback(WEB_EVENT_BLUR, on_ime_blur.as_ref().unchecked_ref()),
2185 );
2186 on_ime_blur.forget();
2187 WEB_IME_ELEMENT.with(|slot: &RefCell<Option<HtmlElement>>| {
2188 if let Ok(mut guard) = slot.try_borrow_mut() {
2189 *guard = Some(html_el);
2190 }
2191 });
2192}
2193
2194#[cfg(target_arch = "wasm32")]
2206fn web_native_action_bridge(kind: &str, arg1: &str, _arg2: &str) -> bool {
2207 if kind == NATIVE_ACTION_FULLSCREEN {
2208 if arg1 == WEB_FS_ACTION_ON {
2209 web_set_fullscreen(true);
2210 return true;
2211 }
2212 if arg1 == WEB_FS_ACTION_OFF {
2213 web_set_fullscreen(false);
2214 return true;
2215 }
2216 return false;
2217 }
2218 if kind == NATIVE_ACTION_OPEN_URL {
2219 if !is_valid_external_url(arg1) {
2220 return false;
2221 }
2222 let Some(win) = window() else {
2223 return false;
2224 };
2225 return win
2226 .open_with_url_and_target_and_features(
2227 arg1.trim(),
2228 WEB_OPEN_TARGET_BLANK,
2229 WEB_OPEN_FEATURES_SAFE,
2230 )
2231 .is_ok();
2232 }
2233 if kind != NATIVE_ACTION_IME {
2234 return false;
2235 }
2236 WEB_IME_ELEMENT.with(|slot: &RefCell<Option<HtmlElement>>| {
2237 let Ok(guard) = slot.try_borrow() else {
2238 return false;
2239 };
2240 let Some(el) = guard.as_ref() else {
2241 return false;
2242 };
2243 if arg1 == WEB_IME_ACTION_SHOW {
2244 WEB_IME_ACTIVE.with(|alpha_val: &Cell<bool>| alpha_val.set(true));
2245 let already_focused: bool = window()
2246 .and_then(|win: Window| win.document())
2247 .and_then(|doc: Document| doc.active_element())
2248 .map(|active_el: Element| active_el.id() == WEB_IME_INPUT_ID)
2249 .unwrap_or(false);
2250 if !already_focused {
2251 drop(el.focus());
2252 }
2253 true
2254 } else if arg1 == WEB_IME_ACTION_HIDE {
2255 WEB_IME_ACTIVE.with(|first_val: &Cell<bool>| first_val.set(false));
2256 WEB_IME_COMPOSING.with(|char_item: &Cell<bool>| char_item.set(false));
2257 let key: JsValue = JsValue::from_str(WEB_PROP_VALUE);
2258 let _: Result<bool, JsValue> = Reflect::set(el.as_ref(), &key, &JsValue::from_str(""));
2259 drop(el.blur());
2260 true
2261 } else {
2262 false
2263 }
2264 })
2265}
2266
2267#[cfg(target_arch = "wasm32")]
2275fn web_queue_key_up(key: &str, code_str: &str, mods: Modifiers) {
2276 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2277 if let Ok(mut borrow) = slot.try_borrow_mut()
2278 && let Some((app, _)) = borrow.as_mut()
2279 {
2280 let wid: WindowId = app.get_window_state().get_id();
2281 let code: KeyCode = web_map_key(key, code_str);
2282 app.dispatch_window_event(WindowEvent::KeyUp(wid, KeyEvent::new(code, mods, false)));
2283 }
2284 });
2285}
2286
2287#[cfg(target_arch = "wasm32")]
2297fn web_read_window_css_viewport(win: &Window) -> (f64, f64) {
2298 if let Ok(vv) = Reflect::get(win.as_ref(), &JsValue::from_str(WEB_PROP_VISUAL_VIEWPORT))
2299 && !vv.is_null()
2300 && !vv.is_undefined()
2301 {
2302 let vv_scale: f64 = Reflect::get(&vv, &JsValue::from_str(WEB_PROP_SCALE))
2303 .ok()
2304 .and_then(|item_val: JsValue| item_val.as_f64())
2305 .filter(|tex_v: &f64| tex_v.is_finite() && *tex_v > 0.0)
2306 .unwrap_or(1.0);
2307 if vv_scale <= WEB_PINCH_ZOOM_THRESHOLD {
2308 let vw: Option<f64> = Reflect::get(&vv, &JsValue::from_str(WEB_PROP_WIDTH))
2309 .ok()
2310 .and_then(|bary_v: JsValue| bary_v.as_f64())
2311 .filter(|sample_val: &f64| sample_val.is_finite() && *sample_val >= 64.0);
2312 let vh: Option<f64> = Reflect::get(&vv, &JsValue::from_str(WEB_PROP_HEIGHT))
2313 .ok()
2314 .and_then(|item_val_primary: JsValue| item_val_primary.as_f64())
2315 .filter(|item_val_secondary: &f64| {
2316 item_val_secondary.is_finite() && *item_val_secondary >= 64.0
2317 });
2318 if let (Some(width_val), Some(height_val)) = (vw, vh) {
2319 return (width_val, height_val);
2320 }
2321 }
2322 }
2323 if let Some(root) = win
2324 .document()
2325 .and_then(|doc: Document| doc.document_element())
2326 {
2327 let cw: f64 = f64::from(root.client_width());
2328 let ch: f64 = f64::from(root.client_height());
2329 if cw >= 64.0 && ch >= 64.0 {
2330 return (cw, ch);
2331 }
2332 }
2333 let weight_val: f64 = win
2334 .inner_width()
2335 .ok()
2336 .and_then(|item_val_next: JsValue| item_val_next.as_f64())
2337 .filter(|span_width: &f64| span_width.is_finite() && *span_width >= 64.0)
2338 .unwrap_or(SHOWCASE_WINDOW_WIDTH as f64);
2339 let half_extent: f64 = win
2340 .inner_height()
2341 .ok()
2342 .and_then(|item_val_alt: JsValue| item_val_alt.as_f64())
2343 .filter(|span_height: &f64| span_height.is_finite() && *span_height >= 64.0)
2344 .unwrap_or(SHOWCASE_WINDOW_HEIGHT as f64);
2345 (weight_val, half_extent)
2346}
2347
2348#[cfg(target_arch = "wasm32")]
2354fn web_query_initial_viewport() -> (f64, f64, f64, f64, f32) {
2355 let Some(win) = window() else {
2356 return (
2357 0.0,
2358 0.0,
2359 SHOWCASE_WINDOW_WIDTH as f64,
2360 SHOWCASE_WINDOW_HEIGHT as f64,
2361 1.0,
2362 );
2363 };
2364 let dpr_raw: f64 = win.device_pixel_ratio();
2365 let dpr: f32 = if dpr_raw.is_finite() && dpr_raw > 0.0 {
2366 (dpr_raw as f32).clamp(WEB_DPR_MIN, WEB_DPR_MAX)
2367 } else {
2368 1.0
2369 };
2370 let mut left: f64 = 0.0;
2371 let mut top: f64 = 0.0;
2372 let mut css_w: f64 = 0.0;
2373 let mut css_h: f64 = 0.0;
2374 if let Some(doc) = win.document()
2375 && let Ok(Some(el)) = doc.query_selector(WEB_SELECTOR_CANVAS)
2376 && let Ok(canvas) = el.dyn_into::<HtmlCanvasElement>()
2377 {
2378 let rect: DomRect = canvas.get_bounding_client_rect();
2379 left = rect.left();
2380 top = rect.top();
2381 css_w = rect.width();
2382 css_h = rect.height();
2383 }
2384 let (win_w, win_h): (f64, f64) = web_read_window_css_viewport(&win);
2385 if !css_w.is_finite() || css_w < 64.0 {
2386 css_w = win_w;
2387 }
2388 if !css_h.is_finite() || css_h < 64.0 {
2389 css_h = win_h;
2390 }
2391 (left, top, css_w, css_h, dpr)
2392}
2393
2394#[cfg(target_arch = "wasm32")]
2405fn web_refresh_cached_viewport(win: &Window, canvas: &HtmlCanvasElement) -> bool {
2406 let rect: DomRect = canvas.get_bounding_client_rect();
2407 let left: f64 = rect.left();
2408 let top: f64 = rect.top();
2409 let (win_w, win_h): (f64, f64) = web_read_window_css_viewport(win);
2410 let css_w: f64 = if rect.width().is_finite() && rect.width() >= 64.0 {
2411 rect.width()
2412 } else {
2413 win_w
2414 };
2415 let css_h: f64 = if rect.height().is_finite() && rect.height() >= 64.0 {
2416 rect.height()
2417 } else {
2418 win_h
2419 };
2420 let dpr_raw: f64 = win.device_pixel_ratio();
2421 let dpr: f32 = if dpr_raw.is_finite() && dpr_raw > 0.0 {
2422 (dpr_raw as f32).clamp(WEB_DPR_MIN, WEB_DPR_MAX)
2423 } else {
2424 1.0
2425 };
2426 let prev: (f64, f64, f64, f64, f32) = WEB_CACHED_VIEWPORT.with(Cell::get);
2427 let changed: bool = (prev.0 - left).abs() > 0.25
2428 || (prev.1 - top).abs() > 0.25
2429 || (prev.2 - css_w).abs() > 0.25
2430 || (prev.3 - css_h).abs() > 0.25
2431 || (prev.4 - dpr).abs() > 0.005;
2432 if changed {
2433 WEB_CACHED_VIEWPORT.with(|cell: &Cell<(f64, f64, f64, f64, f32)>| {
2434 cell.set((left, top, css_w, css_h, dpr));
2435 });
2436 WEB_VIEWPORT_DIRTY.with(|flag: &Cell<bool>| flag.set(true));
2437 }
2438 changed
2439}
2440
2441#[cfg(target_arch = "wasm32")]
2451fn web_apply_cached_viewport(canvas: &HtmlCanvasElement) -> bool {
2452 let (_, _, css_w, css_h, dpr): (f64, f64, f64, f64, f32) = WEB_CACHED_VIEWPORT.with(Cell::get);
2453 let dpr_f64: f64 = f64::from(dpr);
2454 let est_w: u32 = (css_w * dpr_f64)
2455 .round()
2456 .clamp(1.0, WEB_CANVAS_MAX_PHYS_DIM) as u32;
2457 let est_h: u32 = (css_h * dpr_f64)
2458 .round()
2459 .clamp(1.0, WEB_CANVAS_MAX_PHYS_DIM) as u32;
2460 let (obs_w, obs_h): (u32, u32) = WEB_OBSERVED_PHYS_SIZE.with(Cell::get);
2461 let has_obs: bool = obs_w >= 64 && obs_h >= 64;
2462 let matches_obs: bool = has_obs && obs_w.abs_diff(est_w) <= 2 && obs_h.abs_diff(est_h) <= 2;
2463 let (phys_w, phys_h): (u32, u32) = if matches_obs {
2464 (obs_w, obs_h)
2465 } else {
2466 (est_w, est_h)
2467 };
2468 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2469 let Ok(mut borrow) = slot.try_borrow_mut() else {
2470 return false;
2471 };
2472 let Some((app, _)) = borrow.as_mut() else {
2473 return false;
2474 };
2475 let ws: WindowState = app.get_window_state();
2476 let size_diff: bool = ws.get_physical_width() != phys_w
2477 || ws.get_physical_height() != phys_h
2478 || (ws.get_scale_factor() - dpr).abs() > 0.005
2479 || canvas.width() != phys_w
2480 || canvas.height() != phys_h;
2481 if !size_diff {
2482 return false;
2483 }
2484 if canvas.width() != phys_w {
2485 canvas.set_width(phys_w);
2486 }
2487 if canvas.height() != phys_h {
2488 canvas.set_height(phys_h);
2489 }
2490 app.set_exact_physical_viewport(phys_w, phys_h, dpr);
2491 true
2492 })
2493}
2494
2495#[cfg(target_arch = "wasm32")]
2501fn web_sync_safe_area() -> bool {
2502 let measured: SafeAreaInsets = web_query_safe_area_insets();
2503 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2504 let Ok(mut borrow) = slot.try_borrow_mut() else {
2505 return false;
2506 };
2507 let Some((app, _)) = borrow.as_mut() else {
2508 return false;
2509 };
2510 let effective: SafeAreaInsets = if app.is_immersive_fullscreen() {
2511 SafeAreaInsets::default()
2512 } else {
2513 measured
2514 };
2515 let current: SafeAreaInsets = app.get_context().get_safe_area().get_untracked();
2516 if current == effective {
2517 return false;
2518 }
2519 let wid: WindowId = app.get_window_state().get_id();
2520 app.dispatch_window_event(WindowEvent::SafeAreaChanged(wid, effective));
2521 true
2522 })
2523}
2524
2525#[cfg(target_arch = "wasm32")]
2531fn web_report_host_refresh_rate(measured_hz: f32) {
2532 let mut needs_redraw: bool = false;
2533 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2534 if let Ok(mut borrow) = slot.try_borrow_mut()
2535 && let Some((app, _)) = borrow.as_mut()
2536 {
2537 let prev_fps: f32 = app.get_context().get_live_fps().get_untracked();
2538 app.report_host_refresh_rate(measured_hz);
2539 let next_fps: f32 = app.get_context().get_live_fps().get_untracked();
2540 if (next_fps - prev_fps).abs() >= 1.0 {
2541 needs_redraw = true;
2542 }
2543 }
2544 });
2545 if needs_redraw {
2546 web_mark_needs_frame();
2547 }
2548}
2549
2550#[cfg(target_arch = "wasm32")]
2560fn web_flush_frame(dt_secs: f32) -> u64 {
2561 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2562 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2563 Ok(guard) => guard,
2564 Err(_) => return 0,
2565 };
2566 let Some((app, state)) = borrow.as_mut() else {
2567 return 0;
2568 };
2569 let coord: ShowcaseWebDualCanvasCoordinator = web_dual_canvas_snapshot();
2570 state.sync_adaptive_from_web_coordinator(app, &coord);
2571 let hash: u64 = app
2572 .step_game_frame(dt_secs)
2573 .map(|stats: FrameStats| stats.get_frame_hash())
2574 .unwrap_or(0);
2575 state.sync_adaptive_from_web_coordinator(app, &coord);
2576 let pump: bool = app.should_pump_frames();
2577 WEB_SHOULD_PUMP.with(|flag: &Cell<bool>| flag.set(pump));
2578 hash
2579 })
2580}
2581
2582#[cfg(target_arch = "wasm32")]
2588#[wasm_bindgen]
2589pub fn euv_example_web_start() -> u64 {
2590 reset_reactive_runtime();
2591 register_frame_wakeup(web_mark_needs_frame);
2592 let (left, top, css_w, css_h, dpr): (f64, f64, f64, f64, f32) = web_query_initial_viewport();
2593 WEB_CACHED_VIEWPORT.with(|cell: &Cell<(f64, f64, f64, f64, f32)>| {
2594 cell.set((left, top, css_w, css_h, dpr));
2595 });
2596 WEB_VIEWPORT_DIRTY.with(|flag: &Cell<bool>| flag.set(false));
2597 let logical_w: u32 = css_w.round().max(64.0) as u32;
2598 let logical_h: u32 = css_h.round().max(64.0) as u32;
2599 let phys_w: u32 = (css_w * f64::from(dpr))
2600 .round()
2601 .clamp(1.0, WEB_CANVAS_MAX_PHYS_DIM) as u32;
2602 let phys_h: u32 = (css_h * f64::from(dpr))
2603 .round()
2604 .clamp(1.0, WEB_CANVAS_MAX_PHYS_DIM) as u32;
2605 if let Some(win) = window()
2606 && let Some(doc) = win.document()
2607 && let Ok(Some(el)) = doc.query_selector(WEB_SELECTOR_CANVAS)
2608 && let Ok(canvas) = el.dyn_into::<HtmlCanvasElement>()
2609 {
2610 if canvas.width() != phys_w {
2611 canvas.set_width(phys_w);
2612 }
2613 if canvas.height() != phys_h {
2614 canvas.set_height(phys_h);
2615 }
2616 }
2617 match create_showcase_app_with_viewport(false, RenderMode::Auto, logical_w, logical_h, dpr) {
2618 Ok((mut app, state)) => {
2619 app.set_exact_physical_viewport(phys_w, phys_h, dpr);
2620 if let Some(win) = window()
2621 && let Ok(hash_str) = win.location().hash()
2622 {
2623 let initial: String =
2624 resolve_web_hash_route(&hash_str, Some(state.get_dynamic_hub()));
2625 state.get_router().replace(&initial);
2626 let _: bool = state.get_route().set_if_changed(initial);
2627 }
2628 let route_watch: Signal<String> = state.get_route();
2629 let hub_watch: DynamicUpdateHub = state.get_dynamic_hub().clone();
2630 let (hash_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
2631 Effect::new(move || {
2632 let text_value: String = route_watch.get();
2633 if WEB_SYNCING_FROM_HISTORY.with(Cell::get) {
2634 return;
2635 }
2636 if let Some(win) = window() {
2637 let cur_raw: String = win.location().hash().unwrap_or_default();
2638 let cur_norm: String = resolve_web_hash_route(&cur_raw, Some(&hub_watch));
2639 if cur_norm != text_value {
2640 let target_hash: String = format!("#{text_value}");
2641 let _: Result<(), JsValue> = win.location().set_hash(&target_hash);
2642 }
2643 }
2644 })
2645 });
2646 let root_id: NodeId = app
2647 .get_scene()
2648 .with_read(SceneTree::get_root, NodeId::default());
2649 app.get_scene().with_write(
2650 |tree: &mut SceneTree| {
2651 tree.attach_scope(root_id, hash_scope);
2652 },
2653 (),
2654 );
2655 let hash: u64 = app
2656 .step_frame()
2657 .map(|stats: FrameStats| stats.get_frame_hash())
2658 .unwrap_or(0);
2659 let coord: ShowcaseWebDualCanvasCoordinator = web_dual_canvas_snapshot();
2660 state.sync_adaptive_from_web_coordinator(&mut app, &coord);
2661 let pump: bool = app.should_pump_frames();
2662 WEB_SHOULD_PUMP.with(|flag: &Cell<bool>| flag.set(pump));
2663 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2664 if let Ok(mut borrow) = slot.try_borrow_mut() {
2665 *borrow = Some((app, state));
2666 }
2667 });
2668 hash
2669 }
2670 Err(_) => 0,
2671 }
2672}
2673
2674#[cfg(target_arch = "wasm32")]
2684#[wasm_bindgen]
2685pub fn euv_example_render_route(route: &str) -> u64 {
2686 let has_runtime: bool = WEB_SHOWCASE_RUNTIME.with(
2687 |slot: &RefCell<Option<(App, ShowcaseState)>>| matches!(slot.try_borrow(), Ok(guard) if guard.is_some()),
2688 );
2689 if !has_runtime {
2690 let _: u64 = euv_example_web_start();
2691 }
2692 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2693 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2694 Ok(guard) => guard,
2695 Err(_) => return 0,
2696 };
2697 let Some((app, state)) = borrow.as_mut() else {
2698 return 0;
2699 };
2700 let _: bool = state.get_route().set_if_changed(route.to_string());
2701 app.step_frame()
2702 .map(|stats: FrameStats| stats.get_frame_hash())
2703 .unwrap_or(0)
2704 })
2705}
2706
2707#[cfg(target_arch = "wasm32")]
2718#[wasm_bindgen]
2719pub fn euv_web_pointer_move(pos_x: f32, pos_y: f32) -> u64 {
2720 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2721 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2722 Ok(guard) => guard,
2723 Err(_) => return 0,
2724 };
2725 let Some((app, _)) = borrow.as_mut() else {
2726 return 0;
2727 };
2728 let wid: WindowId = app.get_window_state().get_id();
2729 app.dispatch_window_event(WindowEvent::PointerMove(
2730 wid,
2731 PointerEvent::mouse(pos_x, pos_y),
2732 ));
2733 app.step_frame()
2734 .map(|stats: FrameStats| stats.get_frame_hash())
2735 .unwrap_or(0)
2736 })
2737}
2738
2739#[cfg(target_arch = "wasm32")]
2750#[wasm_bindgen]
2751pub fn euv_web_pointer_down(pos_x: f32, pos_y: f32) -> u64 {
2752 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2753 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2754 Ok(guard) => guard,
2755 Err(_) => return 0,
2756 };
2757 let Some((app, _)) = borrow.as_mut() else {
2758 return 0;
2759 };
2760 let wid: WindowId = app.get_window_state().get_id();
2761 app.dispatch_window_event(WindowEvent::PointerDown(
2762 wid,
2763 PointerEvent::mouse(pos_x, pos_y),
2764 ));
2765 app.step_frame()
2766 .map(|stats: FrameStats| stats.get_frame_hash())
2767 .unwrap_or(0)
2768 })
2769}
2770
2771#[cfg(target_arch = "wasm32")]
2782#[wasm_bindgen]
2783pub fn euv_web_pointer_up(pos_x: f32, pos_y: f32) -> u64 {
2784 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2785 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2786 Ok(guard) => guard,
2787 Err(_) => return 0,
2788 };
2789 let Some((app, _)) = borrow.as_mut() else {
2790 return 0;
2791 };
2792 let wid: WindowId = app.get_window_state().get_id();
2793 app.dispatch_window_event(WindowEvent::PointerUp(
2794 wid,
2795 PointerEvent::mouse(pos_x, pos_y),
2796 ));
2797 app.step_frame()
2798 .map(|stats: FrameStats| stats.get_frame_hash())
2799 .unwrap_or(0)
2800 })
2801}
2802
2803#[cfg(target_arch = "wasm32")]
2814#[wasm_bindgen]
2815pub fn euv_web_scroll(dx: f32, dy: f32) -> u64 {
2816 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2817 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2818 Ok(guard) => guard,
2819 Err(_) => return 0,
2820 };
2821 let Some((app, _)) = borrow.as_mut() else {
2822 return 0;
2823 };
2824 let wid: WindowId = app.get_window_state().get_id();
2825 app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(dx, dy)));
2826 app.step_frame()
2827 .map(|stats: FrameStats| stats.get_frame_hash())
2828 .unwrap_or(0)
2829 })
2830}
2831
2832#[cfg(target_arch = "wasm32")]
2842#[wasm_bindgen]
2843pub fn euv_web_key_down(key: &str) -> u64 {
2844 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2845 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2846 Ok(guard) => guard,
2847 Err(_) => return 0,
2848 };
2849 let Some((app, state)) = borrow.as_mut() else {
2850 return 0;
2851 };
2852 let wid: WindowId = app.get_window_state().get_id();
2853 let code: KeyCode = match key {
2854 WEB_KEY_ENTER => KeyCode::Enter,
2855 WEB_KEY_BACKSPACE => KeyCode::Backspace,
2856 WEB_KEY_DELETE => KeyCode::Delete,
2857 WEB_KEY_ESCAPE => KeyCode::Escape,
2858 WEB_KEY_TAB => KeyCode::Tab,
2859 WEB_KEY_SPACE => KeyCode::Space,
2860 WEB_KEY_ARROW_LEFT => KeyCode::ArrowLeft,
2861 WEB_KEY_ARROW_RIGHT => KeyCode::ArrowRight,
2862 WEB_KEY_ARROW_UP => KeyCode::ArrowUp,
2863 WEB_KEY_ARROW_DOWN => KeyCode::ArrowDown,
2864 other => other
2865 .chars()
2866 .next()
2867 .map(KeyCode::Character)
2868 .unwrap_or(KeyCode::Unknown),
2869 };
2870 let key_ev: WindowEvent =
2871 WindowEvent::KeyDown(wid, KeyEvent::new(code, Modifiers::default(), false));
2872 state.get_game_host().ingest_event(&key_ev);
2873 app.dispatch_window_event(key_ev);
2874 if key.chars().count() == 1 {
2875 app.dispatch_window_event(WindowEvent::TextInput(wid, key.to_string()));
2876 }
2877 app.step_frame()
2878 .map(|stats: FrameStats| stats.get_frame_hash())
2879 .unwrap_or(0)
2880 })
2881}
2882
2883#[cfg(target_arch = "wasm32")]
2893#[wasm_bindgen]
2894pub fn euv_web_tick(dt_secs: f32) -> u64 {
2895 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2896 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2897 Ok(guard) => guard,
2898 Err(_) => return 0,
2899 };
2900 let Some((app, state)) = borrow.as_mut() else {
2901 return 0;
2902 };
2903 if !app.should_pump_frames() {
2904 return app.get_renderer().get_last_stats().get_frame_hash();
2905 }
2906 let cur_route: String = state.get_route().get_untracked();
2907 let on_game: bool =
2908 cur_route == ROUTE_GAME || cur_route == ROUTE_GAME_3D || cur_route == ROUTE_WATER;
2909 if on_game || app.has_active_animations() {
2910 return app
2911 .step_game_frame(dt_secs)
2912 .map(|stats: FrameStats| stats.get_frame_hash())
2913 .unwrap_or(0);
2914 }
2915 app.get_renderer().get_last_stats().get_frame_hash()
2916 })
2917}
2918
2919#[cfg(target_arch = "wasm32")]
2931#[wasm_bindgen]
2932pub fn euv_web_resize(width: u32, height: u32, dpr: f32) -> u64 {
2933 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2934 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2935 Ok(guard) => guard,
2936 Err(_) => return 0,
2937 };
2938 let Some((app, _)) = borrow.as_mut() else {
2939 return 0;
2940 };
2941 let width_val: u32 = width.max(64);
2942 let height_val: u32 = height.max(64);
2943 let scale: f32 = if dpr.is_finite() && dpr > 0.0 {
2944 dpr.clamp(WEB_DPR_MIN, WEB_DPR_MAX)
2945 } else {
2946 1.0
2947 };
2948 let phys_w: u32 = ((width_val as f64) * (scale as f64))
2949 .round()
2950 .clamp(1.0, WEB_CANVAS_MAX_PHYS_DIM) as u32;
2951 let phys_h: u32 = ((height_val as f64) * (scale as f64))
2952 .round()
2953 .clamp(1.0, WEB_CANVAS_MAX_PHYS_DIM) as u32;
2954 WEB_OBSERVED_PHYS_SIZE.with(|cell: &Cell<(u32, u32)>| cell.set((0, 0)));
2955 let (prev_l, prev_t, _, _, _): (f64, f64, f64, f64, f32) =
2956 WEB_CACHED_VIEWPORT.with(Cell::get);
2957 WEB_CACHED_VIEWPORT.with(|cell: &Cell<(f64, f64, f64, f64, f32)>| {
2958 cell.set((
2959 prev_l,
2960 prev_t,
2961 f64::from(width_val),
2962 f64::from(height_val),
2963 scale,
2964 ));
2965 });
2966 WEB_VIEWPORT_DIRTY.with(|flag: &Cell<bool>| flag.set(false));
2967 if let Some(win) = window()
2968 && let Some(doc) = win.document()
2969 && let Ok(Some(el)) = doc.query_selector(WEB_SELECTOR_CANVAS)
2970 && let Ok(canvas) = el.dyn_into::<HtmlCanvasElement>()
2971 {
2972 if canvas.width() != phys_w {
2973 canvas.set_width(phys_w);
2974 }
2975 if canvas.height() != phys_h {
2976 canvas.set_height(phys_h);
2977 }
2978 }
2979 app.set_exact_physical_viewport(phys_w, phys_h, scale);
2980 app.step_frame()
2981 .map(|stats: FrameStats| stats.get_frame_hash())
2982 .unwrap_or(0)
2983 })
2984}
2985
2986#[cfg(any(debug_assertions, test))]
2998#[must_use]
2999pub fn dispatch_automation_uri(app: &mut App, state: &ShowcaseState, uri: &str) -> Option<String> {
3000 let hooks: AiAppHooks = state.build_ai_hooks();
3001 AiSchemaProtocol::handle_uri_with_hooks(app, uri, Some(&hooks))
3002}
3003
3004#[cfg(all(debug_assertions, target_arch = "wasm32"))]
3010fn web_attach_dev_automation_bridge(win: &Window) {
3011 let on_json: Closure<dyn FnMut(String) -> String> =
3012 Closure::wrap(Box::new(|req_json: String| euv_dev_ai_schema(&req_json))
3013 as Box<dyn FnMut(String) -> String>);
3014 let _: Result<bool, JsValue> = Reflect::set(
3015 win.as_ref(),
3016 &JsValue::from_str(WEB_PROP_EUV_AUTOMATION),
3017 on_json.as_ref(),
3018 );
3019 on_json.forget();
3020 let on_uri: Closure<dyn FnMut(String) -> String> =
3021 Closure::wrap(
3022 Box::new(|uri: String| euv_dev_ai_uri(&uri)) as Box<dyn FnMut(String) -> String>
3023 );
3024 let _: Result<bool, JsValue> = Reflect::set(
3025 win.as_ref(),
3026 &JsValue::from_str(WEB_PROP_EUV_AUTOMATION_URI),
3027 on_uri.as_ref(),
3028 );
3029 on_uri.forget();
3030}
3031
3032#[cfg(all(debug_assertions, target_arch = "wasm32"))]
3042#[wasm_bindgen]
3043pub fn euv_dev_ai_schema(request_json: &str) -> String {
3044 let out: String = WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
3045 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
3046 Ok(guard) => guard,
3047 Err(_) => return String::new(),
3048 };
3049 let Some((app, state)) = borrow.as_mut() else {
3050 return String::new();
3051 };
3052 let hooks: AiAppHooks = state.build_ai_hooks();
3053 AiSchemaProtocol::handle_json_with_hooks(app, request_json, Some(&hooks))
3054 });
3055 web_mark_needs_frame();
3056 out
3057}
3058
3059#[cfg(all(debug_assertions, target_arch = "wasm32"))]
3069#[wasm_bindgen]
3070pub fn euv_dev_ai_uri(uri: &str) -> String {
3071 let out: String = WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
3072 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
3073 Ok(guard) => guard,
3074 Err(_) => return String::new(),
3075 };
3076 let Some((app, state)) = borrow.as_mut() else {
3077 return String::new();
3078 };
3079 let hooks: AiAppHooks = state.build_ai_hooks();
3080 AiSchemaProtocol::handle_uri_with_hooks(app, uri, Some(&hooks)).unwrap_or_default()
3081 });
3082 web_mark_needs_frame();
3083 out
3084}
3085
3086#[cfg(target_arch = "wasm32")]
3092#[wasm_bindgen]
3093pub fn euv_web_current_route() -> String {
3094 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
3095 match slot.try_borrow() {
3096 Ok(guard) => guard
3097 .as_ref()
3098 .map(|(_, state): &(App, ShowcaseState)| state.get_route().get_untracked())
3099 .unwrap_or_default(),
3100 Err(_) => String::new(),
3101 }
3102 })
3103}
3104
3105#[cfg(target_arch = "wasm32")]
3115fn host_json_escape(raw: &str) -> String {
3116 let mut out: String = String::with_capacity(raw.len() + 8);
3117 for ch in raw.chars() {
3118 match ch {
3119 '"' => out.push_str("\\\""),
3120 '\\' => out.push_str("\\\\"),
3121 '\n' => out.push_str("\\n"),
3122 '\r' => out.push_str("\\r"),
3123 '\t' => out.push_str("\\t"),
3124 char_item if (char_item as u32) < 0x20 => out.push(' '),
3125 color_item => out.push(color_item),
3126 }
3127 }
3128 out
3129}
3130
3131#[cfg(target_arch = "wasm32")]
3137fn host_push_command_json(cmd_json: String) {
3138 HOST_OUTBOUND_COMMANDS.with(|queue: &RefCell<Vec<String>>| {
3139 if let Ok(mut borrow) = queue.try_borrow_mut() {
3140 borrow.push(cmd_json);
3141 }
3142 });
3143}
3144
3145#[cfg(target_arch = "wasm32")]
3157fn host_native_action_bridge(kind: &str, arg1: &str, arg2: &str) -> bool {
3158 if kind == NATIVE_ACTION_CLIPBOARD {
3159 let escaped: String = host_json_escape(arg2);
3160 host_push_command_json(format!(
3161 "{{\"kind\":\"{HOST_CMD_SET_CLIPBOARD}\",\"value\":\"{escaped}\"}}"
3162 ));
3163 return true;
3164 }
3165 if kind == NATIVE_ACTION_IME {
3166 let enabled: bool = arg1 == WEB_IME_ACTION_SHOW;
3167 let rect_escaped: String = host_json_escape(arg2);
3168 host_push_command_json(format!(
3169 "{{\"kind\":\"{HOST_CMD_SHOW_KEYBOARD}\",\"enabled\":{enabled},\"rect\":\"{rect_escaped}\"}}"
3170 ));
3171 return true;
3172 }
3173 if kind == NATIVE_ACTION_HAPTIC {
3174 host_push_command_json(format!("{{\"kind\":\"{HOST_CMD_VIBRATE_SHORT}\"}}"));
3175 return true;
3176 }
3177 if kind == NATIVE_ACTION_OPEN_URL {
3178 if !is_valid_external_url(arg1) {
3179 return false;
3180 }
3181 let escaped: String = host_json_escape(arg1.trim());
3182 host_push_command_json(format!(
3183 "{{\"kind\":\"{HOST_CMD_OPEN_URL}\",\"url\":\"{escaped}\"}}"
3184 ));
3185 return true;
3186 }
3187 if kind == NATIVE_ACTION_TOAST || kind == NATIVE_ACTION_NOTIFY {
3188 let msg: &str = if !arg2.is_empty() { arg2 } else { arg1 };
3189 let escaped: String = host_json_escape(msg);
3190 host_push_command_json(format!(
3191 "{{\"kind\":\"{HOST_CMD_SHOW_TOAST}\",\"message\":\"{escaped}\"}}"
3192 ));
3193 return true;
3194 }
3195 if kind == NATIVE_ACTION_FULLSCREEN {
3196 let enabled: bool = arg1 == WEB_FS_ACTION_ON;
3197 host_push_command_json(format!(
3198 "{{\"kind\":\"{HOST_CMD_SET_FULLSCREEN}\",\"enabled\":{enabled}}}"
3199 ));
3200 return true;
3201 }
3202 if kind == NATIVE_ACTION_EXIT {
3203 host_push_command_json(format!(
3204 "{{\"kind\":\"{HOST_CMD_NAVIGATE_BACK}\",\"delta\":1}}"
3205 ));
3206 return true;
3207 }
3208 let k_esc: String = host_json_escape(kind);
3209 let a1_esc: String = host_json_escape(arg1);
3210 let a2_esc: String = host_json_escape(arg2);
3211 host_push_command_json(format!(
3212 "{{\"kind\":\"{k_esc}\",\"arg1\":\"{a1_esc}\",\"arg2\":\"{a2_esc}\"}}"
3213 ));
3214 true
3215}
3216
3217#[cfg(target_arch = "wasm32")]
3219fn host_mark_dirty() {
3220 HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
3221 if let Ok(mut borrow) = slot.try_borrow_mut()
3222 && let Some(runtime_ref) = borrow.as_mut()
3223 {
3224 runtime_ref.set_dirty(true);
3225 }
3226 });
3227}
3228
3229#[cfg(target_arch = "wasm32")]
3236fn host_sync_dirty_rect(runtime_ref: &mut HostCanvasRuntime, force_full: bool) {
3237 let (phys_w, phys_h): (u32, u32) = runtime_ref
3238 .get_app()
3239 .get_renderer()
3240 .framebuffer()
3241 .map(|target_framebuffer: &Framebuffer| {
3242 (
3243 target_framebuffer.get_width(),
3244 target_framebuffer.get_height(),
3245 )
3246 })
3247 .unwrap_or((0, 0));
3248 if phys_w == 0 || phys_h == 0 {
3249 runtime_ref
3250 .set_dirty_x(0)
3251 .set_dirty_y(0)
3252 .set_dirty_w(0)
3253 .set_dirty_h(0);
3254 return;
3255 }
3256 let damage: DamageRegion = runtime_ref.get_app().last_frame_damage();
3257 if force_full || runtime_ref.get_force_full_dirty() || damage.get_full_damage() {
3258 runtime_ref
3259 .set_force_full_dirty(false)
3260 .set_dirty_x(0)
3261 .set_dirty_y(0)
3262 .set_dirty_w(phys_w)
3263 .set_dirty_h(phys_h);
3264 return;
3265 }
3266 let rects: Vec<PixelDirtyRect> = damage_region_to_pixel_dirty_rects(damage, phys_w, phys_h);
3267 if rects.is_empty() {
3268 runtime_ref
3269 .set_dirty_x(0)
3270 .set_dirty_y(0)
3271 .set_dirty_w(phys_w)
3272 .set_dirty_h(phys_h);
3273 return;
3274 }
3275 let mut min_x: u32 = phys_w;
3276 let mut min_y: u32 = phys_h;
3277 let mut max_x: u32 = 0;
3278 let mut max_y: u32 = 0;
3279 for rect in rects.iter() {
3280 let rx: u32 = rect.get_x();
3281 let ry: u32 = rect.get_y();
3282 let rx2: u32 = rx.saturating_add(rect.get_width()).min(phys_w);
3283 let ry2: u32 = ry.saturating_add(rect.get_height()).min(phys_h);
3284 if rx < min_x {
3285 min_x = rx;
3286 }
3287 if ry < min_y {
3288 min_y = ry;
3289 }
3290 if rx2 > max_x {
3291 max_x = rx2;
3292 }
3293 if ry2 > max_y {
3294 max_y = ry2;
3295 }
3296 }
3297 if max_x <= min_x || max_y <= min_y {
3298 runtime_ref
3299 .set_dirty_x(0)
3300 .set_dirty_y(0)
3301 .set_dirty_w(phys_w)
3302 .set_dirty_h(phys_h);
3303 } else {
3304 runtime_ref
3305 .set_dirty_x(min_x)
3306 .set_dirty_y(min_y)
3307 .set_dirty_w(max_x - min_x)
3308 .set_dirty_h(max_y - min_y);
3309 }
3310}
3311
3312#[cfg(target_arch = "wasm32")]
3328#[wasm_bindgen]
3329pub fn euv_host_init(
3330 host_kind: u32,
3331 vendor: &str,
3332 logical_w: u32,
3333 logical_h: u32,
3334 dpr: f32,
3335 safe_top: f32,
3336 safe_bottom: f32,
3337) -> u64 {
3338 let platform_kind: PlatformKind = match host_kind {
3339 2 => PlatformKind::QuickApp,
3340 3 => PlatformKind::Wearable,
3341 _ => PlatformKind::MiniApp,
3342 };
3343 let clean_w: u32 = logical_w.max(HOST_MIN_VIEWPORT_DIM);
3344 let clean_h: u32 = logical_h.max(HOST_MIN_VIEWPORT_DIM);
3345 let clean_dpr: f32 = if dpr.is_finite() && dpr > 0.0 {
3346 dpr.clamp(0.5, 4.5)
3347 } else {
3348 2.0
3349 };
3350 let safe_area: SafeAreaInsets = SafeAreaInsets::new(
3351 if safe_top.is_finite() {
3352 safe_top.max(0.0)
3353 } else {
3354 0.0
3355 },
3356 0.0,
3357 if safe_bottom.is_finite() {
3358 safe_bottom.max(0.0)
3359 } else {
3360 0.0
3361 },
3362 0.0,
3363 );
3364 HOST_OUTBOUND_COMMANDS.with(|queue: &RefCell<Vec<String>>| {
3365 if let Ok(mut borrow) = queue.try_borrow_mut() {
3366 borrow.clear();
3367 }
3368 });
3369 register_native_action_bridge(host_native_action_bridge);
3370 register_frame_wakeup(host_mark_dirty);
3371 match create_showcase_app_for_platform_with_viewport(
3372 platform_kind,
3373 RenderMode::Software,
3374 clean_w,
3375 clean_h,
3376 clean_dpr,
3377 safe_area,
3378 ) {
3379 Ok((mut app, state)) => {
3380 app.get_mut_renderer()
3381 .get_mut_software()
3382 .set_font_provider(NativeSystemFont::system());
3383 let hash: u64 = app
3384 .step_frame()
3385 .map(|stats: FrameStats| stats.get_frame_hash())
3386 .unwrap_or(0);
3387 let vendor_name: String = if vendor.trim().is_empty() {
3388 HOST_DEFAULT_VENDOR.to_string()
3389 } else {
3390 vendor.trim().to_string()
3391 };
3392 let mut runtime: HostCanvasRuntime = HostCanvasRuntime {
3393 app,
3394 state,
3395 touch_tracker: TouchPointerTracker::default(),
3396 vendor: vendor_name,
3397 platform_kind,
3398 logical_width: clean_w,
3399 logical_height: clean_h,
3400 dpr: clean_dpr,
3401 paused: false,
3402 ambient: false,
3403 dirty: false,
3404 force_full_dirty: true,
3405 dirty_x: 0,
3406 dirty_y: 0,
3407 dirty_w: 0,
3408 dirty_h: 0,
3409 frame_count: 1,
3410 last_frame_hash: hash,
3411 crown_remainder: 0.0,
3412 };
3413 host_sync_dirty_rect(&mut runtime, true);
3414 HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
3415 if let Ok(mut borrow) = slot.try_borrow_mut() {
3416 *borrow = Some(runtime);
3417 }
3418 });
3419 hash
3420 }
3421 Err(_) => 0,
3422 }
3423}
3424
3425#[cfg(target_arch = "wasm32")]
3436#[wasm_bindgen]
3437pub fn euv_host_step(dt_secs: f32, force_render: bool) -> u32 {
3438 HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
3439 let mut borrow: RefMut<'_, Option<HostCanvasRuntime>> = match slot.try_borrow_mut() {
3440 Ok(guard) => guard,
3441 Err(_) => return 0,
3442 };
3443 let Some(runtime_ref) = borrow.as_mut() else {
3444 return 0;
3445 };
3446 if runtime_ref.get_paused() && !force_render {
3447 return 0;
3448 }
3449 let dt: f32 = if dt_secs.is_finite() && dt_secs > 0.0 {
3450 dt_secs.clamp(0.001, 0.1)
3451 } else {
3452 1.0 / 60.0
3453 };
3454 let cur_route: String = runtime_ref.get_state().get_route().get_untracked();
3455 let on_2d_or_3d_game: bool = cur_route == ROUTE_GAME || cur_route == ROUTE_GAME_3D;
3456 let on_game: bool = on_2d_or_3d_game || cur_route == ROUTE_WATER;
3457 let animating: bool = runtime_ref.get_app().has_active_animations();
3458 let host_needs_frame: bool = force_render || runtime_ref.get_dirty();
3459 let active_motion: bool = on_game || animating;
3460 let needs_frame: bool = host_needs_frame || active_motion;
3461 if !needs_frame {
3462 return 0;
3463 }
3464 let res: Result<FrameStats, PlatformError> = if on_game || animating {
3465 runtime_ref.get_mut_app().step_game_frame(dt)
3466 } else {
3467 runtime_ref.get_mut_app().step_frame()
3468 };
3469 match res {
3470 Ok(stats) => {
3471 runtime_ref.set_dirty(false);
3472 runtime_ref.set_frame_count(runtime_ref.get_frame_count().saturating_add(1));
3473 runtime_ref.set_last_frame_hash(stats.get_frame_hash());
3474 host_sync_dirty_rect(runtime_ref, force_render);
3475 1
3476 }
3477 Err(_) => 0,
3478 }
3479 })
3480}
3481
3482#[cfg(target_arch = "wasm32")]
3488#[wasm_bindgen]
3489pub fn euv_host_framebuffer_ptr() -> u32 {
3490 HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
3491 slot.try_borrow()
3492 .ok()
3493 .and_then(|guard: Ref<'_, Option<HostCanvasRuntime>>| {
3494 guard.as_ref().and_then(|runtime_ref: &HostCanvasRuntime| {
3495 runtime_ref.get_app().get_renderer().framebuffer().map(
3496 |target_framebuffer: &Framebuffer| {
3497 target_framebuffer.get_pixels().as_ptr() as usize as u32
3498 },
3499 )
3500 })
3501 })
3502 .unwrap_or(0)
3503 })
3504}
3505
3506#[cfg(target_arch = "wasm32")]
3512#[wasm_bindgen]
3513pub fn euv_host_framebuffer_len() -> u32 {
3514 HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
3515 slot.try_borrow()
3516 .ok()
3517 .and_then(|guard: Ref<'_, Option<HostCanvasRuntime>>| {
3518 guard.as_ref().and_then(|runtime_ref: &HostCanvasRuntime| {
3519 runtime_ref.get_app().get_renderer().framebuffer().map(
3520 |target_framebuffer: &Framebuffer| {
3521 target_framebuffer.get_pixels().len() as u32
3522 },
3523 )
3524 })
3525 })
3526 .unwrap_or(0)
3527 })
3528}
3529
3530#[cfg(target_arch = "wasm32")]
3536#[wasm_bindgen]
3537pub fn euv_host_framebuffer_width() -> u32 {
3538 HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
3539 slot.try_borrow()
3540 .ok()
3541 .and_then(|guard: Ref<'_, Option<HostCanvasRuntime>>| {
3542 guard.as_ref().and_then(|runtime_ref: &HostCanvasRuntime| {
3543 runtime_ref
3544 .get_app()
3545 .get_renderer()
3546 .framebuffer()
3547 .map(Framebuffer::get_width)
3548 })
3549 })
3550 .unwrap_or(0)
3551 })
3552}
3553
3554#[cfg(target_arch = "wasm32")]
3560#[wasm_bindgen]
3561pub fn euv_host_framebuffer_height() -> u32 {
3562 HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
3563 slot.try_borrow()
3564 .ok()
3565 .and_then(|guard: Ref<'_, Option<HostCanvasRuntime>>| {
3566 guard.as_ref().and_then(|runtime_ref: &HostCanvasRuntime| {
3567 runtime_ref
3568 .get_app()
3569 .get_renderer()
3570 .framebuffer()
3571 .map(Framebuffer::get_height)
3572 })
3573 })
3574 .unwrap_or(0)
3575 })
3576}
3577
3578#[cfg(target_arch = "wasm32")]
3584#[wasm_bindgen]
3585pub fn euv_host_dirty_x() -> u32 {
3586 HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
3587 slot.try_borrow()
3588 .ok()
3589 .and_then(|guard: Ref<'_, Option<HostCanvasRuntime>>| {
3590 guard.as_ref().map(HostCanvasRuntime::get_dirty_x)
3591 })
3592 .unwrap_or(0)
3593 })
3594}
3595
3596#[cfg(target_arch = "wasm32")]
3602#[wasm_bindgen]
3603pub fn euv_host_dirty_y() -> u32 {
3604 HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
3605 slot.try_borrow()
3606 .ok()
3607 .and_then(|guard: Ref<'_, Option<HostCanvasRuntime>>| {
3608 guard.as_ref().map(HostCanvasRuntime::get_dirty_y)
3609 })
3610 .unwrap_or(0)
3611 })
3612}
3613
3614#[cfg(target_arch = "wasm32")]
3620#[wasm_bindgen]
3621pub fn euv_host_dirty_w() -> u32 {
3622 HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
3623 slot.try_borrow()
3624 .ok()
3625 .and_then(|guard: Ref<'_, Option<HostCanvasRuntime>>| {
3626 guard.as_ref().map(HostCanvasRuntime::get_dirty_w)
3627 })
3628 .unwrap_or(0)
3629 })
3630}
3631
3632#[cfg(target_arch = "wasm32")]
3638#[wasm_bindgen]
3639pub fn euv_host_dirty_h() -> u32 {
3640 HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
3641 slot.try_borrow()
3642 .ok()
3643 .and_then(|guard: Ref<'_, Option<HostCanvasRuntime>>| {
3644 guard.as_ref().map(HostCanvasRuntime::get_dirty_h)
3645 })
3646 .unwrap_or(0)
3647 })
3648}
3649
3650#[cfg(target_arch = "wasm32")]
3663#[wasm_bindgen]
3664pub fn euv_host_touch(phase: i32, pointer_id: i32, logical_x: f32, logical_y: f32) -> bool {
3665 HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
3666 let mut borrow: RefMut<'_, Option<HostCanvasRuntime>> = match slot.try_borrow_mut() {
3667 Ok(guard) => guard,
3668 Err(_) => return false,
3669 };
3670 let Some(runtime_ref) = borrow.as_mut() else {
3671 return false;
3672 };
3673 let wid: WindowId = runtime_ref.get_app().get_window_state().get_id();
3674 let android_action: i32 = match phase {
3675 0 => ANDROID_ACTION_DOWN,
3676 1 => ANDROID_ACTION_MOVE,
3677 2 => ANDROID_ACTION_UP,
3678 _ => ANDROID_ACTION_CANCEL,
3679 };
3680 let pos_x: f32 = if logical_x.is_finite() {
3681 logical_x
3682 } else {
3683 0.0
3684 };
3685 let pos_y: f32 = if logical_y.is_finite() {
3686 logical_y
3687 } else {
3688 0.0
3689 };
3690 let events: Vec<WindowEvent> = runtime_ref.get_mut_touch_tracker().handle_android_motion(
3691 wid,
3692 android_action,
3693 0,
3694 &[(pointer_id, pos_x, pos_y)],
3695 );
3696 for ui_event in events {
3697 runtime_ref.get_mut_app().dispatch_window_event(ui_event);
3698 }
3699 runtime_ref.set_dirty(true);
3700 true
3701 })
3702}
3703
3704#[cfg(target_arch = "wasm32")]
3717#[wasm_bindgen]
3718pub fn euv_host_scroll(logical_x: f32, logical_y: f32, dx: f32, dy: f32) -> bool {
3719 HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
3720 let mut borrow: RefMut<'_, Option<HostCanvasRuntime>> = match slot.try_borrow_mut() {
3721 Ok(guard) => guard,
3722 Err(_) => return false,
3723 };
3724 let Some(runtime_ref) = borrow.as_mut() else {
3725 return false;
3726 };
3727 let wid: WindowId = runtime_ref.get_app().get_window_state().get_id();
3728 runtime_ref
3729 .get_mut_app()
3730 .dispatch_window_event(WindowEvent::PointerMove(
3731 wid,
3732 PointerEvent::mouse(logical_x, logical_y),
3733 ));
3734 runtime_ref
3735 .get_mut_app()
3736 .dispatch_window_event(WindowEvent::Scroll(wid, Point::new(dx, dy)));
3737 runtime_ref.set_dirty(true);
3738 true
3739 })
3740}
3741
3742#[cfg(target_arch = "wasm32")]
3754#[wasm_bindgen]
3755pub fn euv_host_resize(logical_w: u32, logical_h: u32, dpr: f32) -> bool {
3756 HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
3757 let mut borrow: RefMut<'_, Option<HostCanvasRuntime>> = match slot.try_borrow_mut() {
3758 Ok(guard) => guard,
3759 Err(_) => return false,
3760 };
3761 let Some(runtime_ref) = borrow.as_mut() else {
3762 return false;
3763 };
3764 let width_val: u32 = logical_w.max(HOST_MIN_VIEWPORT_DIM);
3765 let height_val: u32 = logical_h.max(HOST_MIN_VIEWPORT_DIM);
3766 let scale: f32 = if dpr.is_finite() && dpr > 0.0 {
3767 dpr.clamp(0.5, 4.5)
3768 } else {
3769 runtime_ref.get_dpr()
3770 };
3771 let phys_w: u32 = ((width_val as f64) * (scale as f64)).round().max(1.0) as u32;
3772 let phys_h: u32 = ((height_val as f64) * (scale as f64)).round().max(1.0) as u32;
3773 runtime_ref
3774 .set_logical_width(width_val)
3775 .set_logical_height(height_val)
3776 .set_dpr(scale)
3777 .set_dirty(true)
3778 .set_force_full_dirty(true);
3779 runtime_ref
3780 .get_mut_app()
3781 .set_exact_physical_viewport(phys_w, phys_h, scale);
3782 true
3783 })
3784}
3785
3786#[cfg(target_arch = "wasm32")]
3799#[wasm_bindgen]
3800pub fn euv_host_safe_area(top: f32, right: f32, bottom: f32, left: f32) -> bool {
3801 HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
3802 let mut borrow: RefMut<'_, Option<HostCanvasRuntime>> = match slot.try_borrow_mut() {
3803 Ok(guard) => guard,
3804 Err(_) => return false,
3805 };
3806 let Some(runtime_ref) = borrow.as_mut() else {
3807 return false;
3808 };
3809 let wid: WindowId = runtime_ref.get_app().get_window_state().get_id();
3810 let safe: SafeAreaInsets =
3811 SafeAreaInsets::new(top.max(0.0), right.max(0.0), bottom.max(0.0), left.max(0.0));
3812 runtime_ref
3813 .get_mut_app()
3814 .dispatch_window_event(WindowEvent::SafeAreaChanged(wid, safe));
3815 runtime_ref
3816 .get_mut_app()
3817 .dispatch_window_event(WindowEvent::System(SystemEvent::SafeAreaChanged(safe)));
3818 runtime_ref.set_dirty(true).set_force_full_dirty(true);
3819 true
3820 })
3821}
3822
3823#[cfg(target_arch = "wasm32")]
3834#[wasm_bindgen]
3835pub fn euv_host_lifecycle(tag: i32, payload: &str) -> bool {
3836 HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
3837 let mut borrow: RefMut<'_, Option<HostCanvasRuntime>> = match slot.try_borrow_mut() {
3838 Ok(guard) => guard,
3839 Err(_) => return false,
3840 };
3841 let Some(runtime_ref) = borrow.as_mut() else {
3842 return false;
3843 };
3844 let wid: WindowId = runtime_ref.get_app().get_window_state().get_id();
3845 match tag {
3846 1 => {
3847 runtime_ref.set_paused(false).set_dirty(true);
3848 if !payload.trim().is_empty() {
3849 runtime_ref
3850 .get_mut_app()
3851 .dispatch_window_event(WindowEvent::System(SystemEvent::DeepLink(
3852 payload.trim().to_string(),
3853 )));
3854 }
3855 true
3856 }
3857 2 => {
3858 runtime_ref
3859 .set_paused(false)
3860 .set_dirty(true)
3861 .set_force_full_dirty(true);
3862 runtime_ref
3863 .get_mut_app()
3864 .dispatch_window_event(WindowEvent::System(SystemEvent::Appear));
3865 runtime_ref
3866 .get_mut_app()
3867 .dispatch_window_event(WindowEvent::System(SystemEvent::Foreground));
3868 if !payload.trim().is_empty() {
3869 runtime_ref
3870 .get_mut_app()
3871 .dispatch_window_event(WindowEvent::System(SystemEvent::DeepLink(
3872 payload.trim().to_string(),
3873 )));
3874 }
3875 true
3876 }
3877 3 => {
3878 runtime_ref.set_paused(true);
3879 let cancels: Vec<WindowEvent> = runtime_ref
3880 .get_mut_touch_tracker()
3881 .cancel_all_on_focus_loss(wid);
3882 for ui_event in cancels {
3883 runtime_ref.get_mut_app().dispatch_window_event(ui_event);
3884 }
3885 runtime_ref
3886 .get_mut_app()
3887 .dispatch_window_event(WindowEvent::System(SystemEvent::Disappear));
3888 runtime_ref
3889 .get_mut_app()
3890 .dispatch_window_event(WindowEvent::System(SystemEvent::Background));
3891 true
3892 }
3893 4 => {
3894 runtime_ref.set_paused(true);
3895 let cancels: Vec<WindowEvent> = runtime_ref
3896 .get_mut_touch_tracker()
3897 .cancel_all_on_focus_loss(wid);
3898 for dispatched_event in cancels {
3899 runtime_ref
3900 .get_mut_app()
3901 .dispatch_window_event(dispatched_event);
3902 }
3903 runtime_ref
3904 .get_mut_app()
3905 .dispatch_window_event(WindowEvent::System(SystemEvent::Terminate));
3906 true
3907 }
3908 5 => {
3909 let dismissed_overlay: bool = EuvOverlayStack::dismiss_all() > 0;
3910 let exited_fs: bool = if runtime_ref.get_app().is_immersive_fullscreen()
3911 || is_fullscreen_active()
3912 || EuvOverlayStack::has_fullscreen()
3913 {
3914 let _: usize = sync_external_fullscreen_exit();
3915 runtime_ref.get_mut_app().set_immersive_fullscreen(false);
3916 true
3917 } else {
3918 false
3919 };
3920 let cur_route: String = runtime_ref.get_state().get_route().get_untracked();
3921 let popped_route: bool =
3922 if !dismissed_overlay && !exited_fs && cur_route != ROUTE_OVERVIEW {
3923 let _: bool = runtime_ref
3924 .get_state()
3925 .get_route()
3926 .set_if_changed(ROUTE_OVERVIEW.to_string());
3927 true
3928 } else {
3929 false
3930 };
3931 runtime_ref
3932 .get_mut_app()
3933 .dispatch_window_event(WindowEvent::KeyDown(
3934 wid,
3935 KeyEvent::new(KeyCode::Back, Modifiers::default(), false),
3936 ));
3937 runtime_ref
3938 .get_mut_app()
3939 .dispatch_window_event(WindowEvent::System(SystemEvent::BackPressed));
3940 runtime_ref.set_dirty(true);
3941 let closed_modal_or_fs: bool = dismissed_overlay || exited_fs;
3942 closed_modal_or_fs || popped_route
3943 }
3944 _ => false,
3945 }
3946 })
3947}
3948
3949#[cfg(target_arch = "wasm32")]
3960#[wasm_bindgen]
3961pub fn euv_host_ime(text: &str, confirmed: bool) -> bool {
3962 HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
3963 let mut borrow: RefMut<'_, Option<HostCanvasRuntime>> = match slot.try_borrow_mut() {
3964 Ok(guard) => guard,
3965 Err(_) => return false,
3966 };
3967 let Some(runtime_ref) = borrow.as_mut() else {
3968 return false;
3969 };
3970 let wid: WindowId = runtime_ref.get_app().get_window_state().get_id();
3971 if !text.is_empty() {
3972 runtime_ref
3973 .get_mut_app()
3974 .dispatch_window_event(WindowEvent::Ime(wid, ImeEvent::Commit(text.to_string())));
3975 runtime_ref
3976 .get_mut_app()
3977 .dispatch_window_event(WindowEvent::TextInput(wid, text.to_string()));
3978 }
3979 if confirmed {
3980 runtime_ref
3981 .get_mut_app()
3982 .dispatch_window_event(WindowEvent::KeyDown(
3983 wid,
3984 KeyEvent::new(KeyCode::Enter, Modifiers::default(), false),
3985 ));
3986 }
3987 runtime_ref.set_dirty(true);
3988 true
3989 })
3990}
3991
3992#[cfg(target_arch = "wasm32")]
4002#[wasm_bindgen]
4003pub fn euv_host_key(key: &str) -> bool {
4004 HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
4005 let mut borrow: RefMut<'_, Option<HostCanvasRuntime>> = match slot.try_borrow_mut() {
4006 Ok(guard) => guard,
4007 Err(_) => return false,
4008 };
4009 let Some(runtime_ref) = borrow.as_mut() else {
4010 return false;
4011 };
4012 let wid: WindowId = runtime_ref.get_app().get_window_state().get_id();
4013 let code: KeyCode = match key {
4014 WEB_KEY_ENTER => KeyCode::Enter,
4015 WEB_KEY_BACKSPACE => KeyCode::Backspace,
4016 WEB_KEY_DELETE => KeyCode::Delete,
4017 WEB_KEY_ESCAPE => KeyCode::Escape,
4018 WEB_KEY_TAB => KeyCode::Tab,
4019 WEB_KEY_SPACE => KeyCode::Space,
4020 WEB_KEY_ARROW_LEFT => KeyCode::ArrowLeft,
4021 WEB_KEY_ARROW_RIGHT => KeyCode::ArrowRight,
4022 WEB_KEY_ARROW_UP => KeyCode::ArrowUp,
4023 WEB_KEY_ARROW_DOWN => KeyCode::ArrowDown,
4024 other => other
4025 .chars()
4026 .next()
4027 .map(KeyCode::Character)
4028 .unwrap_or(KeyCode::Unknown),
4029 };
4030 let window_event: WindowEvent =
4031 WindowEvent::KeyDown(wid, KeyEvent::new(code, Modifiers::default(), false));
4032 runtime_ref
4033 .get_state()
4034 .get_game_host()
4035 .ingest_event(&window_event);
4036 runtime_ref
4037 .get_mut_app()
4038 .dispatch_window_event(window_event);
4039 runtime_ref.set_dirty(true);
4040 true
4041 })
4042}
4043
4044#[cfg(target_arch = "wasm32")]
4054#[wasm_bindgen]
4055pub fn euv_host_theme(is_dark: bool) -> bool {
4056 HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
4057 let mut borrow: RefMut<'_, Option<HostCanvasRuntime>> = match slot.try_borrow_mut() {
4058 Ok(guard) => guard,
4059 Err(_) => return false,
4060 };
4061 let Some(runtime_ref) = borrow.as_mut() else {
4062 return false;
4063 };
4064 let wid: WindowId = runtime_ref.get_app().get_window_state().get_id();
4065 let theme: ThemeMode = if is_dark {
4066 ThemeMode::Dark
4067 } else {
4068 ThemeMode::Light
4069 };
4070 let _: bool = runtime_ref
4071 .get_state()
4072 .get_theme()
4073 .get_mode()
4074 .set_if_changed(theme);
4075 runtime_ref
4076 .get_mut_app()
4077 .dispatch_window_event(WindowEvent::ThemeChanged(wid, theme));
4078 runtime_ref
4079 .get_mut_app()
4080 .dispatch_window_event(WindowEvent::System(SystemEvent::ThemeChanged(theme)));
4081 runtime_ref.set_dirty(true).set_force_full_dirty(true);
4082 true
4083 })
4084}
4085
4086#[cfg(target_arch = "wasm32")]
4096#[wasm_bindgen]
4097pub fn euv_host_memory_warning(level: i32) -> bool {
4098 HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
4099 let mut borrow: RefMut<'_, Option<HostCanvasRuntime>> = match slot.try_borrow_mut() {
4100 Ok(guard) => guard,
4101 Err(_) => return false,
4102 };
4103 let Some(runtime_ref) = borrow.as_mut() else {
4104 return false;
4105 };
4106 let pressure: MemoryPressure = miniapp_memory_level_to_pressure(level);
4107 runtime_ref
4108 .get_mut_app()
4109 .dispatch_window_event(WindowEvent::System(SystemEvent::MemoryWarning(pressure)));
4110 runtime_ref.set_dirty(true);
4111 true
4112 })
4113}
4114
4115#[cfg(target_arch = "wasm32")]
4125#[wasm_bindgen]
4126pub fn euv_host_keyboard_height(height_dp: f32) -> bool {
4127 HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
4128 let mut borrow: RefMut<'_, Option<HostCanvasRuntime>> = match slot.try_borrow_mut() {
4129 Ok(guard) => guard,
4130 Err(_) => return false,
4131 };
4132 let Some(runtime_ref) = borrow.as_mut() else {
4133 return false;
4134 };
4135 let height_val: f32 = if height_dp.is_finite() {
4136 height_dp.max(0.0)
4137 } else {
4138 0.0
4139 };
4140 runtime_ref
4141 .get_mut_app()
4142 .dispatch_window_event(WindowEvent::System(
4143 SystemEvent::KeyboardVisibilityChanged {
4144 visible: height_val > 0.0,
4145 height: height_val,
4146 },
4147 ));
4148 runtime_ref.set_dirty(true);
4149 true
4150 })
4151}
4152
4153#[cfg(target_arch = "wasm32")]
4163#[wasm_bindgen]
4164pub fn euv_host_network(status: &str) -> bool {
4165 HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
4166 let mut borrow: RefMut<'_, Option<HostCanvasRuntime>> = match slot.try_borrow_mut() {
4167 Ok(guard) => guard,
4168 Err(_) => return false,
4169 };
4170 let Some(runtime_ref) = borrow.as_mut() else {
4171 return false;
4172 };
4173 let lower: String = status.trim().to_ascii_lowercase();
4174 let net: NetworkStatus = if lower == HOST_NET_NONE || lower == HOST_NET_OFFLINE {
4175 NetworkStatus::Offline
4176 } else if lower == HOST_NET_WIFI {
4177 NetworkStatus::Wifi
4178 } else if lower == HOST_NET_CELLULAR || lower.ends_with('g') {
4179 NetworkStatus::Cellular
4180 } else {
4181 NetworkStatus::Unknown
4182 };
4183 runtime_ref
4184 .get_mut_app()
4185 .dispatch_window_event(WindowEvent::System(SystemEvent::NetworkStatusChanged(net)));
4186 runtime_ref.set_dirty(true);
4187 true
4188 })
4189}
4190
4191#[cfg(target_arch = "wasm32")]
4202#[wasm_bindgen]
4203pub fn euv_host_crown(detents: f32, mode: i32) -> bool {
4204 HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
4205 let mut borrow: RefMut<'_, Option<HostCanvasRuntime>> = match slot.try_borrow_mut() {
4206 Ok(guard) => guard,
4207 Err(_) => return false,
4208 };
4209 let Some(runtime_ref) = borrow.as_mut() else {
4210 return false;
4211 };
4212 if !detents.is_finite() || detents.abs() < 1e-4 {
4213 return false;
4214 }
4215 let wid: WindowId = runtime_ref.get_app().get_window_state().get_id();
4216 let cx: f32 = (runtime_ref.get_logical_width() as f32) * 0.5;
4217 let cy: f32 = (runtime_ref.get_logical_height() as f32) * 0.5;
4218 match mode {
4219 1 | 2 => {
4220 let total: f32 = runtime_ref.get_crown_remainder() + detents;
4221 let steps: i32 = total.trunc() as i32;
4222 runtime_ref.set_crown_remainder(total - (steps as f32));
4223 for _ in 0..steps.unsigned_abs() {
4224 let (code, shift): (KeyCode, bool) = if mode == 1 {
4225 (KeyCode::Tab, steps < 0)
4226 } else if steps > 0 {
4227 (KeyCode::ArrowDown, false)
4228 } else {
4229 (KeyCode::ArrowUp, false)
4230 };
4231 let mods: Modifiers = Modifiers::new(shift, false, false, false);
4232 runtime_ref
4233 .get_mut_app()
4234 .dispatch_window_event(WindowEvent::KeyDown(
4235 wid,
4236 KeyEvent::new(code, mods, false),
4237 ));
4238 }
4239 }
4240 _ => {
4241 runtime_ref
4242 .get_mut_app()
4243 .dispatch_window_event(WindowEvent::PointerMove(
4244 wid,
4245 PointerEvent::mouse(cx, cy),
4246 ));
4247 let dy: f32 = detents * WEARABLE_CROWN_PIXELS_PER_DETENT;
4248 runtime_ref
4249 .get_mut_app()
4250 .dispatch_window_event(WindowEvent::Scroll(wid, Point::new(0.0, dy)));
4251 }
4252 }
4253 runtime_ref.set_dirty(true);
4254 true
4255 })
4256}
4257
4258#[cfg(target_arch = "wasm32")]
4268#[wasm_bindgen]
4269pub fn euv_host_ambient(is_ambient: bool) -> bool {
4270 HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
4271 let mut borrow: RefMut<'_, Option<HostCanvasRuntime>> = match slot.try_borrow_mut() {
4272 Ok(guard) => guard,
4273 Err(_) => return false,
4274 };
4275 let Some(runtime_ref) = borrow.as_mut() else {
4276 return false;
4277 };
4278 runtime_ref.set_ambient(is_ambient).set_dirty(true);
4279 runtime_ref
4280 .get_mut_app()
4281 .dispatch_window_event(WindowEvent::System(SystemEvent::LowPowerModeChanged(
4282 is_ambient,
4283 )));
4284 true
4285 })
4286}
4287
4288#[cfg(target_arch = "wasm32")]
4298#[wasm_bindgen]
4299pub fn euv_host_hardware_gesture(gesture_tag: i32) -> bool {
4300 HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
4301 let mut borrow: RefMut<'_, Option<HostCanvasRuntime>> = match slot.try_borrow_mut() {
4302 Ok(guard) => guard,
4303 Err(_) => return false,
4304 };
4305 let Some(runtime_ref) = borrow.as_mut() else {
4306 return false;
4307 };
4308 let wid: WindowId = runtime_ref.get_app().get_window_state().get_id();
4309 match gesture_tag {
4310 0 => {
4311 runtime_ref
4312 .set_paused(false)
4313 .set_ambient(false)
4314 .set_dirty(true);
4315 runtime_ref
4316 .get_mut_app()
4317 .dispatch_window_event(WindowEvent::System(SystemEvent::Foreground));
4318 true
4319 }
4320 1 => {
4321 runtime_ref.set_ambient(true).set_dirty(true);
4322 runtime_ref
4323 .get_mut_app()
4324 .dispatch_window_event(WindowEvent::System(SystemEvent::LowPowerModeChanged(
4325 true,
4326 )));
4327 true
4328 }
4329 2 => {
4330 runtime_ref.set_paused(true).set_ambient(false);
4331 runtime_ref
4332 .get_mut_app()
4333 .dispatch_window_event(WindowEvent::System(SystemEvent::Background));
4334 true
4335 }
4336 3 => {
4337 runtime_ref
4338 .get_mut_app()
4339 .dispatch_window_event(WindowEvent::KeyDown(
4340 wid,
4341 KeyEvent::new(KeyCode::Enter, Modifiers::default(), false),
4342 ));
4343 runtime_ref.set_dirty(true);
4344 true
4345 }
4346 4 => {
4347 runtime_ref
4348 .get_mut_app()
4349 .dispatch_window_event(WindowEvent::KeyDown(
4350 wid,
4351 KeyEvent::new(KeyCode::Back, Modifiers::default(), false),
4352 ));
4353 runtime_ref
4354 .get_mut_app()
4355 .dispatch_window_event(WindowEvent::System(SystemEvent::BackPressed));
4356 runtime_ref.set_dirty(true);
4357 true
4358 }
4359 _ => false,
4360 }
4361 })
4362}
4363
4364#[cfg(target_arch = "wasm32")]
4379#[wasm_bindgen]
4380pub fn euv_host_device_motion(ax: f32, ay: f32, az: f32, gx: f32, gy: f32, gz: f32) -> bool {
4381 HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
4382 let mut borrow: RefMut<'_, Option<HostCanvasRuntime>> = match slot.try_borrow_mut() {
4383 Ok(guard) => guard,
4384 Err(_) => return false,
4385 };
4386 let Some(runtime_ref) = borrow.as_mut() else {
4387 return false;
4388 };
4389 let sample: DeviceMotionSample = DeviceMotionSample::from_vectors(
4390 [ax, ay, az],
4391 [0.0, 0.0, 0.0],
4392 [gx, gy, gz],
4393 [0.0, 0.0, 0.0],
4394 0,
4395 true,
4396 );
4397 runtime_ref
4398 .get_mut_app()
4399 .dispatch_window_event(WindowEvent::System(SystemEvent::DeviceMotion(sample)));
4400 runtime_ref.set_dirty(true);
4401 true
4402 })
4403}
4404
4405#[cfg(target_arch = "wasm32")]
4415#[wasm_bindgen]
4416pub fn euv_host_navigate(route: &str) -> u64 {
4417 HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
4418 let mut borrow: RefMut<'_, Option<HostCanvasRuntime>> = match slot.try_borrow_mut() {
4419 Ok(guard) => guard,
4420 Err(_) => return 0,
4421 };
4422 let Some(runtime_ref) = borrow.as_mut() else {
4423 return 0;
4424 };
4425 let normalized: String =
4426 resolve_web_hash_route(route, Some(runtime_ref.get_state().get_dynamic_hub()));
4427 let _: bool = runtime_ref
4428 .get_state()
4429 .get_route()
4430 .set_if_changed(normalized);
4431 runtime_ref.set_force_full_dirty(true);
4432 match runtime_ref.get_mut_app().step_frame() {
4433 Ok(stats) => {
4434 runtime_ref.set_dirty(false);
4435 runtime_ref.set_frame_count(runtime_ref.get_frame_count().saturating_add(1));
4436 runtime_ref.set_last_frame_hash(stats.get_frame_hash());
4437 host_sync_dirty_rect(runtime_ref, true);
4438 stats.get_frame_hash()
4439 }
4440 Err(_) => 0,
4441 }
4442 })
4443}
4444
4445#[cfg(target_arch = "wasm32")]
4451#[wasm_bindgen]
4452pub fn euv_host_current_route() -> String {
4453 HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
4454 slot.try_borrow()
4455 .ok()
4456 .and_then(|guard: Ref<'_, Option<HostCanvasRuntime>>| {
4457 guard.as_ref().map(|runtime_ref: &HostCanvasRuntime| {
4458 runtime_ref.get_state().get_route().get_untracked()
4459 })
4460 })
4461 .unwrap_or_default()
4462 })
4463}
4464
4465#[cfg(target_arch = "wasm32")]
4471#[wasm_bindgen]
4472pub fn euv_host_drain_commands_json() -> String {
4473 HOST_OUTBOUND_COMMANDS.with(|queue: &RefCell<Vec<String>>| {
4474 let Ok(mut borrow) = queue.try_borrow_mut() else {
4475 return "[]".to_string();
4476 };
4477 let drained: Vec<String> = take(&mut *borrow);
4478 format!("[{}]", drained.join(","))
4479 })
4480}
4481
4482#[cfg(target_arch = "wasm32")]
4488#[wasm_bindgen]
4489pub fn euv_host_stats_json() -> String {
4490 HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
4491 let Ok(guard) = slot.try_borrow() else {
4492 return "{}".to_string();
4493 };
4494 let Some(runtime_ref) = guard.as_ref() else {
4495 return "{}".to_string();
4496 };
4497 let vendor: String = host_json_escape(runtime_ref.get_vendor());
4498 let route: String = host_json_escape(&runtime_ref.get_state().get_route().get_untracked());
4499 let (pw, ph): (u32, u32) = runtime_ref
4500 .get_app()
4501 .get_renderer()
4502 .framebuffer()
4503 .map(|target_framebuffer: &Framebuffer| (target_framebuffer.get_width(), target_framebuffer.get_height()))
4504 .unwrap_or((0, 0));
4505 format!(
4506 "{{\"vendor\":\"{vendor}\",\"platform\":\"{:?}\",\"route\":\"{route}\",\"logicalWidth\":{},\"logicalHeight\":{},\"physicalWidth\":{pw},\"physicalHeight\":{ph},\"dpr\":{:.2},\"frames\":{},\"paused\":{},\"ambient\":{},\"dark\":{},\"dirty\":[{},{},{},{}],\"hash\":{}}}",
4507 runtime_ref.get_platform_kind(),
4508 runtime_ref.get_logical_width(),
4509 runtime_ref.get_logical_height(),
4510 runtime_ref.get_dpr(),
4511 runtime_ref.get_frame_count(),
4512 runtime_ref.get_paused(),
4513 runtime_ref.get_ambient(),
4514 runtime_ref.get_state().get_theme().get_mode().get_untracked() == ThemeMode::Dark,
4515 runtime_ref.get_dirty_x(),
4516 runtime_ref.get_dirty_y(),
4517 runtime_ref.get_dirty_w(),
4518 runtime_ref.get_dirty_h(),
4519 runtime_ref.get_last_frame_hash(),
4520 )
4521 })
4522}
4523
4524#[cfg(target_arch = "wasm32")]
4530#[wasm_bindgen]
4531pub fn euv_host_is_paused() -> bool {
4532 HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
4533 slot.try_borrow()
4534 .ok()
4535 .and_then(|guard: Ref<'_, Option<HostCanvasRuntime>>| {
4536 guard.as_ref().map(HostCanvasRuntime::get_paused)
4537 })
4538 .unwrap_or(true)
4539 })
4540}
4541
4542#[cfg(target_arch = "wasm32")]
4544#[wasm_bindgen]
4545pub fn euv_host_destroy() {
4546 HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
4547 if let Ok(mut borrow) = slot.try_borrow_mut() {
4548 *borrow = None;
4549 }
4550 });
4551 HOST_OUTBOUND_COMMANDS.with(|queue: &RefCell<Vec<String>>| {
4552 if let Ok(mut borrow) = queue.try_borrow_mut() {
4553 borrow.clear();
4554 }
4555 });
4556}