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 let state: ShowcaseState =
118 ShowcaseState::new_with_hub(app.get_dynamic_hub().clone(), enable_bg_workers);
119 state.set_default_host_platform_idx(host_platform_matrix_index(app.platform_kind()));
120 app.attach_game_host(state.get_game_host().clone());
121 app.attach_game_host(state.get_game3d_host().clone());
122 app.attach_game_host(state.get_water_host().clone());
123 let mount_state: ShowcaseState = state.clone();
124 let _: NodeId = app.mount(move || mount_showcase_root(&mount_state));
125 state.sync_adaptive_from_app(&mut app);
126 Ok((app, state))
127}
128
129pub fn create_showcase_app(
140 headless: bool,
141 mode: RenderMode,
142) -> Result<(App, ShowcaseState), PlatformError> {
143 create_showcase_app_with_viewport(
144 headless,
145 mode,
146 SHOWCASE_WINDOW_WIDTH,
147 SHOWCASE_WINDOW_HEIGHT,
148 1.0,
149 )
150}
151
152pub fn create_showcase_app_for_platform(
163 platform: PlatformKind,
164 mode: RenderMode,
165) -> Result<(App, ShowcaseState), PlatformError> {
166 EuvOverlayStack::clear();
167 reset_fullscreen_state();
168 clear_provided_theme();
169 let render_cfg: RenderConfig = default_showcase_render_config(mode, false);
170 let mut window_cfg: WindowConfig = WindowConfig::default();
171 window_cfg
172 .set_title(SHOWCASE_WINDOW_TITLE.to_string())
173 .set_size(SHOWCASE_WINDOW_WIDTH, SHOWCASE_WINDOW_HEIGHT)
174 .set_render(render_cfg)
175 .set_icon(Some(euv_brand_logo_image()));
176 let mut app_cfg: AppConfig = AppConfig::default();
177 app_cfg.set_window(window_cfg);
178 let backend: Box<dyn PlatformBackend> = Box::new(HeadlessPlatform::emulating(
179 platform,
180 1.0,
181 SafeAreaInsets::default(),
182 ));
183 let mut app: App = App::with_platform(app_cfg, backend)?;
184 let state: ShowcaseState = ShowcaseState::new_with_hub(app.get_dynamic_hub().clone(), false);
185 state.set_default_host_platform_idx(host_platform_matrix_index(app.platform_kind()));
186 app.attach_game_host(state.get_game_host().clone());
187 app.attach_game_host(state.get_game3d_host().clone());
188 app.attach_game_host(state.get_water_host().clone());
189 let mount_state: ShowcaseState = state.clone();
190 let _: NodeId = app.mount(move || mount_showcase_root(&mount_state));
191 state.sync_adaptive_from_app(&mut app);
192 Ok((app, state))
193}
194
195pub fn run_headless_smoke(mode: RenderMode) -> Result<FrameStats, PlatformError> {
205 let (mut app, _): (App, ShowcaseState) = create_showcase_app(true, mode)?;
206 app.step_frame()
207}
208
209#[cfg(not(target_arch = "wasm32"))]
223fn dump_rgba_frame(
224 app: &mut App,
225 out_dir: &Path,
226 name: &str,
227 manifest: &mut String,
228 count: &mut usize,
229) -> Result<(), PlatformError> {
230 let _: FrameStats = app.step_frame()?;
231 for _ in 0..20 {
232 if !app.has_active_animations() {
233 break;
234 }
235 let _: FrameStats = app.step_game_frame(1.0 / 60.0)?;
236 }
237 if let Some(fb) = app.get_renderer().framebuffer() {
238 let file_name: String = format!("{name}.rgba");
239 let file_path: PathBuf = out_dir.join(&file_name);
240 fs::write(&file_path, fb.get_pixels().as_slice())
241 .map_err(|err: Error| PlatformError::SurfaceError(err.to_string()))?;
242 manifest.push_str(&format!("{name} {} {}\n", fb.get_width(), fb.get_height()));
243 *count += 1;
244 }
245 Ok(())
246}
247
248#[cfg(not(target_arch = "wasm32"))]
258pub fn capture_showcase_screenshots(out_dir: &Path) -> Result<usize, PlatformError> {
259 reset_reactive_runtime();
260 EuvOverlayStack::clear();
261 reset_fullscreen_state();
262 clear_provided_theme();
263 fs::create_dir_all(out_dir)
264 .map_err(|err: Error| PlatformError::InitializationFailed(err.to_string()))?;
265 let mut window_cfg: WindowConfig = WindowConfig::default();
266 window_cfg
267 .set_title(SHOWCASE_WINDOW_TITLE.to_string())
268 .set_size(1200, 800)
269 .set_render(RenderConfig::software())
270 .set_icon(Some(euv_brand_logo_image()));
271 let mut app_cfg: AppConfig = AppConfig::default();
272 app_cfg.set_window(window_cfg);
273 let backend: Box<dyn PlatformBackend> = Box::new(HeadlessPlatform::emulating(
274 PlatformKind::Headless,
275 2.0,
276 SafeAreaInsets::default(),
277 ));
278 let mut app: App = App::with_platform(app_cfg, backend)?;
279 let state: ShowcaseState = ShowcaseState::new_with_hub(app.get_dynamic_hub().clone(), false);
280 app.attach_game_host(state.get_game_host().clone());
281 app.attach_game_host(state.get_game3d_host().clone());
282 app.attach_game_host(state.get_water_host().clone());
283 let mount_state: ShowcaseState = state.clone();
284 let _: NodeId = app.mount(move || mount_showcase_root(&mount_state));
285 app.get_mut_renderer()
286 .get_mut_software()
287 .set_font_provider(NativeSystemFont::system());
288 let wid: WindowId = app.get_window_state().get_id();
289 let mut manifest: String = String::new();
290 let mut count: usize = 0;
291 app.dispatch_window_event(WindowEvent::Resized(wid, 1200, 800, 2.0));
292 let desktop_routes: [(&str, &str); 12] = [
293 (ROUTE_OVERVIEW, "01_overview_desktop"),
294 (ROUTE_REACTIVE, "02_reactive_desktop"),
295 (ROUTE_RENDER, "03_render_desktop"),
296 (ROUTE_WINDOW, "04_window_desktop"),
297 (ROUTE_FORMS, "05_forms_desktop"),
298 (ROUTE_THEMES, "06_themes_desktop"),
299 (ROUTE_DATA, "07_data_desktop"),
300 (ROUTE_GAME, "08_game_desktop"),
301 (ROUTE_GAME_3D, "08b_game3d_desktop"),
302 (ROUTE_MEDIA, "08c_media_desktop"),
303 (ROUTE_OVERLAYS, "09_overlays_desktop"),
304 (ROUTE_DYNAMIC, "10_dynamic_desktop"),
305 ];
306 for (route, label) in desktop_routes.iter() {
307 let _: bool = state.get_route().set_if_changed((*route).to_string());
308 if *route == ROUTE_OVERVIEW {
309 app.dispatch_window_event(WindowEvent::PointerMove(
310 wid,
311 PointerEvent::mouse(100.0, 108.0),
312 ));
313 }
314 dump_rgba_frame(&mut app, out_dir, label, &mut manifest, &mut count)?;
315 }
316 let _: bool = state.get_route().set_if_changed(ROUTE_FORMS.to_string());
317 let _: FrameStats = app.step_frame()?;
318 app.dispatch_window_event(WindowEvent::PointerMove(
319 wid,
320 PointerEvent::mouse(600.0, 400.0),
321 ));
322 app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(0.0, 420.0)));
323 dump_rgba_frame(
324 &mut app,
325 out_dir,
326 "05b_forms_scrolled",
327 &mut manifest,
328 &mut count,
329 )?;
330 let _: bool = state.get_route().set_if_changed(ROUTE_DATA.to_string());
331 let _: FrameStats = app.step_frame()?;
332 app.dispatch_window_event(WindowEvent::PointerMove(
333 wid,
334 PointerEvent::mouse(600.0, 400.0),
335 ));
336 app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(0.0, 460.0)));
337 dump_rgba_frame(
338 &mut app,
339 out_dir,
340 "07b_data_vlist_scrolled",
341 &mut manifest,
342 &mut count,
343 )?;
344 app.dispatch_window_event(WindowEvent::PointerMove(
345 wid,
346 PointerEvent::mouse(320.0, 120.0),
347 ));
348 app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(0.0, 720.0)));
349 dump_rgba_frame(
350 &mut app,
351 out_dir,
352 "07c_data_bottom",
353 &mut manifest,
354 &mut count,
355 )?;
356 let _: bool = state.get_route().set_if_changed(ROUTE_OVERVIEW.to_string());
357 let _: FrameStats = app.step_frame()?;
358 app.dispatch_window_event(WindowEvent::PointerMove(
359 wid,
360 PointerEvent::mouse(100.0, 108.0),
361 ));
362 dump_rgba_frame(
363 &mut app,
364 out_dir,
365 "01b_overview_hovered",
366 &mut manifest,
367 &mut count,
368 )?;
369 let _: bool = state.get_route().set_if_changed(ROUTE_OVERLAYS.to_string());
370 let _: bool = state.get_modal_open().set_if_changed(true);
371 dump_rgba_frame(
372 &mut app,
373 out_dir,
374 "09b_overlays_modal",
375 &mut manifest,
376 &mut count,
377 )?;
378 let _: bool = state.get_modal_open().set_if_changed(false);
379 let _: bool = state.get_alert_dialog_open().set_if_changed(true);
380 dump_rgba_frame(
381 &mut app,
382 out_dir,
383 "09c_overlays_alert",
384 &mut manifest,
385 &mut count,
386 )?;
387 let _: bool = state.get_alert_dialog_open().set_if_changed(false);
388 let _: bool = state.get_hover_card_open().set_if_changed(true);
389 dump_rgba_frame(
390 &mut app,
391 out_dir,
392 "09d_overlays_hovercard",
393 &mut manifest,
394 &mut count,
395 )?;
396 let _: bool = state.get_hover_card_open().set_if_changed(false);
397 let _: bool = state.get_route().set_if_changed(ROUTE_THEMES.to_string());
398 state.toggle_theme_mode();
399 dump_rgba_frame(
400 &mut app,
401 out_dir,
402 "06b_themes_dark",
403 &mut manifest,
404 &mut count,
405 )?;
406 state.toggle_theme_mode();
407 let _: bool = state.get_route().set_if_changed(ROUTE_OVERVIEW.to_string());
408 app.dispatch_window_event(WindowEvent::Resized(wid, 768, 1024, 2.0));
409 dump_rgba_frame(
410 &mut app,
411 out_dir,
412 "11_overview_tablet",
413 &mut manifest,
414 &mut count,
415 )?;
416 app.dispatch_window_event(WindowEvent::Resized(wid, 390, 844, 2.0));
417 dump_rgba_frame(
418 &mut app,
419 out_dir,
420 "12_overview_mobile",
421 &mut manifest,
422 &mut count,
423 )?;
424 app.dispatch_window_event(WindowEvent::PointerDown(
425 wid,
426 PointerEvent::mouse(350.0, 26.0),
427 ));
428 app.dispatch_window_event(WindowEvent::PointerUp(
429 wid,
430 PointerEvent::mouse(350.0, 26.0),
431 ));
432 dump_rgba_frame(
433 &mut app,
434 out_dir,
435 "12b_mobile_menu_open",
436 &mut manifest,
437 &mut count,
438 )?;
439 app.dispatch_window_event(WindowEvent::PointerDown(
440 wid,
441 PointerEvent::mouse(240.0, 26.0),
442 ));
443 app.dispatch_window_event(WindowEvent::PointerUp(
444 wid,
445 PointerEvent::mouse(240.0, 26.0),
446 ));
447 let _: bool = state.get_route().set_if_changed(ROUTE_FORMS.to_string());
448 dump_rgba_frame(
449 &mut app,
450 out_dir,
451 "13_forms_mobile",
452 &mut manifest,
453 &mut count,
454 )?;
455 fs::write(out_dir.join("manifest.txt"), manifest)
456 .map_err(|err: Error| PlatformError::SurfaceError(err.to_string()))?;
457 Ok(count)
458}
459
460#[must_use]
470pub fn normalize_web_hash_route(raw_hash: &str) -> String {
471 resolve_web_hash_route(raw_hash, None)
472}
473
474#[must_use]
485pub fn resolve_web_hash_route(raw_hash: &str, hub: Option<&DynamicUpdateHub>) -> String {
486 let trimmed: &str = raw_hash.trim().trim_start_matches('#');
487 let without_query: &str = trimmed.split(['?', '#']).next().unwrap_or("").trim();
488 let segments: Vec<&str> = without_query
489 .split('/')
490 .filter(|seg: &&str| !seg.is_empty())
491 .collect();
492 if segments.is_empty() {
493 return ROUTE_OVERVIEW.to_string();
494 }
495 let candidate: String = format!("/{}", segments.join("/"));
496 let is_static: bool = SHOWCASE_ROUTES
497 .iter()
498 .any(|spec: &ShowcaseRouteSpec| spec.get_path() == candidate.as_str());
499 let is_dynamic: bool = hub
500 .map(|h: &DynamicUpdateHub| h.has_dynamic_page(&candidate))
501 .unwrap_or(false);
502 if is_static || is_dynamic {
503 candidate
504 } else {
505 ROUTE_OVERVIEW.to_string()
506 }
507}
508
509pub fn apply_showcase_history_route(
521 app: &mut App,
522 state: &ShowcaseState,
523 raw_hash: &str,
524) -> String {
525 let next: String = resolve_web_hash_route(raw_hash, Some(state.get_dynamic_hub()));
526 let _: usize = EuvOverlayStack::dismiss_all();
527 let _: bool = state.get_cmd_palette_open().set_if_changed(false);
528 if app.is_immersive_fullscreen() || is_fullscreen_active() || EuvOverlayStack::has_fullscreen()
529 {
530 let _: usize = sync_external_fullscreen_exit();
531 app.set_immersive_fullscreen(false);
532 }
533 let _: bool = state.get_route().set_if_changed(next.clone());
534 next
535}
536
537#[must_use]
549pub fn web_is_ime_composition_key(is_composing: bool, key: &str, key_code: u32) -> bool {
550 is_composing || key == WEB_KEY_PROCESS || key_code == WEB_KEY_CODE_IME_PROCESS
551}
552
553#[must_use]
565pub fn web_should_dispatch_text_input(ime_active: bool, mods: Modifiers, key: &str) -> bool {
566 !ime_active && !mods.get_ctrl() && !mods.get_meta() && key.chars().count() == 1
567}
568
569#[cfg(target_arch = "wasm32")]
571#[wasm_bindgen(start)]
572pub fn euv_web_boot() {
573 let _: u64 = euv_example_web_start();
574 let Some(win): Option<Window> = window() else {
575 return;
576 };
577 let Some(doc): Option<Document> = win.document() else {
578 return;
579 };
580 let Ok(Some(el)) = doc.query_selector(WEB_SELECTOR_CANVAS) else {
581 return;
582 };
583 let Ok(canvas) = el.dyn_into::<HtmlCanvasElement>() else {
584 return;
585 };
586 web_attach_ime_proxy(&doc);
587 register_native_action_bridge(web_native_action_bridge);
588 register_frame_wakeup(web_mark_needs_frame);
589 let _: bool = web_refresh_cached_viewport(&win, &canvas);
590 let _: bool = web_apply_cached_viewport(&canvas);
591 let on_move: Closure<dyn FnMut(web_sys::PointerEvent)> =
592 Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
593 let ptr: PointerEvent = web_pointer_from_dom(&ev, None);
594 web_queue_pointer_move_event(ptr);
595 }) as Box<dyn FnMut(web_sys::PointerEvent)>);
596 drop(canvas.add_event_listener_with_callback(
597 WEB_EVENT_POINTER_MOVE,
598 on_move.as_ref().unchecked_ref(),
599 ));
600 on_move.forget();
601 let canvas_down: HtmlCanvasElement = canvas.clone();
602 let on_down: Closure<dyn FnMut(web_sys::PointerEvent)> =
603 Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
604 drop(canvas_down.set_pointer_capture(ev.pointer_id()));
605 let ptr: PointerEvent = web_pointer_from_dom(&ev, Some(true));
606 web_queue_pointer_down_event(ptr);
607 if !WEB_IME_ACTIVE.with(Cell::get) {
608 drop(canvas_down.focus());
609 }
610 }) as Box<dyn FnMut(web_sys::PointerEvent)>);
611 drop(canvas.add_event_listener_with_callback(
612 WEB_EVENT_POINTER_DOWN,
613 on_down.as_ref().unchecked_ref(),
614 ));
615 on_down.forget();
616 let canvas_up: HtmlCanvasElement = canvas.clone();
617 let on_up: Closure<dyn FnMut(web_sys::PointerEvent)> =
618 Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
619 ev.stop_propagation();
620 let ptr: PointerEvent = web_pointer_from_dom(&ev, Some(false));
621 web_queue_pointer_up_event(ptr);
622 drop(canvas_up.release_pointer_capture(ev.pointer_id()));
623 }) as Box<dyn FnMut(web_sys::PointerEvent)>);
624 drop(
625 canvas
626 .add_event_listener_with_callback(WEB_EVENT_POINTER_UP, on_up.as_ref().unchecked_ref()),
627 );
628 on_up.forget();
629 let on_cancel: Closure<dyn FnMut(web_sys::PointerEvent)> =
630 Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
631 ev.stop_propagation();
632 web_queue_pointer_cancel(web_pointer_id_from_dom(&ev));
633 }) as Box<dyn FnMut(web_sys::PointerEvent)>);
634 drop(canvas.add_event_listener_with_callback(
635 WEB_EVENT_POINTER_CANCEL,
636 on_cancel.as_ref().unchecked_ref(),
637 ));
638 drop(canvas.add_event_listener_with_callback(
639 WEB_EVENT_LOST_POINTER_CAPTURE,
640 on_cancel.as_ref().unchecked_ref(),
641 ));
642 on_cancel.forget();
643 let on_win_up: Closure<dyn FnMut(web_sys::PointerEvent)> =
644 Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
645 let ptr: PointerEvent = web_pointer_from_dom(&ev, Some(false));
646 web_queue_pointer_up_event(ptr);
647 }) as Box<dyn FnMut(web_sys::PointerEvent)>);
648 drop(win.add_event_listener_with_callback(
649 WEB_EVENT_POINTER_UP,
650 on_win_up.as_ref().unchecked_ref(),
651 ));
652 on_win_up.forget();
653 let on_win_cancel: Closure<dyn FnMut(web_sys::PointerEvent)> =
654 Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
655 web_queue_pointer_cancel(web_pointer_id_from_dom(&ev));
656 }) as Box<dyn FnMut(web_sys::PointerEvent)>);
657 drop(win.add_event_listener_with_callback(
658 WEB_EVENT_POINTER_CANCEL,
659 on_win_cancel.as_ref().unchecked_ref(),
660 ));
661 on_win_cancel.forget();
662 let on_touch_cancel: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
663 web_queue_pointer_cancel(0);
664 }) as Box<dyn FnMut(Event)>);
665 drop(canvas.add_event_listener_with_callback(
666 WEB_EVENT_TOUCH_CANCEL,
667 on_touch_cancel.as_ref().unchecked_ref(),
668 ));
669 drop(win.add_event_listener_with_callback(
670 WEB_EVENT_TOUCH_CANCEL,
671 on_touch_cancel.as_ref().unchecked_ref(),
672 ));
673 on_touch_cancel.forget();
674 let on_blur: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
675 web_queue_pointer_cancel(0);
676 web_dispatch_system_event(SystemEvent::FocusChanged(false));
677 }) as Box<dyn FnMut(Event)>);
678 drop(win.add_event_listener_with_callback(WEB_EVENT_BLUR, on_blur.as_ref().unchecked_ref()));
679 on_blur.forget();
680 web_attach_system_event_listeners(&win, &doc, &canvas);
681 let on_wheel: Closure<dyn FnMut(WheelEvent)> = Closure::wrap(Box::new(move |ev: WheelEvent| {
682 ev.prevent_default();
683 let (left, top, _, _, _): (f64, f64, f64, f64, f32) = WEB_CACHED_VIEWPORT.with(Cell::get);
684 let x: f32 = (ev.client_x() as f64 - left) as f32;
685 let y: f32 = (ev.client_y() as f64 - top) as f32;
686 let mult: f32 = match ev.delta_mode() {
687 1 => 20.0,
688 2 => 320.0,
689 _ => 1.0,
690 };
691 web_queue_scroll_at(
692 x,
693 y,
694 (ev.delta_x() as f32) * mult,
695 (ev.delta_y() as f32) * mult,
696 );
697 })
698 as Box<dyn FnMut(WheelEvent)>);
699 web_add_non_passive_listener(
700 canvas.as_ref(),
701 WEB_EVENT_WHEEL,
702 on_wheel.as_ref().unchecked_ref(),
703 );
704 on_wheel.forget();
705 let on_key: Closure<dyn FnMut(KeyboardEvent)> =
706 Closure::wrap(Box::new(move |ev: KeyboardEvent| {
707 let key: String = ev.key();
708 if WEB_IME_COMPOSING.with(Cell::get)
709 || web_is_ime_composition_key(ev.is_composing(), &key, ev.key_code())
710 {
711 return;
712 }
713 let code_str: String = ev.code();
714 let mods: Modifiers =
715 Modifiers::new(ev.shift_key(), ev.ctrl_key(), ev.alt_key(), ev.meta_key());
716 let ime_active: bool = WEB_IME_ACTIVE.with(Cell::get);
717 let cmd_or_ctrl: bool = mods.get_ctrl() || mods.get_meta();
718 let is_nav_or_edit_key: bool = matches!(
719 key.as_str(),
720 WEB_KEY_ARROW_UP
721 | WEB_KEY_ARROW_DOWN
722 | WEB_KEY_ARROW_LEFT
723 | WEB_KEY_ARROW_RIGHT
724 | WEB_KEY_HOME
725 | WEB_KEY_END
726 | WEB_KEY_BACKSPACE
727 | WEB_KEY_DELETE
728 );
729 let should_prevent: bool = if cmd_or_ctrl {
730 matches!(code_str.as_str(), WEB_CODE_KEY_K | WEB_CODE_KEY_A)
731 || (ime_active && is_nav_or_edit_key)
732 } else if ime_active {
733 is_nav_or_edit_key || key.as_str() == WEB_KEY_TAB
734 } else {
735 is_nav_or_edit_key
736 || key.as_str() == WEB_KEY_PAGE_UP
737 || key.as_str() == WEB_KEY_PAGE_DOWN
738 || key.as_str() == WEB_KEY_SPACE
739 };
740 if should_prevent {
741 ev.prevent_default();
742 }
743 web_queue_key_down(&key, &code_str, mods, ev.repeat());
744 }) as Box<dyn FnMut(KeyboardEvent)>);
745 drop(win.add_event_listener_with_callback(WEB_EVENT_KEY_DOWN, on_key.as_ref().unchecked_ref()));
746 on_key.forget();
747 let on_key_up: Closure<dyn FnMut(KeyboardEvent)> =
748 Closure::wrap(Box::new(move |ev: KeyboardEvent| {
749 let key: String = ev.key();
750 let code_str: String = ev.code();
751 let mods: Modifiers =
752 Modifiers::new(ev.shift_key(), ev.ctrl_key(), ev.alt_key(), ev.meta_key());
753 web_queue_key_up(&key, &code_str, mods);
754 }) as Box<dyn FnMut(KeyboardEvent)>);
755 drop(
756 win.add_event_listener_with_callback(WEB_EVENT_KEY_UP, on_key_up.as_ref().unchecked_ref()),
757 );
758 on_key_up.forget();
759 let on_paste: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |ev: Event| {
760 if let Some(pasted) = web_extract_paste_text(&ev)
761 && !pasted.is_empty()
762 {
763 ev.prevent_default();
764 web_queue_text_input(pasted);
765 }
766 }) as Box<dyn FnMut(Event)>);
767 drop(win.add_event_listener_with_callback(WEB_EVENT_PASTE, on_paste.as_ref().unchecked_ref()));
768 on_paste.forget();
769 let on_copy: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |ev: Event| {
770 if web_is_copy_proxy_event(&ev) {
771 return;
772 }
773 if let Some(selected) = web_selected_text_snapshot()
774 && web_write_copy_event_text(&ev, &selected)
775 {
776 ev.prevent_default();
777 }
778 }) as Box<dyn FnMut(Event)>);
779 drop(doc.add_event_listener_with_callback(WEB_EVENT_COPY, on_copy.as_ref().unchecked_ref()));
780 on_copy.forget();
781 let win_resize: Window = win.clone();
782 let canvas_resize: HtmlCanvasElement = canvas.clone();
783 let on_resize: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
784 web_apply_viewport_resize_immediate(&win_resize, &canvas_resize);
785 }) as Box<dyn FnMut(Event)>);
786 drop(
787 win.add_event_listener_with_callback(WEB_EVENT_RESIZE, on_resize.as_ref().unchecked_ref()),
788 );
789 if let Ok(vv) = Reflect::get(win.as_ref(), &JsValue::from_str(WEB_PROP_VISUAL_VIEWPORT))
790 && let Ok(vv_target) = vv.dyn_into::<EventTarget>()
791 {
792 drop(vv_target.add_event_listener_with_callback(
793 WEB_EVENT_RESIZE,
794 on_resize.as_ref().unchecked_ref(),
795 ));
796 }
797 on_resize.forget();
798 let win_ro: Window = win.clone();
799 let canvas_ro: HtmlCanvasElement = canvas.clone();
800 let on_ro: Closure<dyn FnMut(f64, f64)> = Closure::wrap(Box::new(move |pw: f64, ph: f64| {
801 let valid_dims: bool = pw.is_finite() && ph.is_finite();
802 if valid_dims && pw >= 64.0 && ph >= 64.0 {
803 let obs_w: u32 = pw.round().clamp(1.0, WEB_CANVAS_MAX_PHYS_DIM) as u32;
804 let obs_h: u32 = ph.round().clamp(1.0, WEB_CANVAS_MAX_PHYS_DIM) as u32;
805 WEB_OBSERVED_PHYS_SIZE.with(|cell: &Cell<(u32, u32)>| cell.set((obs_w, obs_h)));
806 }
807 web_apply_viewport_resize_immediate(&win_ro, &canvas_ro);
808 }) as Box<dyn FnMut(f64, f64)>);
809 let attach_ro_fn: Function =
810 Function::new_with_args(WEB_JS_ATTACH_RESIZE_ARGS, WEB_JS_ATTACH_RESIZE_OBSERVER);
811 drop(attach_ro_fn.call2(
812 &JsValue::NULL,
813 canvas.as_ref(),
814 on_ro.as_ref().unchecked_ref(),
815 ));
816 on_ro.forget();
817 let win_dpr: Window = win.clone();
818 let canvas_dpr: HtmlCanvasElement = canvas.clone();
819 let on_dpr: Closure<dyn FnMut()> = Closure::wrap(Box::new(move || {
820 web_apply_viewport_resize_immediate(&win_dpr, &canvas_dpr);
821 }) as Box<dyn FnMut()>);
822 let attach_dpr_fn: Function =
823 Function::new_with_args(WEB_JS_WATCH_DPR_ARGS, WEB_JS_WATCH_DPR_BODY);
824 drop(attach_dpr_fn.call1(&JsValue::NULL, on_dpr.as_ref().unchecked_ref()));
825 on_dpr.forget();
826 let win_raf: Window = win.clone();
827 let canvas_raf: HtmlCanvasElement = canvas.clone();
828 WEB_RAF_CALLBACK.with(|slot: &RefCell<Option<Closure<dyn FnMut(f64)>>>| {
829 if let Ok(mut guard) = slot.try_borrow_mut() {
830 *guard = Some(Closure::wrap(Box::new(move |ts: f64| {
831 WEB_RAF_ID.with(|id_cell: &Cell<Option<i32>>| id_cell.set(None));
832 if !web_should_pump_frames() {
833 WEB_RAF_LAST_TS.with(|ts_cell: &Cell<f64>| ts_cell.set(0.0));
834 WEB_RAF_ACCUM_SECS.with(|s_cell: &Cell<f32>| s_cell.set(0.0));
835 WEB_RAF_ACCUM_FRAMES.with(|f_cell: &Cell<u32>| f_cell.set(0));
836 return;
837 }
838 let prev_ts: f64 = WEB_RAF_LAST_TS.with(|ts_cell: &Cell<f64>| ts_cell.replace(ts));
839 let mut dt: f32 = 1.0 / 60.0;
840 let mut valid_step: bool = false;
841 if prev_ts > 0.0 {
842 let raw_dt: f32 = ((ts - prev_ts) / 1000.0) as f32;
843 if (0.001..=0.1).contains(&raw_dt) {
844 valid_step = true;
845 }
846 dt = raw_dt.clamp(0.001, 0.05);
847 }
848 if valid_step {
849 let next_secs: f32 = WEB_RAF_ACCUM_SECS.with(Cell::get) + dt;
850 let next_frames: u32 = WEB_RAF_ACCUM_FRAMES.with(Cell::get).saturating_add(1);
851 if next_secs >= 0.35 && next_frames >= 8 {
852 let measured_hz: f32 = (next_frames as f32) / next_secs;
853 WEB_RAF_ACCUM_SECS.with(|s_cell: &Cell<f32>| s_cell.set(0.0));
854 WEB_RAF_ACCUM_FRAMES.with(|f_cell: &Cell<u32>| f_cell.set(0));
855 WEB_RAF_CALIBRATED.with(|c: &Cell<bool>| c.set(true));
856 web_report_host_refresh_rate(measured_hz);
857 } else {
858 WEB_RAF_ACCUM_SECS.with(|s_cell: &Cell<f32>| s_cell.set(next_secs));
859 WEB_RAF_ACCUM_FRAMES.with(|f_cell: &Cell<u32>| f_cell.set(next_frames));
860 }
861 }
862 let live_dpr_raw: f64 = win_raf.device_pixel_ratio();
863 let live_dpr: f32 = if live_dpr_raw.is_finite() && live_dpr_raw > 0.0 {
864 (live_dpr_raw as f32).clamp(WEB_DPR_MIN, WEB_DPR_MAX)
865 } else {
866 1.0
867 };
868 let cached_dpr: f32 = WEB_CACHED_VIEWPORT.with(Cell::get).4;
869 if (live_dpr - cached_dpr).abs() > 0.005 {
870 let _: bool = web_refresh_cached_viewport(&win_raf, &canvas_raf);
871 }
872 let resized_or_scaled: bool =
873 if WEB_VIEWPORT_DIRTY.with(|flag: &Cell<bool>| flag.replace(false)) {
874 web_apply_cached_viewport(&canvas_raf)
875 } else {
876 false
877 };
878 let cur_route: String = euv_web_current_route();
879 let on_game: bool = cur_route == ROUTE_GAME
880 || cur_route == ROUTE_GAME_3D
881 || cur_route == ROUTE_WATER;
882 let animating: bool = web_has_active_animations();
883 let dirty: bool = WEB_NEEDS_FRAME.with(|flag: &Cell<bool>| flag.replace(false))
884 || is_frame_needed();
885 let needs_continuous: bool = resized_or_scaled || on_game;
886 let needs_redraw: bool = animating || dirty;
887 if needs_continuous || needs_redraw {
888 let _: u64 = web_flush_frame(dt);
889 web_record_raf_submission_proxy_tick(&canvas_raf);
890 }
891 let calibrated: bool = WEB_RAF_CALIBRATED.with(Cell::get);
892 let still_active: bool = on_game
893 || web_has_active_animations()
894 || WEB_NEEDS_FRAME.with(Cell::get)
895 || is_frame_needed()
896 || !calibrated;
897 if still_active && web_should_pump_frames() {
898 web_start_raf_pump(&win_raf);
899 } else {
900 WEB_RAF_LAST_TS.with(|ts_cell: &Cell<f64>| ts_cell.set(0.0));
901 }
902 }) as Box<dyn FnMut(f64)>));
903 }
904 });
905 if doc.hidden() {
906 web_dispatch_system_event(SystemEvent::Background);
907 } else {
908 web_start_raf_pump(&win);
909 }
910}
911
912#[cfg(target_arch = "wasm32")]
918fn web_record_raf_submission_proxy_tick(canvas: &HtmlCanvasElement) {
919 let pixel_bytes: u64 = u64::from(canvas.width())
920 .saturating_mul(u64::from(canvas.height()))
921 .saturating_mul(4);
922 WEB_DUAL_CANVAS_COORDINATOR.with(|cell: &RefCell<ShowcaseWebDualCanvasCoordinator>| {
923 if let Ok(mut coord) = cell.try_borrow_mut() {
924 coord.record_raf_proxy_tick(pixel_bytes);
925 }
926 });
927}
928
929#[cfg(target_arch = "wasm32")]
941#[must_use]
942pub fn web_begin_independent_canvas_switch(
943 target: ShowcaseWebPresentationPath,
944 width: u32,
945 height: u32,
946) -> bool {
947 WEB_DUAL_CANVAS_COORDINATOR.with(|cell: &RefCell<ShowcaseWebDualCanvasCoordinator>| {
948 cell.try_borrow_mut()
949 .map(|mut coord: RefMut<'_, ShowcaseWebDualCanvasCoordinator>| {
950 coord.begin_switch(target, width, height)
951 })
952 .unwrap_or(false)
953 })
954}
955
956#[cfg(target_arch = "wasm32")]
968#[must_use]
969pub fn web_commit_independent_canvas_switch(
970 expected_width: u32,
971 expected_height: u32,
972 expected_scene_version: u64,
973) -> bool {
974 WEB_DUAL_CANVAS_COORDINATOR.with(|cell: &RefCell<ShowcaseWebDualCanvasCoordinator>| {
975 cell.try_borrow_mut()
976 .map(|mut coord: RefMut<'_, ShowcaseWebDualCanvasCoordinator>| {
977 coord.commit_at_frame_boundary(
978 expected_width,
979 expected_height,
980 expected_scene_version,
981 )
982 })
983 .unwrap_or(false)
984 })
985}
986
987#[cfg(target_arch = "wasm32")]
993#[must_use]
994pub fn web_dual_canvas_snapshot() -> ShowcaseWebDualCanvasCoordinator {
995 WEB_DUAL_CANVAS_COORDINATOR
996 .with(|cell: &RefCell<ShowcaseWebDualCanvasCoordinator>| cell.borrow().clone())
997}
998
999#[cfg(target_arch = "wasm32")]
1005fn web_should_pump_frames() -> bool {
1006 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1007 match slot.try_borrow() {
1008 Ok(guard) => {
1009 let pump: bool = guard
1010 .as_ref()
1011 .map(|(app, _): &(App, ShowcaseState)| app.should_pump_frames())
1012 .unwrap_or(false);
1013 WEB_SHOULD_PUMP.with(|flag: &Cell<bool>| flag.set(pump));
1014 pump
1015 }
1016 Err(_) => WEB_SHOULD_PUMP.with(Cell::get),
1017 }
1018 })
1019}
1020
1021#[cfg(target_arch = "wasm32")]
1027fn web_start_raf_pump(win: &Window) {
1028 if !web_should_pump_frames() {
1029 return;
1030 }
1031 let already_scheduled: bool =
1032 WEB_RAF_ID.with(|id_cell: &Cell<Option<i32>>| id_cell.get().is_some());
1033 if already_scheduled {
1034 return;
1035 }
1036 WEB_RAF_CALLBACK.with(|slot: &RefCell<Option<Closure<dyn FnMut(f64)>>>| {
1037 if let Ok(cb_ref) = slot.try_borrow()
1038 && let Some(cb) = cb_ref.as_ref()
1039 {
1040 let func: &Function = cb.as_ref().unchecked_ref();
1041 if let Ok(req_id) = win.request_animation_frame(func) {
1042 WEB_RAF_ID.with(|id_cell: &Cell<Option<i32>>| id_cell.set(Some(req_id)));
1043 }
1044 }
1045 });
1046}
1047
1048#[cfg(target_arch = "wasm32")]
1050fn web_stop_raf_pump() {
1051 let pending_id: Option<i32> = WEB_RAF_ID.with(|id_cell: &Cell<Option<i32>>| id_cell.take());
1052 if let Some(req_id) = pending_id
1053 && let Some(win) = window()
1054 {
1055 drop(win.cancel_animation_frame(req_id));
1056 }
1057 WEB_RAF_LAST_TS.with(|ts_cell: &Cell<f64>| ts_cell.set(0.0));
1058 WEB_RAF_ACCUM_SECS.with(|s_cell: &Cell<f32>| s_cell.set(0.0));
1059 WEB_RAF_ACCUM_FRAMES.with(|f_cell: &Cell<u32>| f_cell.set(0));
1060}
1061
1062#[cfg(target_arch = "wasm32")]
1068fn web_dispatch_system_event(event: SystemEvent) {
1069 let mut should_pump: bool = false;
1070 let mut handled: bool = false;
1071 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1072 if let Ok(mut borrow) = slot.try_borrow_mut()
1073 && let Some((app, _)) = borrow.as_mut()
1074 {
1075 app.dispatch_system_event(event);
1076 should_pump = app.should_pump_frames();
1077 handled = true;
1078 }
1079 });
1080 if !handled {
1081 return;
1082 }
1083 WEB_SHOULD_PUMP.with(|flag: &Cell<bool>| flag.set(should_pump));
1084 if !should_pump {
1085 web_stop_raf_pump();
1086 } else {
1087 WEB_RAF_LAST_TS.with(|ts_cell: &Cell<f64>| ts_cell.set(0.0));
1088 web_mark_needs_frame();
1089 if let Some(win) = window() {
1090 web_start_raf_pump(&win);
1091 }
1092 }
1093}
1094
1095#[cfg(target_arch = "wasm32")]
1105fn web_extract_paste_text(ev: &Event) -> Option<String> {
1106 let data: JsValue =
1107 Reflect::get(ev.as_ref(), &JsValue::from_str(WEB_PROP_CLIPBOARD_DATA)).ok()?;
1108 if data.is_null() || data.is_undefined() {
1109 return None;
1110 }
1111 let get_fn_val: JsValue = Reflect::get(&data, &JsValue::from_str(WEB_PROP_GET_DATA)).ok()?;
1112 let get_fn: Function = get_fn_val.dyn_into::<Function>().ok()?;
1113 let result: JsValue = get_fn
1114 .call1(&data, &JsValue::from_str(WEB_MIME_TEXT_PLAIN))
1115 .ok()?;
1116 result.as_string().filter(|s: &String| !s.is_empty())
1117}
1118
1119#[cfg(target_arch = "wasm32")]
1129fn web_is_copy_proxy_event(ev: &Event) -> bool {
1130 let Some(target) = ev.target() else {
1131 return false;
1132 };
1133 let Ok(el) = target.dyn_into::<Element>() else {
1134 return false;
1135 };
1136 el.get_attribute(WEB_ATTR_COPY_PROXY).as_deref() == Some(WEB_COPY_PROXY_FLAG)
1137}
1138
1139#[cfg(target_arch = "wasm32")]
1145fn web_selected_text_snapshot() -> Option<String> {
1146 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1147 let Ok(guard) = slot.try_borrow() else {
1148 return None;
1149 };
1150 let (app, _): &(App, ShowcaseState) = guard.as_ref()?;
1151 app.get_scene()
1152 .get_selected_text()
1153 .filter(|s: &String| !s.is_empty())
1154 })
1155}
1156
1157#[cfg(target_arch = "wasm32")]
1168fn web_write_copy_event_text(ev: &Event, text: &str) -> bool {
1169 let Ok(data) = Reflect::get(ev.as_ref(), &JsValue::from_str(WEB_PROP_CLIPBOARD_DATA)) else {
1170 return false;
1171 };
1172 if data.is_null() || data.is_undefined() {
1173 return false;
1174 }
1175 let Ok(set_fn_val) = Reflect::get(&data, &JsValue::from_str(WEB_PROP_SET_DATA)) else {
1176 return false;
1177 };
1178 let Ok(set_fn) = set_fn_val.dyn_into::<Function>() else {
1179 return false;
1180 };
1181 set_fn
1182 .call2(
1183 &data,
1184 &JsValue::from_str(WEB_MIME_TEXT_PLAIN),
1185 &JsValue::from_str(text),
1186 )
1187 .is_ok()
1188}
1189
1190#[cfg(target_arch = "wasm32")]
1196fn web_sync_route_from_browser_history(win: &Window) {
1197 let raw_hash: String = win.location().hash().unwrap_or_default();
1198 let prev_guard: bool = WEB_SYNCING_FROM_HISTORY.with(|flag: &Cell<bool>| flag.replace(true));
1199 let mut updated: bool = false;
1200 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1201 if let Ok(mut borrow) = slot.try_borrow_mut()
1202 && let Some((app, state)) = borrow.as_mut()
1203 {
1204 let _: String = apply_showcase_history_route(app, state, &raw_hash);
1205 updated = true;
1206 }
1207 });
1208 WEB_SYNCING_FROM_HISTORY.with(|flag: &Cell<bool>| flag.set(prev_guard));
1209 if updated {
1210 let _: bool = web_sync_safe_area();
1211 web_mark_needs_frame();
1212 web_start_raf_pump(win);
1213 }
1214 if let Ok(href) = win.location().href() {
1215 web_dispatch_system_event(SystemEvent::DeepLink(href));
1216 }
1217}
1218
1219#[cfg(target_arch = "wasm32")]
1229fn web_doc_is_fullscreen(doc: &Document) -> bool {
1230 if doc.fullscreen_element().is_some() {
1231 return true;
1232 }
1233 Reflect::get(
1234 doc.as_ref(),
1235 &JsValue::from_str(WEB_PROP_WEBKIT_FULLSCREEN_ELEMENT),
1236 )
1237 .ok()
1238 .map(|v: JsValue| !v.is_null() && !v.is_undefined())
1239 .unwrap_or(false)
1240}
1241
1242#[cfg(target_arch = "wasm32")]
1250fn web_add_non_passive_listener(target: &EventTarget, event: &str, callback: &Function) {
1251 let opts: Object = Object::new();
1252 let _: Result<bool, JsValue> = Reflect::set(
1253 opts.as_ref(),
1254 &JsValue::from_str(WEB_OPT_PASSIVE),
1255 &JsValue::FALSE,
1256 );
1257 if let Ok(add_val) = Reflect::get(
1258 target.as_ref(),
1259 &JsValue::from_str(WEB_METHOD_ADD_EVENT_LISTENER),
1260 ) && let Ok(add_fn) = add_val.dyn_into::<Function>()
1261 && add_fn
1262 .call3(
1263 target.as_ref(),
1264 &JsValue::from_str(event),
1265 callback.as_ref(),
1266 opts.as_ref(),
1267 )
1268 .is_ok()
1269 {
1270 return;
1271 }
1272 drop(target.add_event_listener_with_callback(event, callback));
1273}
1274
1275#[cfg(target_arch = "wasm32")]
1277fn web_ensure_visible_foreground() {
1278 if WEB_SHOULD_PUMP.with(Cell::get) {
1279 return;
1280 }
1281 let is_hidden: bool = window()
1282 .and_then(|w: Window| w.document())
1283 .map(|d: Document| d.hidden())
1284 .unwrap_or(false);
1285 if !is_hidden {
1286 web_dispatch_system_event(SystemEvent::Foreground);
1287 }
1288}
1289
1290#[cfg(target_arch = "wasm32")]
1297fn web_apply_viewport_resize_immediate(win: &Window, canvas: &HtmlCanvasElement) {
1298 web_ensure_visible_foreground();
1299 let viewport_changed: bool = web_refresh_cached_viewport(win, canvas);
1300 let safe_changed: bool = web_sync_safe_area();
1301 let applied: bool = web_apply_cached_viewport(canvas);
1302 let changed_metrics: bool = viewport_changed || safe_changed;
1303 if changed_metrics || applied {
1304 WEB_VIEWPORT_DIRTY.with(|flag: &Cell<bool>| flag.set(false));
1305 let _: u64 = web_flush_frame(0.0);
1306 web_mark_needs_frame();
1307 web_start_raf_pump(win);
1308 }
1309}
1310
1311#[cfg(target_arch = "wasm32")]
1319fn web_sync_fullscreen_from_dom(win: &Window, doc: &Document, canvas: &HtmlCanvasElement) {
1320 web_ensure_visible_foreground();
1321 let dom_fs: bool = web_doc_is_fullscreen(doc);
1322 if !dom_fs {
1323 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1324 if let Ok(mut borrow) = slot.try_borrow_mut()
1325 && let Some((app, _)) = borrow.as_mut()
1326 && (app.is_immersive_fullscreen()
1327 || is_fullscreen_active()
1328 || EuvOverlayStack::has_fullscreen())
1329 {
1330 let _: usize = sync_external_fullscreen_exit();
1331 app.set_immersive_fullscreen(false);
1332 }
1333 });
1334 }
1335 let _: bool = web_refresh_cached_viewport(win, canvas);
1336 let _: bool = web_sync_safe_area();
1337 let _: bool = web_apply_cached_viewport(canvas);
1338 WEB_VIEWPORT_DIRTY.with(|flag: &Cell<bool>| flag.set(false));
1339 let _: u64 = web_flush_frame(0.0);
1340 web_mark_needs_frame();
1341 web_start_raf_pump(win);
1342}
1343
1344#[cfg(target_arch = "wasm32")]
1350fn web_dispatch_theme_changed(mode: ThemeMode) {
1351 let mut dispatched: bool = false;
1352 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1353 if let Ok(mut borrow) = slot.try_borrow_mut()
1354 && let Some((app, _)) = borrow.as_mut()
1355 {
1356 let wid: WindowId = app.get_window_state().get_id();
1357 app.dispatch_window_event(WindowEvent::ThemeChanged(wid, mode));
1358 dispatched = true;
1359 }
1360 });
1361 if dispatched {
1362 web_mark_needs_frame();
1363 }
1364}
1365
1366#[cfg(target_arch = "wasm32")]
1373fn web_handle_orientation_change(win: &Window, canvas: &HtmlCanvasElement) {
1374 web_apply_viewport_resize_immediate(win, canvas);
1375 let (_, _, css_w, css_h, _): (f64, f64, f64, f64, f32) = WEB_CACHED_VIEWPORT.with(Cell::get);
1376 let orient: ScreenOrientation = if css_w > css_h {
1377 ScreenOrientation::Landscape
1378 } else {
1379 ScreenOrientation::Portrait
1380 };
1381 web_dispatch_system_event(SystemEvent::OrientationChanged(orient));
1382 let _: u64 = web_flush_frame(0.0);
1383 web_mark_needs_frame();
1384 web_start_raf_pump(win);
1385}
1386
1387#[cfg(target_arch = "wasm32")]
1395fn web_attach_system_event_listeners(win: &Window, doc: &Document, canvas: &HtmlCanvasElement) {
1396 let doc_vis: Document = doc.clone();
1397 let win_vis: Window = win.clone();
1398 let canvas_vis: HtmlCanvasElement = canvas.clone();
1399 let on_vis: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1400 if doc_vis.hidden() {
1401 web_queue_pointer_cancel(0);
1402 web_dispatch_system_event(SystemEvent::Background);
1403 } else {
1404 let _: bool = web_refresh_cached_viewport(&win_vis, &canvas_vis);
1405 let _: bool = web_sync_safe_area();
1406 web_dispatch_system_event(SystemEvent::Foreground);
1407 }
1408 }) as Box<dyn FnMut(Event)>);
1409 drop(doc.add_event_listener_with_callback(
1410 WEB_EVENT_VISIBILITY_CHANGE,
1411 on_vis.as_ref().unchecked_ref(),
1412 ));
1413 on_vis.forget();
1414 let win_focus: Window = win.clone();
1415 let canvas_focus: HtmlCanvasElement = canvas.clone();
1416 let on_focus: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1417 let _: bool = web_refresh_cached_viewport(&win_focus, &canvas_focus);
1418 let _: bool = web_sync_safe_area();
1419 web_dispatch_system_event(SystemEvent::Foreground);
1420 web_dispatch_system_event(SystemEvent::FocusChanged(true));
1421 }) as Box<dyn FnMut(Event)>);
1422 drop(win.add_event_listener_with_callback(WEB_EVENT_FOCUS, on_focus.as_ref().unchecked_ref()));
1423 on_focus.forget();
1424 let win_ps: Window = win.clone();
1425 let canvas_ps: HtmlCanvasElement = canvas.clone();
1426 let on_pageshow: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1427 let _: bool = web_refresh_cached_viewport(&win_ps, &canvas_ps);
1428 let _: bool = web_sync_safe_area();
1429 web_sync_route_from_browser_history(&win_ps);
1430 web_dispatch_system_event(SystemEvent::Foreground);
1431 }) as Box<dyn FnMut(Event)>);
1432 drop(win.add_event_listener_with_callback(
1433 WEB_EVENT_PAGE_SHOW,
1434 on_pageshow.as_ref().unchecked_ref(),
1435 ));
1436 on_pageshow.forget();
1437 let on_pagehide: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1438 web_queue_pointer_cancel(0);
1439 web_dispatch_system_event(SystemEvent::Background);
1440 }) as Box<dyn FnMut(Event)>);
1441 drop(win.add_event_listener_with_callback(
1442 WEB_EVENT_PAGE_HIDE,
1443 on_pagehide.as_ref().unchecked_ref(),
1444 ));
1445 on_pagehide.forget();
1446 let on_unload: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1447 web_dispatch_system_event(SystemEvent::Terminate);
1448 }) as Box<dyn FnMut(Event)>);
1449 drop(win.add_event_listener_with_callback(
1450 WEB_EVENT_BEFORE_UNLOAD,
1451 on_unload.as_ref().unchecked_ref(),
1452 ));
1453 on_unload.forget();
1454 let on_online: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1455 web_dispatch_system_event(SystemEvent::NetworkStatusChanged(NetworkStatus::Online));
1456 }) as Box<dyn FnMut(Event)>);
1457 drop(
1458 win.add_event_listener_with_callback(WEB_EVENT_ONLINE, on_online.as_ref().unchecked_ref()),
1459 );
1460 on_online.forget();
1461 let on_offline: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1462 web_dispatch_system_event(SystemEvent::NetworkStatusChanged(NetworkStatus::Offline));
1463 }) as Box<dyn FnMut(Event)>);
1464 drop(
1465 win.add_event_listener_with_callback(
1466 WEB_EVENT_OFFLINE,
1467 on_offline.as_ref().unchecked_ref(),
1468 ),
1469 );
1470 on_offline.forget();
1471 if let Ok(Some(mql)) = win.match_media(WEB_MEDIA_PREFERS_DARK) {
1472 let mql_cb: MediaQueryList = mql.clone();
1473 let on_theme: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1474 let next_theme: ThemeMode = if mql_cb.matches() {
1475 ThemeMode::Dark
1476 } else {
1477 ThemeMode::Light
1478 };
1479 web_dispatch_theme_changed(next_theme);
1480 })
1481 as Box<dyn FnMut(Event)>);
1482 drop(
1483 mql.add_event_listener_with_callback(
1484 WEB_EVENT_CHANGE,
1485 on_theme.as_ref().unchecked_ref(),
1486 ),
1487 );
1488 on_theme.forget();
1489 }
1490 let win_hist: Window = win.clone();
1491 let on_history: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1492 web_sync_route_from_browser_history(&win_hist);
1493 }) as Box<dyn FnMut(Event)>);
1494 drop(win.add_event_listener_with_callback(
1495 WEB_EVENT_HASH_CHANGE,
1496 on_history.as_ref().unchecked_ref(),
1497 ));
1498 drop(win.add_event_listener_with_callback(
1499 WEB_EVENT_POP_STATE,
1500 on_history.as_ref().unchecked_ref(),
1501 ));
1502 on_history.forget();
1503 let win_fs: Window = win.clone();
1504 let doc_fs: Document = doc.clone();
1505 let canvas_fs: HtmlCanvasElement = canvas.clone();
1506 let on_fs_change: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1507 web_sync_fullscreen_from_dom(&win_fs, &doc_fs, &canvas_fs);
1508 }) as Box<dyn FnMut(Event)>);
1509 drop(doc.add_event_listener_with_callback(
1510 WEB_EVENT_FULLSCREEN_CHANGE,
1511 on_fs_change.as_ref().unchecked_ref(),
1512 ));
1513 drop(doc.add_event_listener_with_callback(
1514 WEB_EVENT_WEBKIT_FULLSCREEN_CHANGE,
1515 on_fs_change.as_ref().unchecked_ref(),
1516 ));
1517 on_fs_change.forget();
1518 let win_orient: Window = win.clone();
1519 let canvas_orient: HtmlCanvasElement = canvas.clone();
1520 let on_orient: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1521 web_handle_orientation_change(&win_orient, &canvas_orient);
1522 }) as Box<dyn FnMut(Event)>);
1523 drop(win.add_event_listener_with_callback(
1524 WEB_EVENT_ORIENTATION_CHANGE,
1525 on_orient.as_ref().unchecked_ref(),
1526 ));
1527 if let Ok(screen_val) = Reflect::get(win.as_ref(), &JsValue::from_str(WEB_PROP_SCREEN))
1528 && !screen_val.is_null()
1529 && !screen_val.is_undefined()
1530 && let Ok(orient_val) = Reflect::get(&screen_val, &JsValue::from_str(WEB_PROP_ORIENTATION))
1531 && let Ok(orient_target) = orient_val.dyn_into::<EventTarget>()
1532 {
1533 drop(orient_target.add_event_listener_with_callback(
1534 WEB_EVENT_CHANGE,
1535 on_orient.as_ref().unchecked_ref(),
1536 ));
1537 }
1538 on_orient.forget();
1539 let vv_key: JsValue = JsValue::from_str(WEB_PROP_VISUAL_VIEWPORT);
1540 if let Ok(vv_val) = Reflect::get(win.as_ref(), &vv_key)
1541 && let Ok(vv_target) = vv_val.clone().dyn_into::<EventTarget>()
1542 {
1543 let win_vv: Window = win.clone();
1544 let vv_obj: JsValue = vv_val;
1545 let on_vv_resize: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1546 let inner_h: f32 = win_vv
1547 .inner_height()
1548 .ok()
1549 .and_then(|v: JsValue| v.as_f64())
1550 .unwrap_or(0.0) as f32;
1551 let h_key: JsValue = JsValue::from_str(WEB_PROP_HEIGHT);
1552 let vv_h: f32 = Reflect::get(&vv_obj, &h_key)
1553 .ok()
1554 .and_then(|v: JsValue| v.as_f64())
1555 .unwrap_or(inner_h as f64) as f32;
1556 let kb_delta: f32 = (inner_h - vv_h).max(0.0);
1557 let visible: bool = kb_delta >= WEB_KEYBOARD_MIN_DELTA_PX;
1558 let height: f32 = if visible { kb_delta } else { 0.0 };
1559 web_dispatch_system_event(SystemEvent::KeyboardVisibilityChanged { visible, height });
1560 if web_sync_safe_area() {
1561 web_mark_needs_frame();
1562 }
1563 })
1564 as Box<dyn FnMut(Event)>);
1565 drop(vv_target.add_event_listener_with_callback(
1566 WEB_EVENT_RESIZE,
1567 on_vv_resize.as_ref().unchecked_ref(),
1568 ));
1569 on_vv_resize.forget();
1570 }
1571}
1572
1573#[cfg(target_arch = "wasm32")]
1584fn web_map_key(key: &str, code_str: &str) -> KeyCode {
1585 match code_str {
1586 WEB_CODE_KEY_W => return KeyCode::Character('w'),
1587 WEB_CODE_KEY_A => return KeyCode::Character('a'),
1588 WEB_CODE_KEY_S => return KeyCode::Character('s'),
1589 WEB_CODE_KEY_D => return KeyCode::Character('d'),
1590 WEB_CODE_KEY_E => return KeyCode::Character('e'),
1591 WEB_CODE_KEY_R => return KeyCode::Character('r'),
1592 WEB_CODE_KEY_P => return KeyCode::Character('p'),
1593 WEB_CODE_KEY_J => return KeyCode::Character('j'),
1594 WEB_CODE_KEY_C => return KeyCode::Character('c'),
1595 WEB_CODE_KEY_V => return KeyCode::Character('v'),
1596 WEB_CODE_KEY_X => return KeyCode::Character('x'),
1597 WEB_CODE_KEY_Z => return KeyCode::Character('z'),
1598 WEB_CODE_KEY_K => return KeyCode::Character('k'),
1599 WEB_CODE_SPACE => return KeyCode::Space,
1600 WEB_KEY_ARROW_LEFT => return KeyCode::ArrowLeft,
1601 WEB_KEY_ARROW_RIGHT => return KeyCode::ArrowRight,
1602 WEB_KEY_ARROW_UP => return KeyCode::ArrowUp,
1603 WEB_KEY_ARROW_DOWN => return KeyCode::ArrowDown,
1604 WEB_KEY_HOME => return KeyCode::Home,
1605 WEB_KEY_END => return KeyCode::End,
1606 WEB_KEY_PAGE_UP => return KeyCode::PageUp,
1607 WEB_KEY_PAGE_DOWN => return KeyCode::PageDown,
1608 _ => {}
1609 }
1610 match key {
1611 WEB_KEY_ENTER => KeyCode::Enter,
1612 WEB_KEY_BACKSPACE => KeyCode::Backspace,
1613 WEB_KEY_DELETE => KeyCode::Delete,
1614 WEB_KEY_ESCAPE => KeyCode::Escape,
1615 WEB_KEY_TAB => KeyCode::Tab,
1616 WEB_KEY_SPACE => KeyCode::Space,
1617 WEB_KEY_ARROW_LEFT => KeyCode::ArrowLeft,
1618 WEB_KEY_ARROW_RIGHT => KeyCode::ArrowRight,
1619 WEB_KEY_ARROW_UP => KeyCode::ArrowUp,
1620 WEB_KEY_ARROW_DOWN => KeyCode::ArrowDown,
1621 WEB_KEY_HOME => KeyCode::Home,
1622 WEB_KEY_END => KeyCode::End,
1623 WEB_KEY_PAGE_UP => KeyCode::PageUp,
1624 WEB_KEY_PAGE_DOWN => KeyCode::PageDown,
1625 other => other
1626 .chars()
1627 .next()
1628 .map(KeyCode::Character)
1629 .unwrap_or(KeyCode::Unknown),
1630 }
1631}
1632
1633#[cfg(target_arch = "wasm32")]
1639fn web_has_active_animations() -> bool {
1640 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1641 match slot.try_borrow() {
1642 Ok(guard) => guard
1643 .as_ref()
1644 .map(|(app, _): &(App, ShowcaseState)| app.has_active_animations())
1645 .unwrap_or(false),
1646 Err(_) => false,
1647 }
1648 })
1649}
1650
1651#[cfg(target_arch = "wasm32")]
1653fn web_mark_needs_frame() {
1654 WEB_NEEDS_FRAME.with(|flag: &Cell<bool>| flag.set(true));
1655 let idle: bool = WEB_RAF_ID.with(|id_cell: &Cell<Option<i32>>| id_cell.get().is_none());
1656 if idle && let Some(win) = window() {
1657 web_start_raf_pump(&win);
1658 }
1659}
1660
1661#[cfg(target_arch = "wasm32")]
1671fn web_pointer_id_from_dom(ev: &web_sys::PointerEvent) -> u64 {
1672 (ev.pointer_id() as i64).unsigned_abs().saturating_add(1)
1673}
1674
1675#[cfg(target_arch = "wasm32")]
1686fn web_pointer_from_dom(ev: &web_sys::PointerEvent, force_pressed: Option<bool>) -> PointerEvent {
1687 let (left, top, _, _, _): (f64, f64, f64, f64, f32) = WEB_CACHED_VIEWPORT.with(Cell::get);
1688 let x: f32 = (ev.client_x() as f64 - left) as f32;
1689 let y: f32 = (ev.client_y() as f64 - top) as f32;
1690 let pid: u64 = web_pointer_id_from_dom(ev);
1691 let ptype: String = ev.pointer_type();
1692 let device: PointerDevice = if ptype == WEB_PTR_TYPE_TOUCH {
1693 PointerDevice::Touch
1694 } else if ptype == WEB_PTR_TYPE_PEN {
1695 PointerDevice::Stylus
1696 } else {
1697 PointerDevice::Mouse
1698 };
1699 let is_pressed: bool =
1700 force_pressed.unwrap_or_else(|| ev.buttons() != 0 || device == PointerDevice::Touch);
1701 let pressure: f32 = if is_pressed { 1.0 } else { 0.0 };
1702 let mods: Modifiers =
1703 Modifiers::new(ev.shift_key(), ev.ctrl_key(), ev.alt_key(), ev.meta_key());
1704 PointerEvent::new(
1705 pid,
1706 device,
1707 Point::new(x, y),
1708 PointerButton::Primary,
1709 pressure,
1710 mods,
1711 )
1712}
1713
1714#[cfg(target_arch = "wasm32")]
1720fn web_queue_pointer_move_event(ptr: PointerEvent) {
1721 let mut needs_redraw: bool = false;
1722 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1723 if let Ok(mut borrow) = slot.try_borrow_mut()
1724 && let Some((app, _)) = borrow.as_mut()
1725 {
1726 let rev_before: u64 = app.get_scene().with_read(SceneTree::get_revision, 0);
1727 let cursor_before: CursorIcon = app.get_last_cursor();
1728 let wid: WindowId = app.get_window_state().get_id();
1729 app.dispatch_window_event(WindowEvent::PointerMove(wid, ptr));
1730 let rev_after: u64 = app.get_scene().with_read(SceneTree::get_revision, 0);
1731 let cursor_after: CursorIcon = app.get_last_cursor();
1732 let active_drag: bool =
1733 ptr.get_pressure() > 0.0 || ptr.get_device() != PointerDevice::Mouse;
1734 let has_anim: bool = app
1735 .get_scene()
1736 .with_read(SceneTree::has_active_transitions, false);
1737 needs_redraw = rev_after != rev_before
1738 || cursor_after != cursor_before
1739 || active_drag
1740 || has_anim
1741 || is_frame_needed();
1742 }
1743 });
1744 if needs_redraw {
1745 web_mark_needs_frame();
1746 }
1747}
1748
1749#[cfg(target_arch = "wasm32")]
1755fn web_queue_pointer_down_event(ptr: PointerEvent) {
1756 web_ensure_visible_foreground();
1757 let mut queued: bool = false;
1758 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1759 if let Ok(mut borrow) = slot.try_borrow_mut()
1760 && let Some((app, _)) = borrow.as_mut()
1761 {
1762 let wid: WindowId = app.get_window_state().get_id();
1763 app.dispatch_window_event(WindowEvent::PointerDown(wid, ptr));
1764 queued = true;
1765 }
1766 });
1767 if queued {
1768 web_mark_needs_frame();
1769 }
1770}
1771
1772#[cfg(target_arch = "wasm32")]
1778fn web_queue_pointer_up_event(ptr: PointerEvent) {
1779 let mut queued: bool = false;
1780 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1781 if let Ok(mut borrow) = slot.try_borrow_mut()
1782 && let Some((app, _)) = borrow.as_mut()
1783 {
1784 let wid: WindowId = app.get_window_state().get_id();
1785 app.dispatch_window_event(WindowEvent::PointerUp(wid, ptr));
1786 queued = true;
1787 }
1788 });
1789 if queued {
1790 web_mark_needs_frame();
1791 }
1792}
1793
1794#[cfg(target_arch = "wasm32")]
1800fn web_queue_pointer_cancel(pointer_id: u64) {
1801 let mut queued: bool = false;
1802 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1803 if let Ok(mut borrow) = slot.try_borrow_mut()
1804 && let Some((app, _)) = borrow.as_mut()
1805 {
1806 let wid: WindowId = app.get_window_state().get_id();
1807 app.dispatch_window_event(WindowEvent::PointerCancel(wid, pointer_id));
1808 queued = true;
1809 }
1810 });
1811 if queued {
1812 web_mark_needs_frame();
1813 }
1814}
1815
1816#[cfg(target_arch = "wasm32")]
1825fn web_queue_scroll_at(x: f32, y: f32, dx: f32, dy: f32) {
1826 web_ensure_visible_foreground();
1827 let mut queued: bool = false;
1828 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1829 if let Ok(mut borrow) = slot.try_borrow_mut()
1830 && let Some((app, _)) = borrow.as_mut()
1831 {
1832 let wid: WindowId = app.get_window_state().get_id();
1833 app.dispatch_window_event(WindowEvent::PointerMove(wid, PointerEvent::mouse(x, y)));
1834 app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(dx, dy)));
1835 queued = true;
1836 }
1837 });
1838 if queued {
1839 web_mark_needs_frame();
1840 }
1841}
1842
1843#[cfg(target_arch = "wasm32")]
1852fn web_queue_key_down(key: &str, code_str: &str, mods: Modifiers, repeat: bool) {
1853 if WEB_IME_COMPOSING.with(Cell::get) {
1854 return;
1855 }
1856 web_ensure_visible_foreground();
1857 let ime_active: bool = WEB_IME_ACTIVE.with(Cell::get);
1858 let mut queued: bool = false;
1859 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1860 if let Ok(mut borrow) = slot.try_borrow_mut()
1861 && let Some((app, _)) = borrow.as_mut()
1862 {
1863 let wid: WindowId = app.get_window_state().get_id();
1864 let code: KeyCode = web_map_key(key, code_str);
1865 let key_ev: WindowEvent = WindowEvent::KeyDown(wid, KeyEvent::new(code, mods, repeat));
1866 app.dispatch_window_event(key_ev);
1867 if web_should_dispatch_text_input(ime_active, mods, key) {
1868 app.dispatch_window_event(WindowEvent::TextInput(wid, key.to_string()));
1869 }
1870 queued = true;
1871 }
1872 });
1873 if queued {
1874 web_mark_needs_frame();
1875 }
1876}
1877
1878#[cfg(target_arch = "wasm32")]
1884fn web_queue_text_input(text: String) {
1885 if text.is_empty() {
1886 return;
1887 }
1888 let mut queued: bool = false;
1889 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1890 if let Ok(mut borrow) = slot.try_borrow_mut()
1891 && let Some((app, _)) = borrow.as_mut()
1892 {
1893 let wid: WindowId = app.get_window_state().get_id();
1894 app.dispatch_window_event(WindowEvent::TextInput(wid, text));
1895 queued = true;
1896 }
1897 });
1898 if queued {
1899 web_mark_needs_frame();
1900 }
1901}
1902
1903#[cfg(target_arch = "wasm32")]
1910fn web_flush_ime_element(el: &HtmlElement, fallback: Option<String>) {
1911 let key: JsValue = JsValue::from_str(WEB_PROP_VALUE);
1912 let el_text: Option<String> = Reflect::get(el.as_ref(), &key)
1913 .ok()
1914 .and_then(|val: JsValue| val.as_string())
1915 .filter(|s: &String| !s.is_empty());
1916 let _: Result<bool, JsValue> = Reflect::set(el.as_ref(), &key, &JsValue::from_str(""));
1917 let committed: Option<String> = el_text.or_else(|| fallback.filter(|s: &String| !s.is_empty()));
1918 if let Some(text) = committed {
1919 web_queue_text_input(text);
1920 }
1921}
1922
1923#[cfg(target_arch = "wasm32")]
1933fn web_event_is_composing(ev: &Event) -> bool {
1934 Reflect::get(ev.as_ref(), &JsValue::from_str(WEB_PROP_IS_COMPOSING))
1935 .ok()
1936 .and_then(|val: JsValue| val.as_bool())
1937 .unwrap_or(false)
1938}
1939
1940#[cfg(target_arch = "wasm32")]
1950fn web_event_data_string(ev: &Event) -> Option<String> {
1951 Reflect::get(ev.as_ref(), &JsValue::from_str(WEB_PROP_DATA))
1952 .ok()
1953 .and_then(|val: JsValue| val.as_string())
1954 .filter(|s: &String| !s.is_empty())
1955}
1956
1957#[cfg(target_arch = "wasm32")]
1963fn web_attach_ime_proxy(doc: &Document) {
1964 let Ok(raw_el) = doc.create_element(WEB_IME_INPUT_TAG) else {
1965 return;
1966 };
1967 let el: Element = raw_el;
1968 drop(el.set_attribute(WEB_IME_ATTR_ID, WEB_IME_INPUT_ID));
1969 drop(el.set_attribute(WEB_IME_ATTR_TYPE, WEB_IME_ATTR_TEXT));
1970 drop(el.set_attribute(WEB_IME_ATTR_AUTOCOMPLETE, WEB_IME_ATTR_OFF));
1971 drop(el.set_attribute(WEB_IME_ATTR_AUTOCORRECT, WEB_IME_ATTR_OFF));
1972 drop(el.set_attribute(WEB_IME_ATTR_AUTOCAPITALIZE, WEB_IME_ATTR_OFF));
1973 drop(el.set_attribute(WEB_IME_ATTR_SPELLCHECK, WEB_IME_ATTR_FALSE));
1974 drop(el.set_attribute(WEB_IME_ATTR_ARIA_LABEL, WEB_IME_ARIA_LABEL));
1975 drop(el.set_attribute(WEB_IME_ATTR_STYLE, WEB_IME_STYLE));
1976 let Ok(html_el) = el.dyn_into::<HtmlElement>() else {
1977 return;
1978 };
1979 if let Some(body) = doc.body() {
1980 drop(body.append_child(&html_el));
1981 }
1982 let on_ime_focus: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1983 WEB_IME_ACTIVE.with(|a: &Cell<bool>| a.set(true));
1984 }) as Box<dyn FnMut(Event)>);
1985 drop(
1986 html_el.add_event_listener_with_callback(
1987 WEB_EVENT_FOCUS,
1988 on_ime_focus.as_ref().unchecked_ref(),
1989 ),
1990 );
1991 on_ime_focus.forget();
1992 let comp_start: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1993 WEB_IME_COMPOSING.with(|c: &Cell<bool>| c.set(true));
1994 }) as Box<dyn FnMut(Event)>);
1995 drop(html_el.add_event_listener_with_callback(
1996 WEB_EVENT_COMPOSITION_START,
1997 comp_start.as_ref().unchecked_ref(),
1998 ));
1999 comp_start.forget();
2000 let comp_update: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
2001 WEB_IME_COMPOSING.with(|c: &Cell<bool>| c.set(true));
2002 }) as Box<dyn FnMut(Event)>);
2003 drop(html_el.add_event_listener_with_callback(
2004 WEB_EVENT_COMPOSITION_UPDATE,
2005 comp_update.as_ref().unchecked_ref(),
2006 ));
2007 comp_update.forget();
2008 let comp_el: HtmlElement = html_el.clone();
2009 let comp_end: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |ev: Event| {
2010 WEB_IME_COMPOSING.with(|c: &Cell<bool>| c.set(false));
2011 let fallback: Option<String> = web_event_data_string(&ev);
2012 web_flush_ime_element(&comp_el, fallback);
2013 }) as Box<dyn FnMut(Event)>);
2014 drop(html_el.add_event_listener_with_callback(
2015 WEB_EVENT_COMPOSITION_END,
2016 comp_end.as_ref().unchecked_ref(),
2017 ));
2018 comp_end.forget();
2019 let inp_el: HtmlElement = html_el.clone();
2020 let on_input: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |ev: Event| {
2021 if !WEB_IME_COMPOSING.with(Cell::get) && !web_event_is_composing(&ev) {
2022 web_flush_ime_element(&inp_el, None);
2023 }
2024 }) as Box<dyn FnMut(Event)>);
2025 drop(
2026 html_el
2027 .add_event_listener_with_callback(WEB_EVENT_INPUT, on_input.as_ref().unchecked_ref()),
2028 );
2029 on_input.forget();
2030 let on_ime_blur: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
2031 WEB_IME_ACTIVE.with(|a: &Cell<bool>| a.set(false));
2032 WEB_IME_COMPOSING.with(|c: &Cell<bool>| c.set(false));
2033 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2034 if let Ok(mut borrow) = slot.try_borrow_mut()
2035 && let Some((app, _)) = borrow.as_mut()
2036 {
2037 let wid: WindowId = app.get_window_state().get_id();
2038 app.dispatch_window_event(WindowEvent::Ime(wid, ImeEvent::Disabled));
2039 }
2040 });
2041 }) as Box<dyn FnMut(Event)>);
2042 drop(
2043 html_el
2044 .add_event_listener_with_callback(WEB_EVENT_BLUR, on_ime_blur.as_ref().unchecked_ref()),
2045 );
2046 on_ime_blur.forget();
2047 WEB_IME_ELEMENT.with(|slot: &RefCell<Option<HtmlElement>>| {
2048 if let Ok(mut guard) = slot.try_borrow_mut() {
2049 *guard = Some(html_el);
2050 }
2051 });
2052}
2053
2054#[cfg(target_arch = "wasm32")]
2066fn web_native_action_bridge(kind: &str, arg1: &str, _arg2: &str) -> bool {
2067 if kind == NATIVE_ACTION_FULLSCREEN {
2068 if arg1 == WEB_FS_ACTION_ON {
2069 web_set_fullscreen(true);
2070 return true;
2071 }
2072 if arg1 == WEB_FS_ACTION_OFF {
2073 web_set_fullscreen(false);
2074 return true;
2075 }
2076 return false;
2077 }
2078 if kind == NATIVE_ACTION_OPEN_URL {
2079 if !is_valid_external_url(arg1) {
2080 return false;
2081 }
2082 let Some(win) = window() else {
2083 return false;
2084 };
2085 return win
2086 .open_with_url_and_target_and_features(
2087 arg1.trim(),
2088 WEB_OPEN_TARGET_BLANK,
2089 WEB_OPEN_FEATURES_SAFE,
2090 )
2091 .is_ok();
2092 }
2093 if kind != NATIVE_ACTION_IME {
2094 return false;
2095 }
2096 WEB_IME_ELEMENT.with(|slot: &RefCell<Option<HtmlElement>>| {
2097 let Ok(guard) = slot.try_borrow() else {
2098 return false;
2099 };
2100 let Some(el) = guard.as_ref() else {
2101 return false;
2102 };
2103 if arg1 == WEB_IME_ACTION_SHOW {
2104 WEB_IME_ACTIVE.with(|a: &Cell<bool>| a.set(true));
2105 let already_focused: bool = window()
2106 .and_then(|win: Window| win.document())
2107 .and_then(|doc: Document| doc.active_element())
2108 .map(|active_el: Element| active_el.id() == WEB_IME_INPUT_ID)
2109 .unwrap_or(false);
2110 if !already_focused {
2111 drop(el.focus());
2112 }
2113 true
2114 } else if arg1 == WEB_IME_ACTION_HIDE {
2115 WEB_IME_ACTIVE.with(|a: &Cell<bool>| a.set(false));
2116 WEB_IME_COMPOSING.with(|c: &Cell<bool>| c.set(false));
2117 let key: JsValue = JsValue::from_str(WEB_PROP_VALUE);
2118 let _: Result<bool, JsValue> = Reflect::set(el.as_ref(), &key, &JsValue::from_str(""));
2119 drop(el.blur());
2120 true
2121 } else {
2122 false
2123 }
2124 })
2125}
2126
2127#[cfg(target_arch = "wasm32")]
2135fn web_queue_key_up(key: &str, code_str: &str, mods: Modifiers) {
2136 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2137 if let Ok(mut borrow) = slot.try_borrow_mut()
2138 && let Some((app, _)) = borrow.as_mut()
2139 {
2140 let wid: WindowId = app.get_window_state().get_id();
2141 let code: KeyCode = web_map_key(key, code_str);
2142 app.dispatch_window_event(WindowEvent::KeyUp(wid, KeyEvent::new(code, mods, false)));
2143 }
2144 });
2145}
2146
2147#[cfg(target_arch = "wasm32")]
2157fn web_read_window_css_viewport(win: &Window) -> (f64, f64) {
2158 if let Ok(vv) = Reflect::get(win.as_ref(), &JsValue::from_str(WEB_PROP_VISUAL_VIEWPORT))
2159 && !vv.is_null()
2160 && !vv.is_undefined()
2161 {
2162 let vv_scale: f64 = Reflect::get(&vv, &JsValue::from_str(WEB_PROP_SCALE))
2163 .ok()
2164 .and_then(|v: JsValue| v.as_f64())
2165 .filter(|v: &f64| v.is_finite() && *v > 0.0)
2166 .unwrap_or(1.0);
2167 if vv_scale <= WEB_PINCH_ZOOM_THRESHOLD {
2168 let vw: Option<f64> = Reflect::get(&vv, &JsValue::from_str(WEB_PROP_WIDTH))
2169 .ok()
2170 .and_then(|v: JsValue| v.as_f64())
2171 .filter(|v: &f64| v.is_finite() && *v >= 64.0);
2172 let vh: Option<f64> = Reflect::get(&vv, &JsValue::from_str(WEB_PROP_HEIGHT))
2173 .ok()
2174 .and_then(|v: JsValue| v.as_f64())
2175 .filter(|v: &f64| v.is_finite() && *v >= 64.0);
2176 if let (Some(w), Some(h)) = (vw, vh) {
2177 return (w, h);
2178 }
2179 }
2180 }
2181 if let Some(root) = win
2182 .document()
2183 .and_then(|doc: Document| doc.document_element())
2184 {
2185 let cw: f64 = f64::from(root.client_width());
2186 let ch: f64 = f64::from(root.client_height());
2187 if cw >= 64.0 && ch >= 64.0 {
2188 return (cw, ch);
2189 }
2190 }
2191 let w: f64 = win
2192 .inner_width()
2193 .ok()
2194 .and_then(|v: JsValue| v.as_f64())
2195 .filter(|w: &f64| w.is_finite() && *w >= 64.0)
2196 .unwrap_or(SHOWCASE_WINDOW_WIDTH as f64);
2197 let h: f64 = win
2198 .inner_height()
2199 .ok()
2200 .and_then(|v: JsValue| v.as_f64())
2201 .filter(|h: &f64| h.is_finite() && *h >= 64.0)
2202 .unwrap_or(SHOWCASE_WINDOW_HEIGHT as f64);
2203 (w, h)
2204}
2205
2206#[cfg(target_arch = "wasm32")]
2212fn web_query_initial_viewport() -> (f64, f64, f64, f64, f32) {
2213 let Some(win) = window() else {
2214 return (
2215 0.0,
2216 0.0,
2217 SHOWCASE_WINDOW_WIDTH as f64,
2218 SHOWCASE_WINDOW_HEIGHT as f64,
2219 1.0,
2220 );
2221 };
2222 let dpr_raw: f64 = win.device_pixel_ratio();
2223 let dpr: f32 = if dpr_raw.is_finite() && dpr_raw > 0.0 {
2224 (dpr_raw as f32).clamp(WEB_DPR_MIN, WEB_DPR_MAX)
2225 } else {
2226 1.0
2227 };
2228 let mut left: f64 = 0.0;
2229 let mut top: f64 = 0.0;
2230 let mut css_w: f64 = 0.0;
2231 let mut css_h: f64 = 0.0;
2232 if let Some(doc) = win.document()
2233 && let Ok(Some(el)) = doc.query_selector(WEB_SELECTOR_CANVAS)
2234 && let Ok(canvas) = el.dyn_into::<HtmlCanvasElement>()
2235 {
2236 let rect: DomRect = canvas.get_bounding_client_rect();
2237 left = rect.left();
2238 top = rect.top();
2239 css_w = rect.width();
2240 css_h = rect.height();
2241 }
2242 let (win_w, win_h): (f64, f64) = web_read_window_css_viewport(&win);
2243 if !css_w.is_finite() || css_w < 64.0 {
2244 css_w = win_w;
2245 }
2246 if !css_h.is_finite() || css_h < 64.0 {
2247 css_h = win_h;
2248 }
2249 (left, top, css_w, css_h, dpr)
2250}
2251
2252#[cfg(target_arch = "wasm32")]
2263fn web_refresh_cached_viewport(win: &Window, canvas: &HtmlCanvasElement) -> bool {
2264 let rect: DomRect = canvas.get_bounding_client_rect();
2265 let left: f64 = rect.left();
2266 let top: f64 = rect.top();
2267 let (win_w, win_h): (f64, f64) = web_read_window_css_viewport(win);
2268 let css_w: f64 = if rect.width().is_finite() && rect.width() >= 64.0 {
2269 rect.width()
2270 } else {
2271 win_w
2272 };
2273 let css_h: f64 = if rect.height().is_finite() && rect.height() >= 64.0 {
2274 rect.height()
2275 } else {
2276 win_h
2277 };
2278 let dpr_raw: f64 = win.device_pixel_ratio();
2279 let dpr: f32 = if dpr_raw.is_finite() && dpr_raw > 0.0 {
2280 (dpr_raw as f32).clamp(WEB_DPR_MIN, WEB_DPR_MAX)
2281 } else {
2282 1.0
2283 };
2284 let prev: (f64, f64, f64, f64, f32) = WEB_CACHED_VIEWPORT.with(Cell::get);
2285 let changed: bool = (prev.0 - left).abs() > 0.25
2286 || (prev.1 - top).abs() > 0.25
2287 || (prev.2 - css_w).abs() > 0.25
2288 || (prev.3 - css_h).abs() > 0.25
2289 || (prev.4 - dpr).abs() > 0.005;
2290 if changed {
2291 WEB_CACHED_VIEWPORT.with(|cell: &Cell<(f64, f64, f64, f64, f32)>| {
2292 cell.set((left, top, css_w, css_h, dpr));
2293 });
2294 WEB_VIEWPORT_DIRTY.with(|flag: &Cell<bool>| flag.set(true));
2295 }
2296 changed
2297}
2298
2299#[cfg(target_arch = "wasm32")]
2309fn web_apply_cached_viewport(canvas: &HtmlCanvasElement) -> bool {
2310 let (_, _, css_w, css_h, dpr): (f64, f64, f64, f64, f32) = WEB_CACHED_VIEWPORT.with(Cell::get);
2311 let dpr_f64: f64 = f64::from(dpr);
2312 let est_w: u32 = (css_w * dpr_f64)
2313 .round()
2314 .clamp(1.0, WEB_CANVAS_MAX_PHYS_DIM) as u32;
2315 let est_h: u32 = (css_h * dpr_f64)
2316 .round()
2317 .clamp(1.0, WEB_CANVAS_MAX_PHYS_DIM) as u32;
2318 let (obs_w, obs_h): (u32, u32) = WEB_OBSERVED_PHYS_SIZE.with(Cell::get);
2319 let has_obs: bool = obs_w >= 64 && obs_h >= 64;
2320 let matches_obs: bool = has_obs && obs_w.abs_diff(est_w) <= 2 && obs_h.abs_diff(est_h) <= 2;
2321 let (phys_w, phys_h): (u32, u32) = if matches_obs {
2322 (obs_w, obs_h)
2323 } else {
2324 (est_w, est_h)
2325 };
2326 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2327 let Ok(mut borrow) = slot.try_borrow_mut() else {
2328 return false;
2329 };
2330 let Some((app, _)) = borrow.as_mut() else {
2331 return false;
2332 };
2333 let ws: WindowState = app.get_window_state();
2334 let size_diff: bool = ws.get_physical_width() != phys_w
2335 || ws.get_physical_height() != phys_h
2336 || (ws.get_scale_factor() - dpr).abs() > 0.005
2337 || canvas.width() != phys_w
2338 || canvas.height() != phys_h;
2339 if !size_diff {
2340 return false;
2341 }
2342 if canvas.width() != phys_w {
2343 canvas.set_width(phys_w);
2344 }
2345 if canvas.height() != phys_h {
2346 canvas.set_height(phys_h);
2347 }
2348 app.set_exact_physical_viewport(phys_w, phys_h, dpr);
2349 true
2350 })
2351}
2352
2353#[cfg(target_arch = "wasm32")]
2359fn web_sync_safe_area() -> bool {
2360 let measured: SafeAreaInsets = web_query_safe_area_insets();
2361 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2362 let Ok(mut borrow) = slot.try_borrow_mut() else {
2363 return false;
2364 };
2365 let Some((app, _)) = borrow.as_mut() else {
2366 return false;
2367 };
2368 let effective: SafeAreaInsets = if app.is_immersive_fullscreen() {
2369 SafeAreaInsets::default()
2370 } else {
2371 measured
2372 };
2373 let current: SafeAreaInsets = app.get_context().get_safe_area().get_untracked();
2374 if current == effective {
2375 return false;
2376 }
2377 let wid: WindowId = app.get_window_state().get_id();
2378 app.dispatch_window_event(WindowEvent::SafeAreaChanged(wid, effective));
2379 true
2380 })
2381}
2382
2383#[cfg(target_arch = "wasm32")]
2389fn web_report_host_refresh_rate(measured_hz: f32) {
2390 let mut needs_redraw: bool = false;
2391 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2392 if let Ok(mut borrow) = slot.try_borrow_mut()
2393 && let Some((app, _)) = borrow.as_mut()
2394 {
2395 let prev_fps: f32 = app.get_context().get_live_fps().get_untracked();
2396 app.report_host_refresh_rate(measured_hz);
2397 let next_fps: f32 = app.get_context().get_live_fps().get_untracked();
2398 if (next_fps - prev_fps).abs() >= 1.0 {
2399 needs_redraw = true;
2400 }
2401 }
2402 });
2403 if needs_redraw {
2404 web_mark_needs_frame();
2405 }
2406}
2407
2408#[cfg(target_arch = "wasm32")]
2418fn web_flush_frame(dt_secs: f32) -> u64 {
2419 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2420 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2421 Ok(guard) => guard,
2422 Err(_) => return 0,
2423 };
2424 let Some((app, state)) = borrow.as_mut() else {
2425 return 0;
2426 };
2427 let coord: ShowcaseWebDualCanvasCoordinator = web_dual_canvas_snapshot();
2428 state.sync_adaptive_from_web_coordinator(app, &coord);
2429 let hash: u64 = app
2430 .step_game_frame(dt_secs)
2431 .map(|stats: FrameStats| stats.get_frame_hash())
2432 .unwrap_or(0);
2433 state.sync_adaptive_from_web_coordinator(app, &coord);
2434 let pump: bool = app.should_pump_frames();
2435 WEB_SHOULD_PUMP.with(|flag: &Cell<bool>| flag.set(pump));
2436 hash
2437 })
2438}
2439
2440#[cfg(target_arch = "wasm32")]
2446#[wasm_bindgen]
2447pub fn euv_example_web_start() -> u64 {
2448 reset_reactive_runtime();
2449 register_frame_wakeup(web_mark_needs_frame);
2450 let (left, top, css_w, css_h, dpr): (f64, f64, f64, f64, f32) = web_query_initial_viewport();
2451 WEB_CACHED_VIEWPORT.with(|cell: &Cell<(f64, f64, f64, f64, f32)>| {
2452 cell.set((left, top, css_w, css_h, dpr));
2453 });
2454 WEB_VIEWPORT_DIRTY.with(|flag: &Cell<bool>| flag.set(false));
2455 let logical_w: u32 = css_w.round().max(64.0) as u32;
2456 let logical_h: u32 = css_h.round().max(64.0) as u32;
2457 let phys_w: u32 = (css_w * f64::from(dpr))
2458 .round()
2459 .clamp(1.0, WEB_CANVAS_MAX_PHYS_DIM) as u32;
2460 let phys_h: u32 = (css_h * f64::from(dpr))
2461 .round()
2462 .clamp(1.0, WEB_CANVAS_MAX_PHYS_DIM) as u32;
2463 if let Some(win) = window()
2464 && let Some(doc) = win.document()
2465 && let Ok(Some(el)) = doc.query_selector(WEB_SELECTOR_CANVAS)
2466 && let Ok(canvas) = el.dyn_into::<HtmlCanvasElement>()
2467 {
2468 if canvas.width() != phys_w {
2469 canvas.set_width(phys_w);
2470 }
2471 if canvas.height() != phys_h {
2472 canvas.set_height(phys_h);
2473 }
2474 }
2475 match create_showcase_app_with_viewport(false, RenderMode::Auto, logical_w, logical_h, dpr) {
2476 Ok((mut app, state)) => {
2477 app.set_exact_physical_viewport(phys_w, phys_h, dpr);
2478 if let Some(win) = window()
2479 && let Ok(hash_str) = win.location().hash()
2480 {
2481 let initial: String =
2482 resolve_web_hash_route(&hash_str, Some(state.get_dynamic_hub()));
2483 let _: bool = state.get_route().set_if_changed(initial);
2484 }
2485 let route_watch: Signal<String> = state.get_route();
2486 let hub_watch: DynamicUpdateHub = state.get_dynamic_hub().clone();
2487 let (hash_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
2488 Effect::new(move || {
2489 let r: String = route_watch.get();
2490 if WEB_SYNCING_FROM_HISTORY.with(Cell::get) {
2491 return;
2492 }
2493 if let Some(win) = window() {
2494 let cur_raw: String = win.location().hash().unwrap_or_default();
2495 let cur_norm: String = resolve_web_hash_route(&cur_raw, Some(&hub_watch));
2496 if cur_norm != r {
2497 let target_hash: String = format!("#{r}");
2498 let _: Result<(), JsValue> = win.location().set_hash(&target_hash);
2499 }
2500 }
2501 })
2502 });
2503 let root_id: NodeId = app
2504 .get_scene()
2505 .with_read(SceneTree::get_root, NodeId::default());
2506 app.get_scene().with_write(
2507 |tree: &mut SceneTree| {
2508 tree.attach_scope(root_id, hash_scope);
2509 },
2510 (),
2511 );
2512 let hash: u64 = app
2513 .step_frame()
2514 .map(|stats: FrameStats| stats.get_frame_hash())
2515 .unwrap_or(0);
2516 let coord: ShowcaseWebDualCanvasCoordinator = web_dual_canvas_snapshot();
2517 state.sync_adaptive_from_web_coordinator(&mut app, &coord);
2518 let pump: bool = app.should_pump_frames();
2519 WEB_SHOULD_PUMP.with(|flag: &Cell<bool>| flag.set(pump));
2520 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2521 if let Ok(mut borrow) = slot.try_borrow_mut() {
2522 *borrow = Some((app, state));
2523 }
2524 });
2525 hash
2526 }
2527 Err(_) => 0,
2528 }
2529}
2530
2531#[cfg(target_arch = "wasm32")]
2541#[wasm_bindgen]
2542pub fn euv_example_render_route(route: &str) -> u64 {
2543 let has_runtime: bool = WEB_SHOWCASE_RUNTIME.with(
2544 |slot: &RefCell<Option<(App, ShowcaseState)>>| matches!(slot.try_borrow(), Ok(guard) if guard.is_some()),
2545 );
2546 if !has_runtime {
2547 let _: u64 = euv_example_web_start();
2548 }
2549 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2550 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2551 Ok(guard) => guard,
2552 Err(_) => return 0,
2553 };
2554 let Some((app, state)) = borrow.as_mut() else {
2555 return 0;
2556 };
2557 let _: bool = state.get_route().set_if_changed(route.to_string());
2558 app.step_frame()
2559 .map(|stats: FrameStats| stats.get_frame_hash())
2560 .unwrap_or(0)
2561 })
2562}
2563
2564#[cfg(target_arch = "wasm32")]
2575#[wasm_bindgen]
2576pub fn euv_web_pointer_move(x: f32, y: f32) -> u64 {
2577 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2578 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2579 Ok(guard) => guard,
2580 Err(_) => return 0,
2581 };
2582 let Some((app, _)) = borrow.as_mut() else {
2583 return 0;
2584 };
2585 let wid: WindowId = app.get_window_state().get_id();
2586 app.dispatch_window_event(WindowEvent::PointerMove(wid, PointerEvent::mouse(x, y)));
2587 app.step_frame()
2588 .map(|stats: FrameStats| stats.get_frame_hash())
2589 .unwrap_or(0)
2590 })
2591}
2592
2593#[cfg(target_arch = "wasm32")]
2604#[wasm_bindgen]
2605pub fn euv_web_pointer_down(x: f32, y: f32) -> u64 {
2606 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2607 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2608 Ok(guard) => guard,
2609 Err(_) => return 0,
2610 };
2611 let Some((app, _)) = borrow.as_mut() else {
2612 return 0;
2613 };
2614 let wid: WindowId = app.get_window_state().get_id();
2615 app.dispatch_window_event(WindowEvent::PointerDown(wid, PointerEvent::mouse(x, y)));
2616 app.step_frame()
2617 .map(|stats: FrameStats| stats.get_frame_hash())
2618 .unwrap_or(0)
2619 })
2620}
2621
2622#[cfg(target_arch = "wasm32")]
2633#[wasm_bindgen]
2634pub fn euv_web_pointer_up(x: f32, y: f32) -> u64 {
2635 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2636 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2637 Ok(guard) => guard,
2638 Err(_) => return 0,
2639 };
2640 let Some((app, _)) = borrow.as_mut() else {
2641 return 0;
2642 };
2643 let wid: WindowId = app.get_window_state().get_id();
2644 app.dispatch_window_event(WindowEvent::PointerUp(wid, PointerEvent::mouse(x, y)));
2645 app.step_frame()
2646 .map(|stats: FrameStats| stats.get_frame_hash())
2647 .unwrap_or(0)
2648 })
2649}
2650
2651#[cfg(target_arch = "wasm32")]
2662#[wasm_bindgen]
2663pub fn euv_web_scroll(dx: f32, dy: f32) -> u64 {
2664 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2665 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2666 Ok(guard) => guard,
2667 Err(_) => return 0,
2668 };
2669 let Some((app, _)) = borrow.as_mut() else {
2670 return 0;
2671 };
2672 let wid: WindowId = app.get_window_state().get_id();
2673 app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(dx, dy)));
2674 app.step_frame()
2675 .map(|stats: FrameStats| stats.get_frame_hash())
2676 .unwrap_or(0)
2677 })
2678}
2679
2680#[cfg(target_arch = "wasm32")]
2690#[wasm_bindgen]
2691pub fn euv_web_key_down(key: &str) -> u64 {
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 wid: WindowId = app.get_window_state().get_id();
2701 let code: KeyCode = match key {
2702 WEB_KEY_ENTER => KeyCode::Enter,
2703 WEB_KEY_BACKSPACE => KeyCode::Backspace,
2704 WEB_KEY_DELETE => KeyCode::Delete,
2705 WEB_KEY_ESCAPE => KeyCode::Escape,
2706 WEB_KEY_TAB => KeyCode::Tab,
2707 WEB_KEY_SPACE => KeyCode::Space,
2708 WEB_KEY_ARROW_LEFT => KeyCode::ArrowLeft,
2709 WEB_KEY_ARROW_RIGHT => KeyCode::ArrowRight,
2710 WEB_KEY_ARROW_UP => KeyCode::ArrowUp,
2711 WEB_KEY_ARROW_DOWN => KeyCode::ArrowDown,
2712 other => other
2713 .chars()
2714 .next()
2715 .map(KeyCode::Character)
2716 .unwrap_or(KeyCode::Unknown),
2717 };
2718 let key_ev: WindowEvent =
2719 WindowEvent::KeyDown(wid, KeyEvent::new(code, Modifiers::default(), false));
2720 state.get_game_host().ingest_event(&key_ev);
2721 app.dispatch_window_event(key_ev);
2722 if key.chars().count() == 1 {
2723 app.dispatch_window_event(WindowEvent::TextInput(wid, key.to_string()));
2724 }
2725 app.step_frame()
2726 .map(|stats: FrameStats| stats.get_frame_hash())
2727 .unwrap_or(0)
2728 })
2729}
2730
2731#[cfg(target_arch = "wasm32")]
2741#[wasm_bindgen]
2742pub fn euv_web_tick(dt_secs: f32) -> u64 {
2743 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2744 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2745 Ok(guard) => guard,
2746 Err(_) => return 0,
2747 };
2748 let Some((app, state)) = borrow.as_mut() else {
2749 return 0;
2750 };
2751 if !app.should_pump_frames() {
2752 return app.get_renderer().get_last_stats().get_frame_hash();
2753 }
2754 let cur_route: String = state.get_route().get_untracked();
2755 let on_game: bool =
2756 cur_route == ROUTE_GAME || cur_route == ROUTE_GAME_3D || cur_route == ROUTE_WATER;
2757 if on_game || app.has_active_animations() {
2758 return app
2759 .step_game_frame(dt_secs)
2760 .map(|stats: FrameStats| stats.get_frame_hash())
2761 .unwrap_or(0);
2762 }
2763 app.get_renderer().get_last_stats().get_frame_hash()
2764 })
2765}
2766
2767#[cfg(target_arch = "wasm32")]
2779#[wasm_bindgen]
2780pub fn euv_web_resize(width: u32, height: u32, dpr: f32) -> u64 {
2781 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2782 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2783 Ok(guard) => guard,
2784 Err(_) => return 0,
2785 };
2786 let Some((app, _)) = borrow.as_mut() else {
2787 return 0;
2788 };
2789 let w: u32 = width.max(64);
2790 let h: u32 = height.max(64);
2791 let scale: f32 = if dpr.is_finite() && dpr > 0.0 {
2792 dpr.clamp(WEB_DPR_MIN, WEB_DPR_MAX)
2793 } else {
2794 1.0
2795 };
2796 let phys_w: u32 = ((w as f64) * (scale as f64))
2797 .round()
2798 .clamp(1.0, WEB_CANVAS_MAX_PHYS_DIM) as u32;
2799 let phys_h: u32 = ((h as f64) * (scale as f64))
2800 .round()
2801 .clamp(1.0, WEB_CANVAS_MAX_PHYS_DIM) as u32;
2802 WEB_OBSERVED_PHYS_SIZE.with(|cell: &Cell<(u32, u32)>| cell.set((0, 0)));
2803 let (prev_l, prev_t, _, _, _): (f64, f64, f64, f64, f32) =
2804 WEB_CACHED_VIEWPORT.with(Cell::get);
2805 WEB_CACHED_VIEWPORT.with(|cell: &Cell<(f64, f64, f64, f64, f32)>| {
2806 cell.set((prev_l, prev_t, f64::from(w), f64::from(h), scale));
2807 });
2808 WEB_VIEWPORT_DIRTY.with(|flag: &Cell<bool>| flag.set(false));
2809 if let Some(win) = window()
2810 && let Some(doc) = win.document()
2811 && let Ok(Some(el)) = doc.query_selector(WEB_SELECTOR_CANVAS)
2812 && let Ok(canvas) = el.dyn_into::<HtmlCanvasElement>()
2813 {
2814 if canvas.width() != phys_w {
2815 canvas.set_width(phys_w);
2816 }
2817 if canvas.height() != phys_h {
2818 canvas.set_height(phys_h);
2819 }
2820 }
2821 app.set_exact_physical_viewport(phys_w, phys_h, scale);
2822 app.step_frame()
2823 .map(|stats: FrameStats| stats.get_frame_hash())
2824 .unwrap_or(0)
2825 })
2826}
2827
2828#[cfg(all(debug_assertions, target_arch = "wasm32"))]
2838#[wasm_bindgen]
2839pub fn euv_dev_ai_schema(request_json: &str) -> String {
2840 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2841 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2842 Ok(guard) => guard,
2843 Err(_) => return String::new(),
2844 };
2845 let Some((app, state)) = borrow.as_mut() else {
2846 return String::new();
2847 };
2848 let hooks: AiAppHooks = state.build_ai_hooks();
2849 AiSchemaProtocol::handle_json_with_hooks(app, request_json, Some(&hooks))
2850 })
2851}
2852
2853#[cfg(target_arch = "wasm32")]
2859#[wasm_bindgen]
2860pub fn euv_web_current_route() -> String {
2861 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2862 match slot.try_borrow() {
2863 Ok(guard) => guard
2864 .as_ref()
2865 .map(|(_, state): &(App, ShowcaseState)| state.get_route().get_untracked())
2866 .unwrap_or_default(),
2867 Err(_) => String::new(),
2868 }
2869 })
2870}