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, 4.5)
93 } else {
94 1.0
95 };
96 let render_cfg: RenderConfig = default_showcase_render_config(mode, headless);
97 let mut window_cfg: WindowConfig = WindowConfig::default();
98 window_cfg
99 .set_title(SHOWCASE_WINDOW_TITLE.to_string())
100 .set_size(init_w, init_h)
101 .set_render(render_cfg)
102 .set_icon(Some(euv_brand_logo_image()));
103 let mut app_cfg: AppConfig = AppConfig::default();
104 app_cfg.set_window(window_cfg);
105 let mut app: App = if headless {
106 App::headless(app_cfg)?
107 } else {
108 App::new(app_cfg)?
109 };
110 if (init_scale - 1.0).abs() > 0.005 {
111 let phys_w: u32 = ((init_w as f64) * (init_scale as f64)).round().max(1.0) as u32;
112 let phys_h: u32 = ((init_h as f64) * (init_scale as f64)).round().max(1.0) as u32;
113 app.set_exact_physical_viewport(phys_w, phys_h, init_scale);
114 }
115 let enable_bg_workers: bool = !headless && cfg!(not(target_arch = "wasm32"));
116 let state: ShowcaseState =
117 ShowcaseState::new_with_hub(app.get_dynamic_hub().clone(), enable_bg_workers);
118 state.set_default_host_platform_idx(host_platform_matrix_index(app.platform_kind()));
119 app.attach_game_host(state.get_game_host().clone());
120 app.attach_game_host(state.get_game3d_host().clone());
121 app.attach_game_host(state.get_water_host().clone());
122 let mount_state: ShowcaseState = state.clone();
123 let _: NodeId = app.mount(move || mount_showcase_root(&mount_state));
124 Ok((app, state))
125}
126
127pub fn create_showcase_app(
138 headless: bool,
139 mode: RenderMode,
140) -> Result<(App, ShowcaseState), PlatformError> {
141 create_showcase_app_with_viewport(
142 headless,
143 mode,
144 SHOWCASE_WINDOW_WIDTH,
145 SHOWCASE_WINDOW_HEIGHT,
146 1.0,
147 )
148}
149
150pub fn create_showcase_app_for_platform(
161 platform: PlatformKind,
162 mode: RenderMode,
163) -> Result<(App, ShowcaseState), PlatformError> {
164 EuvOverlayStack::clear();
165 reset_fullscreen_state();
166 clear_provided_theme();
167 let render_cfg: RenderConfig = default_showcase_render_config(mode, false);
168 let mut window_cfg: WindowConfig = WindowConfig::default();
169 window_cfg
170 .set_title(SHOWCASE_WINDOW_TITLE.to_string())
171 .set_size(SHOWCASE_WINDOW_WIDTH, SHOWCASE_WINDOW_HEIGHT)
172 .set_render(render_cfg)
173 .set_icon(Some(euv_brand_logo_image()));
174 let mut app_cfg: AppConfig = AppConfig::default();
175 app_cfg.set_window(window_cfg);
176 let backend: Box<dyn PlatformBackend> = Box::new(HeadlessPlatform::emulating(
177 platform,
178 1.0,
179 SafeAreaInsets::default(),
180 ));
181 let mut app: App = App::with_platform(app_cfg, backend)?;
182 let state: ShowcaseState = ShowcaseState::new_with_hub(app.get_dynamic_hub().clone(), false);
183 state.set_default_host_platform_idx(host_platform_matrix_index(app.platform_kind()));
184 app.attach_game_host(state.get_game_host().clone());
185 app.attach_game_host(state.get_game3d_host().clone());
186 app.attach_game_host(state.get_water_host().clone());
187 let mount_state: ShowcaseState = state.clone();
188 let _: NodeId = app.mount(move || mount_showcase_root(&mount_state));
189 Ok((app, state))
190}
191
192pub fn run_headless_smoke(mode: RenderMode) -> Result<FrameStats, PlatformError> {
202 let (mut app, _): (App, ShowcaseState) = create_showcase_app(true, mode)?;
203 app.step_frame()
204}
205
206#[cfg(not(target_arch = "wasm32"))]
220fn dump_rgba_frame(
221 app: &mut App,
222 out_dir: &Path,
223 name: &str,
224 manifest: &mut String,
225 count: &mut usize,
226) -> Result<(), PlatformError> {
227 let _: FrameStats = app.step_frame()?;
228 for _ in 0..20 {
229 if !app.has_active_animations() {
230 break;
231 }
232 let _: FrameStats = app.step_game_frame(1.0 / 60.0)?;
233 }
234 if let Some(fb) = app.get_renderer().framebuffer() {
235 let file_name: String = format!("{name}.rgba");
236 let file_path: PathBuf = out_dir.join(&file_name);
237 fs::write(&file_path, fb.get_pixels().as_slice())
238 .map_err(|err: Error| PlatformError::SurfaceError(err.to_string()))?;
239 manifest.push_str(&format!("{name} {} {}\n", fb.get_width(), fb.get_height()));
240 *count += 1;
241 }
242 Ok(())
243}
244
245#[cfg(not(target_arch = "wasm32"))]
255pub fn capture_showcase_screenshots(out_dir: &Path) -> Result<usize, PlatformError> {
256 reset_reactive_runtime();
257 EuvOverlayStack::clear();
258 reset_fullscreen_state();
259 clear_provided_theme();
260 fs::create_dir_all(out_dir)
261 .map_err(|err: Error| PlatformError::InitializationFailed(err.to_string()))?;
262 let mut window_cfg: WindowConfig = WindowConfig::default();
263 window_cfg
264 .set_title(SHOWCASE_WINDOW_TITLE.to_string())
265 .set_size(1200, 800)
266 .set_render(RenderConfig::software())
267 .set_icon(Some(euv_brand_logo_image()));
268 let mut app_cfg: AppConfig = AppConfig::default();
269 app_cfg.set_window(window_cfg);
270 let backend: Box<dyn PlatformBackend> = Box::new(HeadlessPlatform::emulating(
271 PlatformKind::Headless,
272 2.0,
273 SafeAreaInsets::default(),
274 ));
275 let mut app: App = App::with_platform(app_cfg, backend)?;
276 let state: ShowcaseState = ShowcaseState::new_with_hub(app.get_dynamic_hub().clone(), false);
277 app.attach_game_host(state.get_game_host().clone());
278 app.attach_game_host(state.get_game3d_host().clone());
279 app.attach_game_host(state.get_water_host().clone());
280 let mount_state: ShowcaseState = state.clone();
281 let _: NodeId = app.mount(move || mount_showcase_root(&mount_state));
282 app.get_mut_renderer()
283 .get_mut_software()
284 .set_font_provider(NativeSystemFont::system());
285 let wid: WindowId = app.get_window_state().get_id();
286 let mut manifest: String = String::new();
287 let mut count: usize = 0;
288 app.dispatch_window_event(WindowEvent::Resized(wid, 1200, 800, 2.0));
289 let desktop_routes: [(&str, &str); 12] = [
290 (ROUTE_OVERVIEW, "01_overview_desktop"),
291 (ROUTE_REACTIVE, "02_reactive_desktop"),
292 (ROUTE_RENDER, "03_render_desktop"),
293 (ROUTE_WINDOW, "04_window_desktop"),
294 (ROUTE_FORMS, "05_forms_desktop"),
295 (ROUTE_THEMES, "06_themes_desktop"),
296 (ROUTE_DATA, "07_data_desktop"),
297 (ROUTE_GAME, "08_game_desktop"),
298 (ROUTE_GAME_3D, "08b_game3d_desktop"),
299 (ROUTE_MEDIA, "08c_media_desktop"),
300 (ROUTE_OVERLAYS, "09_overlays_desktop"),
301 (ROUTE_DYNAMIC, "10_dynamic_desktop"),
302 ];
303 for (route, label) in desktop_routes.iter() {
304 let _: bool = state.get_route().set_if_changed((*route).to_string());
305 if *route == ROUTE_OVERVIEW {
306 app.dispatch_window_event(WindowEvent::PointerMove(
307 wid,
308 PointerEvent::mouse(100.0, 108.0),
309 ));
310 }
311 dump_rgba_frame(&mut app, out_dir, label, &mut manifest, &mut count)?;
312 }
313 let _: bool = state.get_route().set_if_changed(ROUTE_FORMS.to_string());
314 let _: FrameStats = app.step_frame()?;
315 app.dispatch_window_event(WindowEvent::PointerMove(
316 wid,
317 PointerEvent::mouse(600.0, 400.0),
318 ));
319 app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(0.0, 420.0)));
320 dump_rgba_frame(
321 &mut app,
322 out_dir,
323 "05b_forms_scrolled",
324 &mut manifest,
325 &mut count,
326 )?;
327 let _: bool = state.get_route().set_if_changed(ROUTE_DATA.to_string());
328 let _: FrameStats = app.step_frame()?;
329 app.dispatch_window_event(WindowEvent::PointerMove(
330 wid,
331 PointerEvent::mouse(600.0, 400.0),
332 ));
333 app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(0.0, 460.0)));
334 dump_rgba_frame(
335 &mut app,
336 out_dir,
337 "07b_data_vlist_scrolled",
338 &mut manifest,
339 &mut count,
340 )?;
341 app.dispatch_window_event(WindowEvent::PointerMove(
342 wid,
343 PointerEvent::mouse(320.0, 120.0),
344 ));
345 app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(0.0, 720.0)));
346 dump_rgba_frame(
347 &mut app,
348 out_dir,
349 "07c_data_bottom",
350 &mut manifest,
351 &mut count,
352 )?;
353 let _: bool = state.get_route().set_if_changed(ROUTE_OVERVIEW.to_string());
354 let _: FrameStats = app.step_frame()?;
355 app.dispatch_window_event(WindowEvent::PointerMove(
356 wid,
357 PointerEvent::mouse(100.0, 108.0),
358 ));
359 dump_rgba_frame(
360 &mut app,
361 out_dir,
362 "01b_overview_hovered",
363 &mut manifest,
364 &mut count,
365 )?;
366 let _: bool = state.get_route().set_if_changed(ROUTE_OVERLAYS.to_string());
367 let _: bool = state.get_modal_open().set_if_changed(true);
368 dump_rgba_frame(
369 &mut app,
370 out_dir,
371 "09b_overlays_modal",
372 &mut manifest,
373 &mut count,
374 )?;
375 let _: bool = state.get_modal_open().set_if_changed(false);
376 let _: bool = state.get_alert_dialog_open().set_if_changed(true);
377 dump_rgba_frame(
378 &mut app,
379 out_dir,
380 "09c_overlays_alert",
381 &mut manifest,
382 &mut count,
383 )?;
384 let _: bool = state.get_alert_dialog_open().set_if_changed(false);
385 let _: bool = state.get_hover_card_open().set_if_changed(true);
386 dump_rgba_frame(
387 &mut app,
388 out_dir,
389 "09d_overlays_hovercard",
390 &mut manifest,
391 &mut count,
392 )?;
393 let _: bool = state.get_hover_card_open().set_if_changed(false);
394 let _: bool = state.get_route().set_if_changed(ROUTE_THEMES.to_string());
395 state.toggle_theme_mode();
396 dump_rgba_frame(
397 &mut app,
398 out_dir,
399 "06b_themes_dark",
400 &mut manifest,
401 &mut count,
402 )?;
403 state.toggle_theme_mode();
404 let _: bool = state.get_route().set_if_changed(ROUTE_OVERVIEW.to_string());
405 app.dispatch_window_event(WindowEvent::Resized(wid, 768, 1024, 2.0));
406 dump_rgba_frame(
407 &mut app,
408 out_dir,
409 "11_overview_tablet",
410 &mut manifest,
411 &mut count,
412 )?;
413 app.dispatch_window_event(WindowEvent::Resized(wid, 390, 844, 2.0));
414 dump_rgba_frame(
415 &mut app,
416 out_dir,
417 "12_overview_mobile",
418 &mut manifest,
419 &mut count,
420 )?;
421 app.dispatch_window_event(WindowEvent::PointerDown(
422 wid,
423 PointerEvent::mouse(350.0, 26.0),
424 ));
425 app.dispatch_window_event(WindowEvent::PointerUp(
426 wid,
427 PointerEvent::mouse(350.0, 26.0),
428 ));
429 dump_rgba_frame(
430 &mut app,
431 out_dir,
432 "12b_mobile_menu_open",
433 &mut manifest,
434 &mut count,
435 )?;
436 app.dispatch_window_event(WindowEvent::PointerDown(
437 wid,
438 PointerEvent::mouse(240.0, 26.0),
439 ));
440 app.dispatch_window_event(WindowEvent::PointerUp(
441 wid,
442 PointerEvent::mouse(240.0, 26.0),
443 ));
444 let _: bool = state.get_route().set_if_changed(ROUTE_FORMS.to_string());
445 dump_rgba_frame(
446 &mut app,
447 out_dir,
448 "13_forms_mobile",
449 &mut manifest,
450 &mut count,
451 )?;
452 fs::write(out_dir.join("manifest.txt"), manifest)
453 .map_err(|err: Error| PlatformError::SurfaceError(err.to_string()))?;
454 Ok(count)
455}
456
457#[cfg(target_arch = "wasm32")]
459#[wasm_bindgen(start)]
460pub fn euv_web_boot() {
461 let _: u64 = euv_example_web_start();
462 let Some(win): Option<Window> = window() else {
463 return;
464 };
465 let Some(doc): Option<Document> = win.document() else {
466 return;
467 };
468 let Ok(Some(el)) = doc.query_selector(WEB_SELECTOR_CANVAS) else {
469 return;
470 };
471 let Ok(canvas) = el.dyn_into::<HtmlCanvasElement>() else {
472 return;
473 };
474 web_attach_ime_proxy(&doc);
475 register_native_action_bridge(web_native_action_bridge);
476 register_frame_wakeup(web_mark_needs_frame);
477 let _: bool = web_refresh_cached_viewport(&win, &canvas);
478 let _: bool = web_apply_cached_viewport(&canvas);
479 let on_move: Closure<dyn FnMut(web_sys::PointerEvent)> =
480 Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
481 let ptr: PointerEvent = web_pointer_from_dom(&ev, None);
482 web_queue_pointer_move_event(ptr);
483 }) as Box<dyn FnMut(web_sys::PointerEvent)>);
484 drop(canvas.add_event_listener_with_callback(
485 WEB_EVENT_POINTER_MOVE,
486 on_move.as_ref().unchecked_ref(),
487 ));
488 on_move.forget();
489 let canvas_down: HtmlCanvasElement = canvas.clone();
490 let on_down: Closure<dyn FnMut(web_sys::PointerEvent)> =
491 Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
492 drop(canvas_down.set_pointer_capture(ev.pointer_id()));
493 let ptr: PointerEvent = web_pointer_from_dom(&ev, Some(true));
494 web_queue_pointer_down_event(ptr);
495 if !WEB_IME_ACTIVE.with(Cell::get) {
496 drop(canvas_down.focus());
497 }
498 }) as Box<dyn FnMut(web_sys::PointerEvent)>);
499 drop(canvas.add_event_listener_with_callback(
500 WEB_EVENT_POINTER_DOWN,
501 on_down.as_ref().unchecked_ref(),
502 ));
503 on_down.forget();
504 let canvas_up: HtmlCanvasElement = canvas.clone();
505 let on_up: Closure<dyn FnMut(web_sys::PointerEvent)> =
506 Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
507 ev.stop_propagation();
508 let ptr: PointerEvent = web_pointer_from_dom(&ev, Some(false));
509 web_queue_pointer_up_event(ptr);
510 drop(canvas_up.release_pointer_capture(ev.pointer_id()));
511 }) as Box<dyn FnMut(web_sys::PointerEvent)>);
512 drop(
513 canvas
514 .add_event_listener_with_callback(WEB_EVENT_POINTER_UP, on_up.as_ref().unchecked_ref()),
515 );
516 on_up.forget();
517 let on_cancel: Closure<dyn FnMut(web_sys::PointerEvent)> =
518 Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
519 ev.stop_propagation();
520 web_queue_pointer_cancel(web_pointer_id_from_dom(&ev));
521 }) as Box<dyn FnMut(web_sys::PointerEvent)>);
522 drop(canvas.add_event_listener_with_callback(
523 WEB_EVENT_POINTER_CANCEL,
524 on_cancel.as_ref().unchecked_ref(),
525 ));
526 drop(canvas.add_event_listener_with_callback(
527 WEB_EVENT_LOST_POINTER_CAPTURE,
528 on_cancel.as_ref().unchecked_ref(),
529 ));
530 on_cancel.forget();
531 let on_win_up: Closure<dyn FnMut(web_sys::PointerEvent)> =
532 Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
533 let ptr: PointerEvent = web_pointer_from_dom(&ev, Some(false));
534 web_queue_pointer_up_event(ptr);
535 }) as Box<dyn FnMut(web_sys::PointerEvent)>);
536 drop(win.add_event_listener_with_callback(
537 WEB_EVENT_POINTER_UP,
538 on_win_up.as_ref().unchecked_ref(),
539 ));
540 on_win_up.forget();
541 let on_win_cancel: Closure<dyn FnMut(web_sys::PointerEvent)> =
542 Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
543 web_queue_pointer_cancel(web_pointer_id_from_dom(&ev));
544 }) as Box<dyn FnMut(web_sys::PointerEvent)>);
545 drop(win.add_event_listener_with_callback(
546 WEB_EVENT_POINTER_CANCEL,
547 on_win_cancel.as_ref().unchecked_ref(),
548 ));
549 on_win_cancel.forget();
550 let on_blur: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
551 web_queue_pointer_cancel(0);
552 web_dispatch_system_event(SystemEvent::FocusChanged(false));
553 }) as Box<dyn FnMut(Event)>);
554 drop(win.add_event_listener_with_callback(WEB_EVENT_BLUR, on_blur.as_ref().unchecked_ref()));
555 on_blur.forget();
556 web_attach_system_event_listeners(&win, &doc);
557 let on_wheel: Closure<dyn FnMut(WheelEvent)> = Closure::wrap(Box::new(move |ev: WheelEvent| {
558 ev.prevent_default();
559 let (left, top, _, _, _): (f64, f64, f64, f64, f32) = WEB_CACHED_VIEWPORT.with(Cell::get);
560 let x: f32 = (ev.client_x() as f64 - left) as f32;
561 let y: f32 = (ev.client_y() as f64 - top) as f32;
562 let mult: f32 = match ev.delta_mode() {
563 1 => 20.0,
564 2 => 320.0,
565 _ => 1.0,
566 };
567 web_queue_scroll_at(
568 x,
569 y,
570 (ev.delta_x() as f32) * mult,
571 (ev.delta_y() as f32) * mult,
572 );
573 })
574 as Box<dyn FnMut(WheelEvent)>);
575 drop(
576 canvas.add_event_listener_with_callback(WEB_EVENT_WHEEL, on_wheel.as_ref().unchecked_ref()),
577 );
578 on_wheel.forget();
579 let on_key: Closure<dyn FnMut(KeyboardEvent)> =
580 Closure::wrap(Box::new(move |ev: KeyboardEvent| {
581 let key: String = ev.key();
582 let code_str: String = ev.code();
583 let ime_active: bool = WEB_IME_ACTIVE.with(Cell::get);
584 let should_prevent: bool = if ime_active {
585 matches!(
586 key.as_str(),
587 WEB_KEY_ARROW_UP
588 | WEB_KEY_ARROW_DOWN
589 | WEB_KEY_ARROW_LEFT
590 | WEB_KEY_ARROW_RIGHT
591 | WEB_KEY_BACKSPACE
592 )
593 } else {
594 matches!(
595 key.as_str(),
596 WEB_KEY_ARROW_UP
597 | WEB_KEY_ARROW_DOWN
598 | WEB_KEY_ARROW_LEFT
599 | WEB_KEY_ARROW_RIGHT
600 | WEB_KEY_BACKSPACE
601 | WEB_KEY_SPACE
602 )
603 };
604 if should_prevent {
605 ev.prevent_default();
606 }
607 web_queue_key_down(&key, &code_str);
608 }) as Box<dyn FnMut(KeyboardEvent)>);
609 drop(win.add_event_listener_with_callback(WEB_EVENT_KEY_DOWN, on_key.as_ref().unchecked_ref()));
610 on_key.forget();
611 let on_key_up: Closure<dyn FnMut(KeyboardEvent)> =
612 Closure::wrap(Box::new(move |ev: KeyboardEvent| {
613 let key: String = ev.key();
614 let code_str: String = ev.code();
615 web_queue_key_up(&key, &code_str);
616 }) as Box<dyn FnMut(KeyboardEvent)>);
617 drop(
618 win.add_event_listener_with_callback(WEB_EVENT_KEY_UP, on_key_up.as_ref().unchecked_ref()),
619 );
620 on_key_up.forget();
621 let win_resize: Window = win.clone();
622 let canvas_resize: HtmlCanvasElement = canvas.clone();
623 let on_resize: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
624 let viewport_changed: bool = web_refresh_cached_viewport(&win_resize, &canvas_resize);
625 let safe_changed: bool = web_sync_safe_area();
626 if viewport_changed || safe_changed {
627 web_mark_needs_frame();
628 }
629 }) as Box<dyn FnMut(Event)>);
630 drop(
631 win.add_event_listener_with_callback(WEB_EVENT_RESIZE, on_resize.as_ref().unchecked_ref()),
632 );
633 on_resize.forget();
634 let win_ro: Window = win.clone();
635 let canvas_ro: HtmlCanvasElement = canvas.clone();
636 let on_ro: Closure<dyn FnMut()> = Closure::wrap(Box::new(move || {
637 if web_refresh_cached_viewport(&win_ro, &canvas_ro) {
638 web_mark_needs_frame();
639 }
640 }) as Box<dyn FnMut()>);
641 let attach_ro_fn: Function =
642 Function::new_with_args(WEB_JS_ATTACH_RESIZE_ARGS, WEB_JS_ATTACH_RESIZE_OBSERVER);
643 drop(attach_ro_fn.call2(
644 &JsValue::NULL,
645 canvas.as_ref(),
646 on_ro.as_ref().unchecked_ref(),
647 ));
648 on_ro.forget();
649 let win_dpr: Window = win.clone();
650 let canvas_dpr: HtmlCanvasElement = canvas.clone();
651 let on_dpr: Closure<dyn FnMut()> = Closure::wrap(Box::new(move || {
652 if web_refresh_cached_viewport(&win_dpr, &canvas_dpr) {
653 web_mark_needs_frame();
654 }
655 }) as Box<dyn FnMut()>);
656 let attach_dpr_fn: Function =
657 Function::new_with_args(WEB_JS_WATCH_DPR_ARGS, WEB_JS_WATCH_DPR_BODY);
658 drop(attach_dpr_fn.call1(&JsValue::NULL, on_dpr.as_ref().unchecked_ref()));
659 on_dpr.forget();
660 let win_raf: Window = win.clone();
661 let canvas_raf: HtmlCanvasElement = canvas.clone();
662 WEB_RAF_CALLBACK.with(|slot: &RefCell<Option<Closure<dyn FnMut(f64)>>>| {
663 if let Ok(mut guard) = slot.try_borrow_mut() {
664 *guard = Some(Closure::wrap(Box::new(move |ts: f64| {
665 WEB_RAF_ID.with(|id_cell: &Cell<Option<i32>>| id_cell.set(None));
666 if !web_should_pump_frames() {
667 WEB_RAF_LAST_TS.with(|ts_cell: &Cell<f64>| ts_cell.set(0.0));
668 WEB_RAF_ACCUM_SECS.with(|s_cell: &Cell<f32>| s_cell.set(0.0));
669 WEB_RAF_ACCUM_FRAMES.with(|f_cell: &Cell<u32>| f_cell.set(0));
670 return;
671 }
672 let prev_ts: f64 = WEB_RAF_LAST_TS.with(|ts_cell: &Cell<f64>| ts_cell.replace(ts));
673 let mut dt: f32 = 1.0 / 60.0;
674 let mut valid_step: bool = false;
675 if prev_ts > 0.0 {
676 let raw_dt: f32 = ((ts - prev_ts) / 1000.0) as f32;
677 if (0.001..=0.1).contains(&raw_dt) {
678 valid_step = true;
679 }
680 dt = raw_dt.clamp(0.001, 0.05);
681 }
682 if valid_step {
683 let next_secs: f32 = WEB_RAF_ACCUM_SECS.with(Cell::get) + dt;
684 let next_frames: u32 = WEB_RAF_ACCUM_FRAMES.with(Cell::get).saturating_add(1);
685 if next_secs >= 0.35 && next_frames >= 8 {
686 let measured_hz: f32 = (next_frames as f32) / next_secs;
687 WEB_RAF_ACCUM_SECS.with(|s_cell: &Cell<f32>| s_cell.set(0.0));
688 WEB_RAF_ACCUM_FRAMES.with(|f_cell: &Cell<u32>| f_cell.set(0));
689 WEB_RAF_CALIBRATED.with(|c: &Cell<bool>| c.set(true));
690 web_report_host_refresh_rate(measured_hz);
691 } else {
692 WEB_RAF_ACCUM_SECS.with(|s_cell: &Cell<f32>| s_cell.set(next_secs));
693 WEB_RAF_ACCUM_FRAMES.with(|f_cell: &Cell<u32>| f_cell.set(next_frames));
694 }
695 }
696 let resized_or_scaled: bool =
697 if WEB_VIEWPORT_DIRTY.with(|flag: &Cell<bool>| flag.replace(false)) {
698 web_apply_cached_viewport(&canvas_raf)
699 } else {
700 false
701 };
702 let cur_route: String = euv_web_current_route();
703 let on_game: bool = cur_route == ROUTE_GAME
704 || cur_route == ROUTE_GAME_3D
705 || cur_route == ROUTE_WATER;
706 let animating: bool = web_has_active_animations();
707 let dirty: bool = WEB_NEEDS_FRAME.with(|flag: &Cell<bool>| flag.replace(false))
708 || is_frame_needed();
709 let needs_continuous: bool = resized_or_scaled || on_game;
710 let needs_redraw: bool = animating || dirty;
711 if needs_continuous || needs_redraw {
712 let _: u64 = web_flush_frame(dt);
713 }
714 let calibrated: bool = WEB_RAF_CALIBRATED.with(Cell::get);
715 let still_active: bool = on_game
716 || web_has_active_animations()
717 || WEB_NEEDS_FRAME.with(Cell::get)
718 || is_frame_needed()
719 || !calibrated;
720 if still_active && web_should_pump_frames() {
721 web_start_raf_pump(&win_raf);
722 } else {
723 WEB_RAF_LAST_TS.with(|ts_cell: &Cell<f64>| ts_cell.set(0.0));
724 }
725 }) as Box<dyn FnMut(f64)>));
726 }
727 });
728 if doc.hidden() {
729 web_dispatch_system_event(SystemEvent::Background);
730 } else {
731 web_start_raf_pump(&win);
732 }
733}
734
735#[cfg(target_arch = "wasm32")]
741fn web_should_pump_frames() -> bool {
742 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
743 match slot.try_borrow() {
744 Ok(guard) => {
745 let pump: bool = guard
746 .as_ref()
747 .map(|(app, _): &(App, ShowcaseState)| app.should_pump_frames())
748 .unwrap_or(false);
749 WEB_SHOULD_PUMP.with(|flag: &Cell<bool>| flag.set(pump));
750 pump
751 }
752 Err(_) => WEB_SHOULD_PUMP.with(Cell::get),
753 }
754 })
755}
756
757#[cfg(target_arch = "wasm32")]
763fn web_start_raf_pump(win: &Window) {
764 if !web_should_pump_frames() {
765 return;
766 }
767 let already_scheduled: bool =
768 WEB_RAF_ID.with(|id_cell: &Cell<Option<i32>>| id_cell.get().is_some());
769 if already_scheduled {
770 return;
771 }
772 WEB_RAF_CALLBACK.with(|slot: &RefCell<Option<Closure<dyn FnMut(f64)>>>| {
773 if let Ok(cb_ref) = slot.try_borrow()
774 && let Some(cb) = cb_ref.as_ref()
775 {
776 let func: &Function = cb.as_ref().unchecked_ref();
777 if let Ok(req_id) = win.request_animation_frame(func) {
778 WEB_RAF_ID.with(|id_cell: &Cell<Option<i32>>| id_cell.set(Some(req_id)));
779 }
780 }
781 });
782}
783
784#[cfg(target_arch = "wasm32")]
786fn web_stop_raf_pump() {
787 let pending_id: Option<i32> = WEB_RAF_ID.with(|id_cell: &Cell<Option<i32>>| id_cell.take());
788 if let Some(req_id) = pending_id
789 && let Some(win) = window()
790 {
791 drop(win.cancel_animation_frame(req_id));
792 }
793 WEB_RAF_LAST_TS.with(|ts_cell: &Cell<f64>| ts_cell.set(0.0));
794 WEB_RAF_ACCUM_SECS.with(|s_cell: &Cell<f32>| s_cell.set(0.0));
795 WEB_RAF_ACCUM_FRAMES.with(|f_cell: &Cell<u32>| f_cell.set(0));
796}
797
798#[cfg(target_arch = "wasm32")]
804fn web_dispatch_system_event(event: SystemEvent) {
805 let mut should_pump: bool = false;
806 let mut handled: bool = false;
807 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
808 if let Ok(mut borrow) = slot.try_borrow_mut()
809 && let Some((app, _)) = borrow.as_mut()
810 {
811 app.dispatch_system_event(event);
812 should_pump = app.should_pump_frames();
813 handled = true;
814 }
815 });
816 if !handled {
817 return;
818 }
819 WEB_SHOULD_PUMP.with(|flag: &Cell<bool>| flag.set(should_pump));
820 if !should_pump {
821 web_stop_raf_pump();
822 } else {
823 WEB_RAF_LAST_TS.with(|ts_cell: &Cell<f64>| ts_cell.set(0.0));
824 web_mark_needs_frame();
825 if let Some(win) = window() {
826 web_start_raf_pump(&win);
827 }
828 }
829}
830
831#[cfg(target_arch = "wasm32")]
838fn web_attach_system_event_listeners(win: &Window, doc: &Document) {
839 let doc_vis: Document = doc.clone();
840 let on_vis: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
841 if doc_vis.hidden() {
842 web_dispatch_system_event(SystemEvent::Background);
843 } else {
844 web_dispatch_system_event(SystemEvent::Foreground);
845 }
846 }) as Box<dyn FnMut(Event)>);
847 drop(doc.add_event_listener_with_callback(
848 WEB_EVENT_VISIBILITY_CHANGE,
849 on_vis.as_ref().unchecked_ref(),
850 ));
851 on_vis.forget();
852 let on_focus: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
853 web_dispatch_system_event(SystemEvent::FocusChanged(true));
854 }) as Box<dyn FnMut(Event)>);
855 drop(win.add_event_listener_with_callback(WEB_EVENT_FOCUS, on_focus.as_ref().unchecked_ref()));
856 on_focus.forget();
857 let on_pageshow: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
858 web_dispatch_system_event(SystemEvent::Foreground);
859 }) as Box<dyn FnMut(Event)>);
860 drop(win.add_event_listener_with_callback(
861 WEB_EVENT_PAGE_SHOW,
862 on_pageshow.as_ref().unchecked_ref(),
863 ));
864 on_pageshow.forget();
865 let on_pagehide: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
866 web_dispatch_system_event(SystemEvent::Background);
867 }) as Box<dyn FnMut(Event)>);
868 drop(win.add_event_listener_with_callback(
869 WEB_EVENT_PAGE_HIDE,
870 on_pagehide.as_ref().unchecked_ref(),
871 ));
872 on_pagehide.forget();
873 let on_unload: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
874 web_dispatch_system_event(SystemEvent::Terminate);
875 }) as Box<dyn FnMut(Event)>);
876 drop(win.add_event_listener_with_callback(
877 WEB_EVENT_BEFORE_UNLOAD,
878 on_unload.as_ref().unchecked_ref(),
879 ));
880 on_unload.forget();
881 let on_online: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
882 web_dispatch_system_event(SystemEvent::NetworkStatusChanged(NetworkStatus::Online));
883 }) as Box<dyn FnMut(Event)>);
884 drop(
885 win.add_event_listener_with_callback(WEB_EVENT_ONLINE, on_online.as_ref().unchecked_ref()),
886 );
887 on_online.forget();
888 let on_offline: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
889 web_dispatch_system_event(SystemEvent::NetworkStatusChanged(NetworkStatus::Offline));
890 }) as Box<dyn FnMut(Event)>);
891 drop(
892 win.add_event_listener_with_callback(
893 WEB_EVENT_OFFLINE,
894 on_offline.as_ref().unchecked_ref(),
895 ),
896 );
897 on_offline.forget();
898 if let Ok(Some(mql)) = win.match_media(WEB_MEDIA_PREFERS_DARK) {
899 let mql_cb: MediaQueryList = mql.clone();
900 let on_theme: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
901 let next_theme: ThemeMode = if mql_cb.matches() {
902 ThemeMode::Dark
903 } else {
904 ThemeMode::Light
905 };
906 web_dispatch_system_event(SystemEvent::ThemeChanged(next_theme));
907 })
908 as Box<dyn FnMut(Event)>);
909 drop(
910 mql.add_event_listener_with_callback(
911 WEB_EVENT_CHANGE,
912 on_theme.as_ref().unchecked_ref(),
913 ),
914 );
915 on_theme.forget();
916 }
917 let win_hash: Window = win.clone();
918 let on_hash: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
919 if let Ok(href) = win_hash.location().href() {
920 web_dispatch_system_event(SystemEvent::DeepLink(href));
921 }
922 }) as Box<dyn FnMut(Event)>);
923 drop(
924 win.add_event_listener_with_callback(
925 WEB_EVENT_HASH_CHANGE,
926 on_hash.as_ref().unchecked_ref(),
927 ),
928 );
929 on_hash.forget();
930 let vv_key: JsValue = JsValue::from_str(WEB_PROP_VISUAL_VIEWPORT);
931 if let Ok(vv_val) = Reflect::get(win.as_ref(), &vv_key)
932 && let Ok(vv_target) = vv_val.clone().dyn_into::<EventTarget>()
933 {
934 let win_vv: Window = win.clone();
935 let vv_obj: JsValue = vv_val;
936 let on_vv_resize: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
937 let inner_h: f32 = win_vv
938 .inner_height()
939 .ok()
940 .and_then(|v: JsValue| v.as_f64())
941 .unwrap_or(0.0) as f32;
942 let h_key: JsValue = JsValue::from_str(WEB_PROP_HEIGHT);
943 let vv_h: f32 = Reflect::get(&vv_obj, &h_key)
944 .ok()
945 .and_then(|v: JsValue| v.as_f64())
946 .unwrap_or(inner_h as f64) as f32;
947 let kb_delta: f32 = (inner_h - vv_h).max(0.0);
948 let visible: bool = kb_delta >= WEB_KEYBOARD_MIN_DELTA_PX;
949 let height: f32 = if visible { kb_delta } else { 0.0 };
950 web_dispatch_system_event(SystemEvent::KeyboardVisibilityChanged { visible, height });
951 if web_sync_safe_area() {
952 web_mark_needs_frame();
953 }
954 })
955 as Box<dyn FnMut(Event)>);
956 drop(vv_target.add_event_listener_with_callback(
957 WEB_EVENT_RESIZE,
958 on_vv_resize.as_ref().unchecked_ref(),
959 ));
960 on_vv_resize.forget();
961 }
962}
963
964#[cfg(target_arch = "wasm32")]
975fn web_map_key(key: &str, code_str: &str) -> KeyCode {
976 match code_str {
977 "KeyW" => return KeyCode::Character('w'),
978 "KeyA" => return KeyCode::Character('a'),
979 "KeyS" => return KeyCode::Character('s'),
980 "KeyD" => return KeyCode::Character('d'),
981 "KeyE" => return KeyCode::Character('e'),
982 "KeyR" => return KeyCode::Character('r'),
983 "KeyP" => return KeyCode::Character('p'),
984 "KeyJ" => return KeyCode::Character('j'),
985 "Space" => return KeyCode::Space,
986 "ArrowLeft" => return KeyCode::ArrowLeft,
987 "ArrowRight" => return KeyCode::ArrowRight,
988 "ArrowUp" => return KeyCode::ArrowUp,
989 "ArrowDown" => return KeyCode::ArrowDown,
990 _ => {}
991 }
992 match key {
993 WEB_KEY_ENTER => KeyCode::Enter,
994 WEB_KEY_BACKSPACE => KeyCode::Backspace,
995 WEB_KEY_DELETE => KeyCode::Delete,
996 WEB_KEY_ESCAPE => KeyCode::Escape,
997 WEB_KEY_TAB => KeyCode::Tab,
998 WEB_KEY_SPACE => KeyCode::Space,
999 WEB_KEY_ARROW_LEFT => KeyCode::ArrowLeft,
1000 WEB_KEY_ARROW_RIGHT => KeyCode::ArrowRight,
1001 WEB_KEY_ARROW_UP => KeyCode::ArrowUp,
1002 WEB_KEY_ARROW_DOWN => KeyCode::ArrowDown,
1003 other => other
1004 .chars()
1005 .next()
1006 .map(KeyCode::Character)
1007 .unwrap_or(KeyCode::Unknown),
1008 }
1009}
1010
1011#[cfg(target_arch = "wasm32")]
1017fn web_has_active_animations() -> bool {
1018 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1019 match slot.try_borrow() {
1020 Ok(guard) => guard
1021 .as_ref()
1022 .map(|(app, _): &(App, ShowcaseState)| app.has_active_animations())
1023 .unwrap_or(false),
1024 Err(_) => false,
1025 }
1026 })
1027}
1028
1029#[cfg(target_arch = "wasm32")]
1031fn web_mark_needs_frame() {
1032 WEB_NEEDS_FRAME.with(|flag: &Cell<bool>| flag.set(true));
1033 let idle: bool = WEB_RAF_ID.with(|id_cell: &Cell<Option<i32>>| id_cell.get().is_none());
1034 if idle && let Some(win) = window() {
1035 web_start_raf_pump(&win);
1036 }
1037}
1038
1039#[cfg(target_arch = "wasm32")]
1049fn web_pointer_id_from_dom(ev: &web_sys::PointerEvent) -> u64 {
1050 (ev.pointer_id() as i64).unsigned_abs().saturating_add(1)
1051}
1052
1053#[cfg(target_arch = "wasm32")]
1064fn web_pointer_from_dom(ev: &web_sys::PointerEvent, force_pressed: Option<bool>) -> PointerEvent {
1065 let (left, top, _, _, _): (f64, f64, f64, f64, f32) = WEB_CACHED_VIEWPORT.with(Cell::get);
1066 let x: f32 = (ev.client_x() as f64 - left) as f32;
1067 let y: f32 = (ev.client_y() as f64 - top) as f32;
1068 let pid: u64 = web_pointer_id_from_dom(ev);
1069 let ptype: String = ev.pointer_type();
1070 let device: PointerDevice = if ptype == WEB_PTR_TYPE_TOUCH {
1071 PointerDevice::Touch
1072 } else if ptype == WEB_PTR_TYPE_PEN {
1073 PointerDevice::Stylus
1074 } else {
1075 PointerDevice::Mouse
1076 };
1077 let is_pressed: bool =
1078 force_pressed.unwrap_or_else(|| ev.buttons() != 0 || device == PointerDevice::Touch);
1079 let pressure: f32 = if is_pressed { 1.0 } else { 0.0 };
1080 PointerEvent::new(
1081 pid,
1082 device,
1083 Point::new(x, y),
1084 PointerButton::Primary,
1085 pressure,
1086 Modifiers::default(),
1087 )
1088}
1089
1090#[cfg(target_arch = "wasm32")]
1096fn web_queue_pointer_move_event(ptr: PointerEvent) {
1097 let mut queued: bool = false;
1098 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1099 if let Ok(mut borrow) = slot.try_borrow_mut()
1100 && let Some((app, _)) = borrow.as_mut()
1101 {
1102 let wid: WindowId = app.get_window_state().get_id();
1103 app.dispatch_window_event(WindowEvent::PointerMove(wid, ptr));
1104 queued = true;
1105 }
1106 });
1107 if queued {
1108 web_mark_needs_frame();
1109 }
1110}
1111
1112#[cfg(target_arch = "wasm32")]
1118fn web_queue_pointer_down_event(ptr: PointerEvent) {
1119 let mut queued: bool = false;
1120 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1121 if let Ok(mut borrow) = slot.try_borrow_mut()
1122 && let Some((app, _)) = borrow.as_mut()
1123 {
1124 let wid: WindowId = app.get_window_state().get_id();
1125 app.dispatch_window_event(WindowEvent::PointerDown(wid, ptr));
1126 queued = true;
1127 }
1128 });
1129 if queued {
1130 web_mark_needs_frame();
1131 }
1132}
1133
1134#[cfg(target_arch = "wasm32")]
1140fn web_queue_pointer_up_event(ptr: PointerEvent) {
1141 let mut queued: bool = false;
1142 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1143 if let Ok(mut borrow) = slot.try_borrow_mut()
1144 && let Some((app, _)) = borrow.as_mut()
1145 {
1146 let wid: WindowId = app.get_window_state().get_id();
1147 app.dispatch_window_event(WindowEvent::PointerUp(wid, ptr));
1148 queued = true;
1149 }
1150 });
1151 if queued {
1152 web_mark_needs_frame();
1153 }
1154}
1155
1156#[cfg(target_arch = "wasm32")]
1162fn web_queue_pointer_cancel(pointer_id: u64) {
1163 let mut queued: bool = false;
1164 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1165 if let Ok(mut borrow) = slot.try_borrow_mut()
1166 && let Some((app, _)) = borrow.as_mut()
1167 {
1168 let wid: WindowId = app.get_window_state().get_id();
1169 app.dispatch_window_event(WindowEvent::PointerCancel(wid, pointer_id));
1170 queued = true;
1171 }
1172 });
1173 if queued {
1174 web_mark_needs_frame();
1175 }
1176}
1177
1178#[cfg(target_arch = "wasm32")]
1187fn web_queue_scroll_at(x: f32, y: f32, dx: f32, dy: f32) {
1188 let mut queued: bool = false;
1189 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1190 if let Ok(mut borrow) = slot.try_borrow_mut()
1191 && let Some((app, _)) = borrow.as_mut()
1192 {
1193 let wid: WindowId = app.get_window_state().get_id();
1194 app.dispatch_window_event(WindowEvent::PointerMove(wid, PointerEvent::mouse(x, y)));
1195 app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(dx, dy)));
1196 queued = true;
1197 }
1198 });
1199 if queued {
1200 web_mark_needs_frame();
1201 }
1202}
1203
1204#[cfg(target_arch = "wasm32")]
1211fn web_queue_key_down(key: &str, code_str: &str) {
1212 if WEB_IME_COMPOSING.with(Cell::get) {
1213 return;
1214 }
1215 let ime_active: bool = WEB_IME_ACTIVE.with(Cell::get);
1216 let mut queued: bool = false;
1217 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1218 if let Ok(mut borrow) = slot.try_borrow_mut()
1219 && let Some((app, _)) = borrow.as_mut()
1220 {
1221 let wid: WindowId = app.get_window_state().get_id();
1222 let code: KeyCode = web_map_key(key, code_str);
1223 let key_ev: WindowEvent =
1224 WindowEvent::KeyDown(wid, KeyEvent::new(code, Modifiers::default(), false));
1225 app.dispatch_window_event(key_ev);
1226 if !ime_active && key.chars().count() == 1 {
1227 app.dispatch_window_event(WindowEvent::TextInput(wid, key.to_string()));
1228 }
1229 queued = true;
1230 }
1231 });
1232 if queued {
1233 web_mark_needs_frame();
1234 }
1235}
1236
1237#[cfg(target_arch = "wasm32")]
1243fn web_queue_text_input(text: String) {
1244 if text.is_empty() {
1245 return;
1246 }
1247 let mut queued: bool = false;
1248 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1249 if let Ok(mut borrow) = slot.try_borrow_mut()
1250 && let Some((app, _)) = borrow.as_mut()
1251 {
1252 let wid: WindowId = app.get_window_state().get_id();
1253 app.dispatch_window_event(WindowEvent::TextInput(wid, text));
1254 queued = true;
1255 }
1256 });
1257 if queued {
1258 web_mark_needs_frame();
1259 }
1260}
1261
1262#[cfg(target_arch = "wasm32")]
1268fn web_flush_ime_element(el: &HtmlElement) {
1269 let key: JsValue = JsValue::from_str(WEB_PROP_VALUE);
1270 if let Ok(val) = Reflect::get(el.as_ref(), &key)
1271 && let Some(text) = val.as_string()
1272 && !text.is_empty()
1273 {
1274 let _: Result<bool, JsValue> = Reflect::set(el.as_ref(), &key, &JsValue::from_str(""));
1275 web_queue_text_input(text);
1276 }
1277}
1278
1279#[cfg(target_arch = "wasm32")]
1285fn web_attach_ime_proxy(doc: &Document) {
1286 let Ok(raw_el) = doc.create_element(WEB_IME_INPUT_TAG) else {
1287 return;
1288 };
1289 let el: Element = raw_el;
1290 drop(el.set_attribute(WEB_IME_ATTR_ID, WEB_IME_INPUT_ID));
1291 drop(el.set_attribute(WEB_IME_ATTR_TYPE, WEB_IME_ATTR_TEXT));
1292 drop(el.set_attribute(WEB_IME_ATTR_AUTOCOMPLETE, WEB_IME_ATTR_OFF));
1293 drop(el.set_attribute(WEB_IME_ATTR_AUTOCORRECT, WEB_IME_ATTR_OFF));
1294 drop(el.set_attribute(WEB_IME_ATTR_AUTOCAPITALIZE, WEB_IME_ATTR_OFF));
1295 drop(el.set_attribute(WEB_IME_ATTR_SPELLCHECK, WEB_IME_ATTR_FALSE));
1296 drop(el.set_attribute(WEB_IME_ATTR_ARIA_LABEL, WEB_IME_ARIA_LABEL));
1297 drop(el.set_attribute(WEB_IME_ATTR_STYLE, WEB_IME_STYLE));
1298 let Ok(html_el) = el.dyn_into::<HtmlElement>() else {
1299 return;
1300 };
1301 if let Some(body) = doc.body() {
1302 drop(body.append_child(&html_el));
1303 }
1304 let comp_start: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1305 WEB_IME_COMPOSING.with(|c: &Cell<bool>| c.set(true));
1306 }) as Box<dyn FnMut(Event)>);
1307 drop(html_el.add_event_listener_with_callback(
1308 WEB_EVENT_COMPOSITION_START,
1309 comp_start.as_ref().unchecked_ref(),
1310 ));
1311 comp_start.forget();
1312 let comp_el: HtmlElement = html_el.clone();
1313 let comp_end: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1314 WEB_IME_COMPOSING.with(|c: &Cell<bool>| c.set(false));
1315 web_flush_ime_element(&comp_el);
1316 }) as Box<dyn FnMut(Event)>);
1317 drop(html_el.add_event_listener_with_callback(
1318 WEB_EVENT_COMPOSITION_END,
1319 comp_end.as_ref().unchecked_ref(),
1320 ));
1321 comp_end.forget();
1322 let inp_el: HtmlElement = html_el.clone();
1323 let on_input: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1324 if !WEB_IME_COMPOSING.with(Cell::get) {
1325 web_flush_ime_element(&inp_el);
1326 }
1327 }) as Box<dyn FnMut(Event)>);
1328 drop(
1329 html_el
1330 .add_event_listener_with_callback(WEB_EVENT_INPUT, on_input.as_ref().unchecked_ref()),
1331 );
1332 on_input.forget();
1333 let on_ime_blur: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1334 WEB_IME_ACTIVE.with(|a: &Cell<bool>| a.set(false));
1335 WEB_IME_COMPOSING.with(|c: &Cell<bool>| c.set(false));
1336 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1337 if let Ok(mut borrow) = slot.try_borrow_mut()
1338 && let Some((app, _)) = borrow.as_mut()
1339 {
1340 let wid: WindowId = app.get_window_state().get_id();
1341 app.dispatch_window_event(WindowEvent::Ime(wid, ImeEvent::Disabled));
1342 }
1343 });
1344 }) as Box<dyn FnMut(Event)>);
1345 drop(
1346 html_el
1347 .add_event_listener_with_callback(WEB_EVENT_BLUR, on_ime_blur.as_ref().unchecked_ref()),
1348 );
1349 on_ime_blur.forget();
1350 WEB_IME_ELEMENT.with(|slot: &RefCell<Option<HtmlElement>>| {
1351 if let Ok(mut guard) = slot.try_borrow_mut() {
1352 *guard = Some(html_el);
1353 }
1354 });
1355}
1356
1357#[cfg(target_arch = "wasm32")]
1369fn web_native_action_bridge(kind: &str, arg1: &str, _arg2: &str) -> bool {
1370 if kind == NATIVE_ACTION_FULLSCREEN {
1371 if arg1 == WEB_FS_ACTION_ON {
1372 web_set_fullscreen(true);
1373 return true;
1374 }
1375 if arg1 == WEB_FS_ACTION_OFF {
1376 web_set_fullscreen(false);
1377 return true;
1378 }
1379 return false;
1380 }
1381 if kind != NATIVE_ACTION_IME {
1382 return false;
1383 }
1384 WEB_IME_ELEMENT.with(|slot: &RefCell<Option<HtmlElement>>| {
1385 let Ok(guard) = slot.try_borrow() else {
1386 return false;
1387 };
1388 let Some(el) = guard.as_ref() else {
1389 return false;
1390 };
1391 if arg1 == WEB_IME_ACTION_SHOW {
1392 WEB_IME_ACTIVE.with(|a: &Cell<bool>| a.set(true));
1393 if let Some(win) = window()
1394 && let Some(doc) = win.document()
1395 && let Some(active_el) = doc.active_element()
1396 && active_el.id() == WEB_IME_INPUT_ID
1397 {
1398 drop(el.blur());
1399 }
1400 drop(el.focus());
1401 true
1402 } else if arg1 == WEB_IME_ACTION_HIDE {
1403 WEB_IME_ACTIVE.with(|a: &Cell<bool>| a.set(false));
1404 WEB_IME_COMPOSING.with(|c: &Cell<bool>| c.set(false));
1405 let key: JsValue = JsValue::from_str(WEB_PROP_VALUE);
1406 let _: Result<bool, JsValue> = Reflect::set(el.as_ref(), &key, &JsValue::from_str(""));
1407 drop(el.blur());
1408 true
1409 } else {
1410 false
1411 }
1412 })
1413}
1414
1415#[cfg(target_arch = "wasm32")]
1422fn web_queue_key_up(key: &str, code_str: &str) {
1423 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1424 if let Ok(mut borrow) = slot.try_borrow_mut()
1425 && let Some((app, _)) = borrow.as_mut()
1426 {
1427 let wid: WindowId = app.get_window_state().get_id();
1428 let code: KeyCode = web_map_key(key, code_str);
1429 app.dispatch_window_event(WindowEvent::KeyUp(
1430 wid,
1431 KeyEvent::new(code, Modifiers::default(), false),
1432 ));
1433 }
1434 });
1435}
1436
1437#[cfg(target_arch = "wasm32")]
1443fn web_query_initial_viewport() -> (f64, f64, f64, f64, f32) {
1444 let Some(win) = window() else {
1445 return (
1446 0.0,
1447 0.0,
1448 SHOWCASE_WINDOW_WIDTH as f64,
1449 SHOWCASE_WINDOW_HEIGHT as f64,
1450 1.0,
1451 );
1452 };
1453 let dpr_raw: f64 = win.device_pixel_ratio();
1454 let dpr: f32 = if dpr_raw.is_finite() && dpr_raw > 0.0 {
1455 dpr_raw.clamp(0.5, 4.5) as f32
1456 } else {
1457 1.0
1458 };
1459 let mut left: f64 = 0.0;
1460 let mut top: f64 = 0.0;
1461 let mut css_w: f64 = 0.0;
1462 let mut css_h: f64 = 0.0;
1463 if let Some(doc) = win.document()
1464 && let Ok(Some(el)) = doc.query_selector(WEB_SELECTOR_CANVAS)
1465 && let Ok(canvas) = el.dyn_into::<HtmlCanvasElement>()
1466 {
1467 let rect: DomRect = canvas.get_bounding_client_rect();
1468 left = rect.left();
1469 top = rect.top();
1470 css_w = rect.width();
1471 css_h = rect.height();
1472 }
1473 if css_w < 320.0 {
1474 css_w = win
1475 .inner_width()
1476 .ok()
1477 .and_then(|v: JsValue| v.as_f64())
1478 .filter(|w: &f64| *w >= 320.0)
1479 .unwrap_or(SHOWCASE_WINDOW_WIDTH as f64);
1480 }
1481 if css_h < 320.0 {
1482 css_h = win
1483 .inner_height()
1484 .ok()
1485 .and_then(|v: JsValue| v.as_f64())
1486 .filter(|h: &f64| *h >= 320.0)
1487 .unwrap_or(SHOWCASE_WINDOW_HEIGHT as f64);
1488 }
1489 (left, top, css_w, css_h, dpr)
1490}
1491
1492#[cfg(target_arch = "wasm32")]
1503fn web_refresh_cached_viewport(win: &Window, canvas: &HtmlCanvasElement) -> bool {
1504 let rect: DomRect = canvas.get_bounding_client_rect();
1505 let left: f64 = rect.left();
1506 let top: f64 = rect.top();
1507 let css_w: f64 = if rect.width() >= 320.0 {
1508 rect.width()
1509 } else {
1510 win.inner_width()
1511 .ok()
1512 .and_then(|v: JsValue| v.as_f64())
1513 .filter(|w: &f64| *w >= 320.0)
1514 .unwrap_or(SHOWCASE_WINDOW_WIDTH as f64)
1515 };
1516 let css_h: f64 = if rect.height() >= 320.0 {
1517 rect.height()
1518 } else {
1519 win.inner_height()
1520 .ok()
1521 .and_then(|v: JsValue| v.as_f64())
1522 .filter(|h: &f64| *h >= 320.0)
1523 .unwrap_or(SHOWCASE_WINDOW_HEIGHT as f64)
1524 };
1525 let dpr_raw: f64 = win.device_pixel_ratio();
1526 let dpr: f32 = if dpr_raw.is_finite() && dpr_raw > 0.0 {
1527 dpr_raw.clamp(0.5, 4.5) as f32
1528 } else {
1529 1.0
1530 };
1531 let prev: (f64, f64, f64, f64, f32) = WEB_CACHED_VIEWPORT.with(Cell::get);
1532 let changed: bool = (prev.0 - left).abs() > 0.25
1533 || (prev.1 - top).abs() > 0.25
1534 || (prev.2 - css_w).abs() > 0.25
1535 || (prev.3 - css_h).abs() > 0.25
1536 || (prev.4 - dpr).abs() > 0.005;
1537 if changed {
1538 WEB_CACHED_VIEWPORT.with(|cell: &Cell<(f64, f64, f64, f64, f32)>| {
1539 cell.set((left, top, css_w, css_h, dpr));
1540 });
1541 WEB_VIEWPORT_DIRTY.with(|flag: &Cell<bool>| flag.set(true));
1542 }
1543 changed
1544}
1545
1546#[cfg(target_arch = "wasm32")]
1556fn web_apply_cached_viewport(canvas: &HtmlCanvasElement) -> bool {
1557 let (_, _, css_w, css_h, dpr): (f64, f64, f64, f64, f32) = WEB_CACHED_VIEWPORT.with(Cell::get);
1558 let dpr_f64: f64 = f64::from(dpr);
1559 let phys_w: u32 = (css_w * dpr_f64).round().max(1.0) as u32;
1560 let phys_h: u32 = (css_h * dpr_f64).round().max(1.0) as u32;
1561 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1562 let Ok(mut borrow) = slot.try_borrow_mut() else {
1563 return false;
1564 };
1565 let Some((app, _)) = borrow.as_mut() else {
1566 return false;
1567 };
1568 let ws: WindowState = app.get_window_state();
1569 let size_diff: bool = ws.get_physical_width() != phys_w
1570 || ws.get_physical_height() != phys_h
1571 || (ws.get_scale_factor() - dpr).abs() > 0.005
1572 || canvas.width() != phys_w
1573 || canvas.height() != phys_h;
1574 if !size_diff {
1575 return false;
1576 }
1577 if canvas.width() != phys_w {
1578 canvas.set_width(phys_w);
1579 }
1580 if canvas.height() != phys_h {
1581 canvas.set_height(phys_h);
1582 }
1583 app.set_exact_physical_viewport(phys_w, phys_h, dpr);
1584 true
1585 })
1586}
1587
1588#[cfg(target_arch = "wasm32")]
1594fn web_sync_safe_area() -> bool {
1595 let measured: SafeAreaInsets = web_query_safe_area_insets();
1596 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1597 let Ok(mut borrow) = slot.try_borrow_mut() else {
1598 return false;
1599 };
1600 let Some((app, _)) = borrow.as_mut() else {
1601 return false;
1602 };
1603 let effective: SafeAreaInsets = if app.is_immersive_fullscreen() {
1604 SafeAreaInsets::default()
1605 } else {
1606 measured
1607 };
1608 let current: SafeAreaInsets = app.get_context().get_safe_area().get_untracked();
1609 if current == effective {
1610 return false;
1611 }
1612 let wid: WindowId = app.get_window_state().get_id();
1613 app.dispatch_window_event(WindowEvent::SafeAreaChanged(wid, effective));
1614 true
1615 })
1616}
1617
1618#[cfg(target_arch = "wasm32")]
1624fn web_report_host_refresh_rate(measured_hz: f32) {
1625 let mut needs_redraw: bool = false;
1626 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1627 if let Ok(mut borrow) = slot.try_borrow_mut()
1628 && let Some((app, _)) = borrow.as_mut()
1629 {
1630 let prev_fps: f32 = app.get_context().get_live_fps().get_untracked();
1631 app.report_host_refresh_rate(measured_hz);
1632 let next_fps: f32 = app.get_context().get_live_fps().get_untracked();
1633 if (next_fps - prev_fps).abs() >= 1.0 {
1634 needs_redraw = true;
1635 }
1636 }
1637 });
1638 if needs_redraw {
1639 web_mark_needs_frame();
1640 }
1641}
1642
1643#[cfg(target_arch = "wasm32")]
1653fn web_flush_frame(dt_secs: f32) -> u64 {
1654 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1655 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
1656 Ok(guard) => guard,
1657 Err(_) => return 0,
1658 };
1659 let Some((app, _)) = borrow.as_mut() else {
1660 return 0;
1661 };
1662 let hash: u64 = app
1663 .step_game_frame(dt_secs)
1664 .map(|stats: FrameStats| stats.get_frame_hash())
1665 .unwrap_or(0);
1666 let pump: bool = app.should_pump_frames();
1667 WEB_SHOULD_PUMP.with(|flag: &Cell<bool>| flag.set(pump));
1668 hash
1669 })
1670}
1671
1672#[cfg(target_arch = "wasm32")]
1678#[wasm_bindgen]
1679pub fn euv_example_web_start() -> u64 {
1680 reset_reactive_runtime();
1681 register_frame_wakeup(web_mark_needs_frame);
1682 let (left, top, css_w, css_h, dpr): (f64, f64, f64, f64, f32) = web_query_initial_viewport();
1683 WEB_CACHED_VIEWPORT.with(|cell: &Cell<(f64, f64, f64, f64, f32)>| {
1684 cell.set((left, top, css_w, css_h, dpr));
1685 });
1686 WEB_VIEWPORT_DIRTY.with(|flag: &Cell<bool>| flag.set(false));
1687 let logical_w: u32 = css_w.round().max(320.0) as u32;
1688 let logical_h: u32 = css_h.round().max(320.0) as u32;
1689 let phys_w: u32 = (css_w * f64::from(dpr)).round().max(1.0) as u32;
1690 let phys_h: u32 = (css_h * f64::from(dpr)).round().max(1.0) as u32;
1691 if let Some(win) = window()
1692 && let Some(doc) = win.document()
1693 && let Ok(Some(el)) = doc.query_selector(WEB_SELECTOR_CANVAS)
1694 && let Ok(canvas) = el.dyn_into::<HtmlCanvasElement>()
1695 {
1696 if canvas.width() != phys_w {
1697 canvas.set_width(phys_w);
1698 }
1699 if canvas.height() != phys_h {
1700 canvas.set_height(phys_h);
1701 }
1702 }
1703 match create_showcase_app_with_viewport(false, RenderMode::Auto, logical_w, logical_h, dpr) {
1704 Ok((mut app, state)) => {
1705 app.set_exact_physical_viewport(phys_w, phys_h, dpr);
1706 if let Some(win) = window()
1707 && let Ok(hash_str) = win.location().hash()
1708 {
1709 let cleaned: &str = hash_str.trim_start_matches('#');
1710 if cleaned.starts_with('/') {
1711 let _: bool = state.get_route().set_if_changed(cleaned.to_string());
1712 }
1713 }
1714 let route_watch: Signal<String> = state.get_route();
1715 let (hash_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
1716 Effect::new(move || {
1717 let r: String = route_watch.get();
1718 if let Some(win) = window() {
1719 let target_hash: String = format!("#{r}");
1720 if win.location().hash().ok().as_deref() != Some(target_hash.as_str()) {
1721 let _: Result<(), JsValue> = win.location().set_hash(&target_hash);
1722 }
1723 }
1724 })
1725 });
1726 let root_id: NodeId = app
1727 .get_scene()
1728 .with_read(SceneTree::get_root, NodeId::default());
1729 app.get_scene().with_write(
1730 |tree: &mut SceneTree| {
1731 tree.attach_scope(root_id, hash_scope);
1732 },
1733 (),
1734 );
1735 let hash: u64 = app
1736 .step_frame()
1737 .map(|stats: FrameStats| stats.get_frame_hash())
1738 .unwrap_or(0);
1739 let pump: bool = app.should_pump_frames();
1740 WEB_SHOULD_PUMP.with(|flag: &Cell<bool>| flag.set(pump));
1741 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1742 if let Ok(mut borrow) = slot.try_borrow_mut() {
1743 *borrow = Some((app, state));
1744 }
1745 });
1746 hash
1747 }
1748 Err(_) => 0,
1749 }
1750}
1751
1752#[cfg(target_arch = "wasm32")]
1762#[wasm_bindgen]
1763pub fn euv_example_render_route(route: &str) -> u64 {
1764 let has_runtime: bool = WEB_SHOWCASE_RUNTIME.with(
1765 |slot: &RefCell<Option<(App, ShowcaseState)>>| matches!(slot.try_borrow(), Ok(guard) if guard.is_some()),
1766 );
1767 if !has_runtime {
1768 let _: u64 = euv_example_web_start();
1769 }
1770 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1771 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
1772 Ok(guard) => guard,
1773 Err(_) => return 0,
1774 };
1775 let Some((app, state)) = borrow.as_mut() else {
1776 return 0;
1777 };
1778 let _: bool = state.get_route().set_if_changed(route.to_string());
1779 app.step_frame()
1780 .map(|stats: FrameStats| stats.get_frame_hash())
1781 .unwrap_or(0)
1782 })
1783}
1784
1785#[cfg(target_arch = "wasm32")]
1796#[wasm_bindgen]
1797pub fn euv_web_pointer_move(x: f32, y: f32) -> u64 {
1798 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1799 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
1800 Ok(guard) => guard,
1801 Err(_) => return 0,
1802 };
1803 let Some((app, _)) = borrow.as_mut() else {
1804 return 0;
1805 };
1806 let wid: WindowId = app.get_window_state().get_id();
1807 app.dispatch_window_event(WindowEvent::PointerMove(wid, PointerEvent::mouse(x, y)));
1808 app.step_frame()
1809 .map(|stats: FrameStats| stats.get_frame_hash())
1810 .unwrap_or(0)
1811 })
1812}
1813
1814#[cfg(target_arch = "wasm32")]
1825#[wasm_bindgen]
1826pub fn euv_web_pointer_down(x: f32, y: f32) -> u64 {
1827 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1828 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
1829 Ok(guard) => guard,
1830 Err(_) => return 0,
1831 };
1832 let Some((app, _)) = borrow.as_mut() else {
1833 return 0;
1834 };
1835 let wid: WindowId = app.get_window_state().get_id();
1836 app.dispatch_window_event(WindowEvent::PointerDown(wid, PointerEvent::mouse(x, y)));
1837 app.step_frame()
1838 .map(|stats: FrameStats| stats.get_frame_hash())
1839 .unwrap_or(0)
1840 })
1841}
1842
1843#[cfg(target_arch = "wasm32")]
1854#[wasm_bindgen]
1855pub fn euv_web_pointer_up(x: f32, y: f32) -> u64 {
1856 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1857 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
1858 Ok(guard) => guard,
1859 Err(_) => return 0,
1860 };
1861 let Some((app, _)) = borrow.as_mut() else {
1862 return 0;
1863 };
1864 let wid: WindowId = app.get_window_state().get_id();
1865 app.dispatch_window_event(WindowEvent::PointerUp(wid, PointerEvent::mouse(x, y)));
1866 app.step_frame()
1867 .map(|stats: FrameStats| stats.get_frame_hash())
1868 .unwrap_or(0)
1869 })
1870}
1871
1872#[cfg(target_arch = "wasm32")]
1883#[wasm_bindgen]
1884pub fn euv_web_scroll(dx: f32, dy: f32) -> u64 {
1885 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1886 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
1887 Ok(guard) => guard,
1888 Err(_) => return 0,
1889 };
1890 let Some((app, _)) = borrow.as_mut() else {
1891 return 0;
1892 };
1893 let wid: WindowId = app.get_window_state().get_id();
1894 app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(dx, dy)));
1895 app.step_frame()
1896 .map(|stats: FrameStats| stats.get_frame_hash())
1897 .unwrap_or(0)
1898 })
1899}
1900
1901#[cfg(target_arch = "wasm32")]
1911#[wasm_bindgen]
1912pub fn euv_web_key_down(key: &str) -> u64 {
1913 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1914 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
1915 Ok(guard) => guard,
1916 Err(_) => return 0,
1917 };
1918 let Some((app, state)) = borrow.as_mut() else {
1919 return 0;
1920 };
1921 let wid: WindowId = app.get_window_state().get_id();
1922 let code: KeyCode = match key {
1923 WEB_KEY_ENTER => KeyCode::Enter,
1924 WEB_KEY_BACKSPACE => KeyCode::Backspace,
1925 WEB_KEY_DELETE => KeyCode::Delete,
1926 WEB_KEY_ESCAPE => KeyCode::Escape,
1927 WEB_KEY_TAB => KeyCode::Tab,
1928 WEB_KEY_SPACE => KeyCode::Space,
1929 WEB_KEY_ARROW_LEFT => KeyCode::ArrowLeft,
1930 WEB_KEY_ARROW_RIGHT => KeyCode::ArrowRight,
1931 WEB_KEY_ARROW_UP => KeyCode::ArrowUp,
1932 WEB_KEY_ARROW_DOWN => KeyCode::ArrowDown,
1933 other => other
1934 .chars()
1935 .next()
1936 .map(KeyCode::Character)
1937 .unwrap_or(KeyCode::Unknown),
1938 };
1939 let key_ev: WindowEvent =
1940 WindowEvent::KeyDown(wid, KeyEvent::new(code, Modifiers::default(), false));
1941 state.get_game_host().ingest_event(&key_ev);
1942 app.dispatch_window_event(key_ev);
1943 if key.chars().count() == 1 {
1944 app.dispatch_window_event(WindowEvent::TextInput(wid, key.to_string()));
1945 }
1946 app.step_frame()
1947 .map(|stats: FrameStats| stats.get_frame_hash())
1948 .unwrap_or(0)
1949 })
1950}
1951
1952#[cfg(target_arch = "wasm32")]
1962#[wasm_bindgen]
1963pub fn euv_web_tick(dt_secs: f32) -> u64 {
1964 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1965 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
1966 Ok(guard) => guard,
1967 Err(_) => return 0,
1968 };
1969 let Some((app, state)) = borrow.as_mut() else {
1970 return 0;
1971 };
1972 if !app.should_pump_frames() {
1973 return app.get_renderer().get_last_stats().get_frame_hash();
1974 }
1975 let cur_route: String = state.get_route().get_untracked();
1976 let on_game: bool =
1977 cur_route == ROUTE_GAME || cur_route == ROUTE_GAME_3D || cur_route == ROUTE_WATER;
1978 if on_game || app.has_active_animations() {
1979 return app
1980 .step_game_frame(dt_secs)
1981 .map(|stats: FrameStats| stats.get_frame_hash())
1982 .unwrap_or(0);
1983 }
1984 app.get_renderer().get_last_stats().get_frame_hash()
1985 })
1986}
1987
1988#[cfg(target_arch = "wasm32")]
2000#[wasm_bindgen]
2001pub fn euv_web_resize(width: u32, height: u32, dpr: f32) -> u64 {
2002 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2003 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2004 Ok(guard) => guard,
2005 Err(_) => return 0,
2006 };
2007 let Some((app, _)) = borrow.as_mut() else {
2008 return 0;
2009 };
2010 let w: u32 = width.max(320);
2011 let h: u32 = height.max(320);
2012 let scale: f32 = if dpr.is_finite() && dpr > 0.0 {
2013 dpr.clamp(0.5, 4.5)
2014 } else {
2015 1.0
2016 };
2017 let phys_w: u32 = ((w as f64) * (scale as f64)).round().max(1.0) as u32;
2018 let phys_h: u32 = ((h as f64) * (scale as f64)).round().max(1.0) as u32;
2019 let (prev_l, prev_t, _, _, _): (f64, f64, f64, f64, f32) =
2020 WEB_CACHED_VIEWPORT.with(Cell::get);
2021 WEB_CACHED_VIEWPORT.with(|cell: &Cell<(f64, f64, f64, f64, f32)>| {
2022 cell.set((prev_l, prev_t, f64::from(w), f64::from(h), scale));
2023 });
2024 WEB_VIEWPORT_DIRTY.with(|flag: &Cell<bool>| flag.set(false));
2025 if let Some(win) = window()
2026 && let Some(doc) = win.document()
2027 && let Ok(Some(el)) = doc.query_selector(WEB_SELECTOR_CANVAS)
2028 && let Ok(canvas) = el.dyn_into::<HtmlCanvasElement>()
2029 {
2030 if canvas.width() != phys_w {
2031 canvas.set_width(phys_w);
2032 }
2033 if canvas.height() != phys_h {
2034 canvas.set_height(phys_h);
2035 }
2036 }
2037 app.set_exact_physical_viewport(phys_w, phys_h, scale);
2038 app.step_frame()
2039 .map(|stats: FrameStats| stats.get_frame_hash())
2040 .unwrap_or(0)
2041 })
2042}
2043
2044#[cfg(all(debug_assertions, target_arch = "wasm32"))]
2054#[wasm_bindgen]
2055pub fn euv_dev_ai_schema(request_json: &str) -> String {
2056 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2057 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2058 Ok(guard) => guard,
2059 Err(_) => return String::new(),
2060 };
2061 let Some((app, state)) = borrow.as_mut() else {
2062 return String::new();
2063 };
2064 let hooks: AiAppHooks = state.build_ai_hooks();
2065 AiSchemaProtocol::handle_json_with_hooks(app, request_json, Some(&hooks))
2066 })
2067}
2068
2069#[cfg(target_arch = "wasm32")]
2075#[wasm_bindgen]
2076pub fn euv_web_current_route() -> String {
2077 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2078 match slot.try_borrow() {
2079 Ok(guard) => guard
2080 .as_ref()
2081 .map(|(_, state): &(App, ShowcaseState)| state.get_route().get_untracked())
2082 .unwrap_or_default(),
2083 Err(_) => String::new(),
2084 }
2085 })
2086}