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 #[cfg(debug_assertions)]
578 web_attach_dev_automation_bridge(&win);
579 let Some(doc): Option<Document> = win.document() else {
580 return;
581 };
582 let Ok(Some(el)) = doc.query_selector(WEB_SELECTOR_CANVAS) else {
583 return;
584 };
585 let Ok(canvas) = el.dyn_into::<HtmlCanvasElement>() else {
586 return;
587 };
588 web_attach_ime_proxy(&doc);
589 register_native_action_bridge(web_native_action_bridge);
590 register_frame_wakeup(web_mark_needs_frame);
591 let _: bool = web_refresh_cached_viewport(&win, &canvas);
592 let _: bool = web_apply_cached_viewport(&canvas);
593 let on_move: Closure<dyn FnMut(web_sys::PointerEvent)> =
594 Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
595 let ptr: PointerEvent = web_pointer_from_dom(&ev, None);
596 web_queue_pointer_move_event(ptr);
597 }) as Box<dyn FnMut(web_sys::PointerEvent)>);
598 drop(canvas.add_event_listener_with_callback(
599 WEB_EVENT_POINTER_MOVE,
600 on_move.as_ref().unchecked_ref(),
601 ));
602 on_move.forget();
603 let canvas_down: HtmlCanvasElement = canvas.clone();
604 let on_down: Closure<dyn FnMut(web_sys::PointerEvent)> =
605 Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
606 drop(canvas_down.set_pointer_capture(ev.pointer_id()));
607 let ptr: PointerEvent = web_pointer_from_dom(&ev, Some(true));
608 web_queue_pointer_down_event(ptr);
609 if !WEB_IME_ACTIVE.with(Cell::get) {
610 drop(canvas_down.focus());
611 }
612 }) as Box<dyn FnMut(web_sys::PointerEvent)>);
613 drop(canvas.add_event_listener_with_callback(
614 WEB_EVENT_POINTER_DOWN,
615 on_down.as_ref().unchecked_ref(),
616 ));
617 on_down.forget();
618 let canvas_up: HtmlCanvasElement = canvas.clone();
619 let on_up: Closure<dyn FnMut(web_sys::PointerEvent)> =
620 Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
621 ev.stop_propagation();
622 let ptr: PointerEvent = web_pointer_from_dom(&ev, Some(false));
623 web_queue_pointer_up_event(ptr);
624 drop(canvas_up.release_pointer_capture(ev.pointer_id()));
625 }) as Box<dyn FnMut(web_sys::PointerEvent)>);
626 drop(
627 canvas
628 .add_event_listener_with_callback(WEB_EVENT_POINTER_UP, on_up.as_ref().unchecked_ref()),
629 );
630 on_up.forget();
631 let on_cancel: Closure<dyn FnMut(web_sys::PointerEvent)> =
632 Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
633 ev.stop_propagation();
634 web_queue_pointer_cancel(web_pointer_id_from_dom(&ev));
635 }) as Box<dyn FnMut(web_sys::PointerEvent)>);
636 drop(canvas.add_event_listener_with_callback(
637 WEB_EVENT_POINTER_CANCEL,
638 on_cancel.as_ref().unchecked_ref(),
639 ));
640 drop(canvas.add_event_listener_with_callback(
641 WEB_EVENT_LOST_POINTER_CAPTURE,
642 on_cancel.as_ref().unchecked_ref(),
643 ));
644 on_cancel.forget();
645 let on_win_up: Closure<dyn FnMut(web_sys::PointerEvent)> =
646 Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
647 let ptr: PointerEvent = web_pointer_from_dom(&ev, Some(false));
648 web_queue_pointer_up_event(ptr);
649 }) as Box<dyn FnMut(web_sys::PointerEvent)>);
650 drop(win.add_event_listener_with_callback(
651 WEB_EVENT_POINTER_UP,
652 on_win_up.as_ref().unchecked_ref(),
653 ));
654 on_win_up.forget();
655 let on_win_cancel: Closure<dyn FnMut(web_sys::PointerEvent)> =
656 Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
657 web_queue_pointer_cancel(web_pointer_id_from_dom(&ev));
658 }) as Box<dyn FnMut(web_sys::PointerEvent)>);
659 drop(win.add_event_listener_with_callback(
660 WEB_EVENT_POINTER_CANCEL,
661 on_win_cancel.as_ref().unchecked_ref(),
662 ));
663 on_win_cancel.forget();
664 let on_touch_cancel: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
665 web_queue_pointer_cancel(0);
666 }) as Box<dyn FnMut(Event)>);
667 drop(canvas.add_event_listener_with_callback(
668 WEB_EVENT_TOUCH_CANCEL,
669 on_touch_cancel.as_ref().unchecked_ref(),
670 ));
671 drop(win.add_event_listener_with_callback(
672 WEB_EVENT_TOUCH_CANCEL,
673 on_touch_cancel.as_ref().unchecked_ref(),
674 ));
675 on_touch_cancel.forget();
676 let on_blur: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
677 web_queue_pointer_cancel(0);
678 web_dispatch_system_event(SystemEvent::FocusChanged(false));
679 }) as Box<dyn FnMut(Event)>);
680 drop(win.add_event_listener_with_callback(WEB_EVENT_BLUR, on_blur.as_ref().unchecked_ref()));
681 on_blur.forget();
682 web_attach_system_event_listeners(&win, &doc, &canvas);
683 let on_wheel: Closure<dyn FnMut(WheelEvent)> = Closure::wrap(Box::new(move |ev: WheelEvent| {
684 ev.prevent_default();
685 let (left, top, _, _, _): (f64, f64, f64, f64, f32) = WEB_CACHED_VIEWPORT.with(Cell::get);
686 let x: f32 = (ev.client_x() as f64 - left) as f32;
687 let y: f32 = (ev.client_y() as f64 - top) as f32;
688 let mult: f32 = match ev.delta_mode() {
689 1 => 20.0,
690 2 => 320.0,
691 _ => 1.0,
692 };
693 web_queue_scroll_at(
694 x,
695 y,
696 (ev.delta_x() as f32) * mult,
697 (ev.delta_y() as f32) * mult,
698 );
699 })
700 as Box<dyn FnMut(WheelEvent)>);
701 web_add_non_passive_listener(
702 canvas.as_ref(),
703 WEB_EVENT_WHEEL,
704 on_wheel.as_ref().unchecked_ref(),
705 );
706 on_wheel.forget();
707 let on_key: Closure<dyn FnMut(KeyboardEvent)> =
708 Closure::wrap(Box::new(move |ev: KeyboardEvent| {
709 let key: String = ev.key();
710 if WEB_IME_COMPOSING.with(Cell::get)
711 || web_is_ime_composition_key(ev.is_composing(), &key, ev.key_code())
712 {
713 return;
714 }
715 let code_str: String = ev.code();
716 let mods: Modifiers =
717 Modifiers::new(ev.shift_key(), ev.ctrl_key(), ev.alt_key(), ev.meta_key());
718 let ime_active: bool = WEB_IME_ACTIVE.with(Cell::get);
719 let cmd_or_ctrl: bool = mods.get_ctrl() || mods.get_meta();
720 let is_nav_or_edit_key: bool = matches!(
721 key.as_str(),
722 WEB_KEY_ARROW_UP
723 | WEB_KEY_ARROW_DOWN
724 | WEB_KEY_ARROW_LEFT
725 | WEB_KEY_ARROW_RIGHT
726 | WEB_KEY_HOME
727 | WEB_KEY_END
728 | WEB_KEY_BACKSPACE
729 | WEB_KEY_DELETE
730 );
731 let should_prevent: bool = if cmd_or_ctrl {
732 matches!(code_str.as_str(), WEB_CODE_KEY_K | WEB_CODE_KEY_A)
733 || (ime_active && is_nav_or_edit_key)
734 } else if ime_active {
735 is_nav_or_edit_key || key.as_str() == WEB_KEY_TAB
736 } else {
737 is_nav_or_edit_key
738 || key.as_str() == WEB_KEY_PAGE_UP
739 || key.as_str() == WEB_KEY_PAGE_DOWN
740 || key.as_str() == WEB_KEY_SPACE
741 };
742 if should_prevent {
743 ev.prevent_default();
744 }
745 web_queue_key_down(&key, &code_str, mods, ev.repeat());
746 }) as Box<dyn FnMut(KeyboardEvent)>);
747 drop(win.add_event_listener_with_callback(WEB_EVENT_KEY_DOWN, on_key.as_ref().unchecked_ref()));
748 on_key.forget();
749 let on_key_up: Closure<dyn FnMut(KeyboardEvent)> =
750 Closure::wrap(Box::new(move |ev: KeyboardEvent| {
751 let key: String = ev.key();
752 let code_str: String = ev.code();
753 let mods: Modifiers =
754 Modifiers::new(ev.shift_key(), ev.ctrl_key(), ev.alt_key(), ev.meta_key());
755 web_queue_key_up(&key, &code_str, mods);
756 }) as Box<dyn FnMut(KeyboardEvent)>);
757 drop(
758 win.add_event_listener_with_callback(WEB_EVENT_KEY_UP, on_key_up.as_ref().unchecked_ref()),
759 );
760 on_key_up.forget();
761 let on_paste: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |ev: Event| {
762 if let Some(pasted) = web_extract_paste_text(&ev)
763 && !pasted.is_empty()
764 {
765 ev.prevent_default();
766 web_queue_text_input(pasted);
767 }
768 }) as Box<dyn FnMut(Event)>);
769 drop(win.add_event_listener_with_callback(WEB_EVENT_PASTE, on_paste.as_ref().unchecked_ref()));
770 on_paste.forget();
771 let on_copy: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |ev: Event| {
772 if web_is_copy_proxy_event(&ev) {
773 return;
774 }
775 if let Some(selected) = web_selected_text_snapshot()
776 && web_write_copy_event_text(&ev, &selected)
777 {
778 ev.prevent_default();
779 }
780 }) as Box<dyn FnMut(Event)>);
781 drop(doc.add_event_listener_with_callback(WEB_EVENT_COPY, on_copy.as_ref().unchecked_ref()));
782 on_copy.forget();
783 let win_resize: Window = win.clone();
784 let canvas_resize: HtmlCanvasElement = canvas.clone();
785 let on_resize: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
786 web_apply_viewport_resize_immediate(&win_resize, &canvas_resize);
787 }) as Box<dyn FnMut(Event)>);
788 drop(
789 win.add_event_listener_with_callback(WEB_EVENT_RESIZE, on_resize.as_ref().unchecked_ref()),
790 );
791 if let Ok(vv) = Reflect::get(win.as_ref(), &JsValue::from_str(WEB_PROP_VISUAL_VIEWPORT))
792 && let Ok(vv_target) = vv.dyn_into::<EventTarget>()
793 {
794 drop(vv_target.add_event_listener_with_callback(
795 WEB_EVENT_RESIZE,
796 on_resize.as_ref().unchecked_ref(),
797 ));
798 }
799 on_resize.forget();
800 let win_ro: Window = win.clone();
801 let canvas_ro: HtmlCanvasElement = canvas.clone();
802 let on_ro: Closure<dyn FnMut(f64, f64)> = Closure::wrap(Box::new(move |pw: f64, ph: f64| {
803 let valid_dims: bool = pw.is_finite() && ph.is_finite();
804 if valid_dims && pw >= 64.0 && ph >= 64.0 {
805 let obs_w: u32 = pw.round().clamp(1.0, WEB_CANVAS_MAX_PHYS_DIM) as u32;
806 let obs_h: u32 = ph.round().clamp(1.0, WEB_CANVAS_MAX_PHYS_DIM) as u32;
807 WEB_OBSERVED_PHYS_SIZE.with(|cell: &Cell<(u32, u32)>| cell.set((obs_w, obs_h)));
808 }
809 web_apply_viewport_resize_immediate(&win_ro, &canvas_ro);
810 }) as Box<dyn FnMut(f64, f64)>);
811 let attach_ro_fn: Function =
812 Function::new_with_args(WEB_JS_ATTACH_RESIZE_ARGS, WEB_JS_ATTACH_RESIZE_OBSERVER);
813 drop(attach_ro_fn.call2(
814 &JsValue::NULL,
815 canvas.as_ref(),
816 on_ro.as_ref().unchecked_ref(),
817 ));
818 on_ro.forget();
819 let win_dpr: Window = win.clone();
820 let canvas_dpr: HtmlCanvasElement = canvas.clone();
821 let on_dpr: Closure<dyn FnMut()> = Closure::wrap(Box::new(move || {
822 web_apply_viewport_resize_immediate(&win_dpr, &canvas_dpr);
823 }) as Box<dyn FnMut()>);
824 let attach_dpr_fn: Function =
825 Function::new_with_args(WEB_JS_WATCH_DPR_ARGS, WEB_JS_WATCH_DPR_BODY);
826 drop(attach_dpr_fn.call1(&JsValue::NULL, on_dpr.as_ref().unchecked_ref()));
827 on_dpr.forget();
828 let win_raf: Window = win.clone();
829 let canvas_raf: HtmlCanvasElement = canvas.clone();
830 WEB_RAF_CALLBACK.with(|slot: &RefCell<Option<Closure<dyn FnMut(f64)>>>| {
831 if let Ok(mut guard) = slot.try_borrow_mut() {
832 *guard = Some(Closure::wrap(Box::new(move |ts: f64| {
833 WEB_RAF_ID.with(|id_cell: &Cell<Option<i32>>| id_cell.set(None));
834 if !web_should_pump_frames() {
835 WEB_RAF_LAST_TS.with(|ts_cell: &Cell<f64>| ts_cell.set(0.0));
836 WEB_RAF_ACCUM_SECS.with(|s_cell: &Cell<f32>| s_cell.set(0.0));
837 WEB_RAF_ACCUM_FRAMES.with(|f_cell: &Cell<u32>| f_cell.set(0));
838 return;
839 }
840 let prev_ts: f64 = WEB_RAF_LAST_TS.with(|ts_cell: &Cell<f64>| ts_cell.replace(ts));
841 let mut dt: f32 = 1.0 / 60.0;
842 let mut valid_step: bool = false;
843 if prev_ts > 0.0 {
844 let raw_dt: f32 = ((ts - prev_ts) / 1000.0) as f32;
845 if (0.001..=0.1).contains(&raw_dt) {
846 valid_step = true;
847 }
848 dt = raw_dt.clamp(0.001, 0.05);
849 }
850 if valid_step {
851 let next_secs: f32 = WEB_RAF_ACCUM_SECS.with(Cell::get) + dt;
852 let next_frames: u32 = WEB_RAF_ACCUM_FRAMES.with(Cell::get).saturating_add(1);
853 if next_secs >= 0.35 && next_frames >= 8 {
854 let measured_hz: f32 = (next_frames as f32) / next_secs;
855 WEB_RAF_ACCUM_SECS.with(|s_cell: &Cell<f32>| s_cell.set(0.0));
856 WEB_RAF_ACCUM_FRAMES.with(|f_cell: &Cell<u32>| f_cell.set(0));
857 WEB_RAF_CALIBRATED.with(|c: &Cell<bool>| c.set(true));
858 web_report_host_refresh_rate(measured_hz);
859 } else {
860 WEB_RAF_ACCUM_SECS.with(|s_cell: &Cell<f32>| s_cell.set(next_secs));
861 WEB_RAF_ACCUM_FRAMES.with(|f_cell: &Cell<u32>| f_cell.set(next_frames));
862 }
863 }
864 let live_dpr_raw: f64 = win_raf.device_pixel_ratio();
865 let live_dpr: f32 = if live_dpr_raw.is_finite() && live_dpr_raw > 0.0 {
866 (live_dpr_raw as f32).clamp(WEB_DPR_MIN, WEB_DPR_MAX)
867 } else {
868 1.0
869 };
870 let cached_dpr: f32 = WEB_CACHED_VIEWPORT.with(Cell::get).4;
871 if (live_dpr - cached_dpr).abs() > 0.005 {
872 let _: bool = web_refresh_cached_viewport(&win_raf, &canvas_raf);
873 }
874 let resized_or_scaled: bool =
875 if WEB_VIEWPORT_DIRTY.with(|flag: &Cell<bool>| flag.replace(false)) {
876 web_apply_cached_viewport(&canvas_raf)
877 } else {
878 false
879 };
880 let cur_route: String = euv_web_current_route();
881 let on_game: bool = cur_route == ROUTE_GAME
882 || cur_route == ROUTE_GAME_3D
883 || cur_route == ROUTE_WATER;
884 let animating: bool = web_has_active_animations();
885 let dirty: bool = WEB_NEEDS_FRAME.with(|flag: &Cell<bool>| flag.replace(false))
886 || is_frame_needed();
887 let needs_continuous: bool = resized_or_scaled || on_game;
888 let needs_redraw: bool = animating || dirty;
889 if needs_continuous || needs_redraw {
890 let _: u64 = web_flush_frame(dt);
891 web_record_raf_submission_proxy_tick(&canvas_raf);
892 }
893 let calibrated: bool = WEB_RAF_CALIBRATED.with(Cell::get);
894 let still_active: bool = on_game
895 || web_has_active_animations()
896 || WEB_NEEDS_FRAME.with(Cell::get)
897 || is_frame_needed()
898 || !calibrated;
899 if still_active && web_should_pump_frames() {
900 web_start_raf_pump(&win_raf);
901 } else {
902 WEB_RAF_LAST_TS.with(|ts_cell: &Cell<f64>| ts_cell.set(0.0));
903 }
904 }) as Box<dyn FnMut(f64)>));
905 }
906 });
907 if doc.hidden() {
908 web_dispatch_system_event(SystemEvent::Background);
909 } else {
910 web_start_raf_pump(&win);
911 }
912}
913
914#[cfg(target_arch = "wasm32")]
920fn web_record_raf_submission_proxy_tick(canvas: &HtmlCanvasElement) {
921 let pixel_bytes: u64 = u64::from(canvas.width())
922 .saturating_mul(u64::from(canvas.height()))
923 .saturating_mul(4);
924 WEB_DUAL_CANVAS_COORDINATOR.with(|cell: &RefCell<ShowcaseWebDualCanvasCoordinator>| {
925 if let Ok(mut coord) = cell.try_borrow_mut() {
926 coord.record_raf_proxy_tick(pixel_bytes);
927 }
928 });
929}
930
931#[cfg(target_arch = "wasm32")]
943#[must_use]
944pub fn web_begin_independent_canvas_switch(
945 target: ShowcaseWebPresentationPath,
946 width: u32,
947 height: u32,
948) -> bool {
949 WEB_DUAL_CANVAS_COORDINATOR.with(|cell: &RefCell<ShowcaseWebDualCanvasCoordinator>| {
950 cell.try_borrow_mut()
951 .map(|mut coord: RefMut<'_, ShowcaseWebDualCanvasCoordinator>| {
952 coord.begin_switch(target, width, height)
953 })
954 .unwrap_or(false)
955 })
956}
957
958#[cfg(target_arch = "wasm32")]
970#[must_use]
971pub fn web_commit_independent_canvas_switch(
972 expected_width: u32,
973 expected_height: u32,
974 expected_scene_version: u64,
975) -> bool {
976 WEB_DUAL_CANVAS_COORDINATOR.with(|cell: &RefCell<ShowcaseWebDualCanvasCoordinator>| {
977 cell.try_borrow_mut()
978 .map(|mut coord: RefMut<'_, ShowcaseWebDualCanvasCoordinator>| {
979 coord.commit_at_frame_boundary(
980 expected_width,
981 expected_height,
982 expected_scene_version,
983 )
984 })
985 .unwrap_or(false)
986 })
987}
988
989#[cfg(target_arch = "wasm32")]
995#[must_use]
996pub fn web_dual_canvas_snapshot() -> ShowcaseWebDualCanvasCoordinator {
997 WEB_DUAL_CANVAS_COORDINATOR
998 .with(|cell: &RefCell<ShowcaseWebDualCanvasCoordinator>| cell.borrow().clone())
999}
1000
1001#[cfg(target_arch = "wasm32")]
1007fn web_should_pump_frames() -> bool {
1008 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1009 match slot.try_borrow() {
1010 Ok(guard) => {
1011 let pump: bool = guard
1012 .as_ref()
1013 .map(|(app, _): &(App, ShowcaseState)| app.should_pump_frames())
1014 .unwrap_or(false);
1015 WEB_SHOULD_PUMP.with(|flag: &Cell<bool>| flag.set(pump));
1016 pump
1017 }
1018 Err(_) => WEB_SHOULD_PUMP.with(Cell::get),
1019 }
1020 })
1021}
1022
1023#[cfg(target_arch = "wasm32")]
1029fn web_start_raf_pump(win: &Window) {
1030 if !web_should_pump_frames() {
1031 return;
1032 }
1033 let already_scheduled: bool =
1034 WEB_RAF_ID.with(|id_cell: &Cell<Option<i32>>| id_cell.get().is_some());
1035 if already_scheduled {
1036 return;
1037 }
1038 WEB_RAF_CALLBACK.with(|slot: &RefCell<Option<Closure<dyn FnMut(f64)>>>| {
1039 if let Ok(cb_ref) = slot.try_borrow()
1040 && let Some(cb) = cb_ref.as_ref()
1041 {
1042 let func: &Function = cb.as_ref().unchecked_ref();
1043 if let Ok(req_id) = win.request_animation_frame(func) {
1044 WEB_RAF_ID.with(|id_cell: &Cell<Option<i32>>| id_cell.set(Some(req_id)));
1045 }
1046 }
1047 });
1048}
1049
1050#[cfg(target_arch = "wasm32")]
1052fn web_stop_raf_pump() {
1053 let pending_id: Option<i32> = WEB_RAF_ID.with(|id_cell: &Cell<Option<i32>>| id_cell.take());
1054 if let Some(req_id) = pending_id
1055 && let Some(win) = window()
1056 {
1057 drop(win.cancel_animation_frame(req_id));
1058 }
1059 WEB_RAF_LAST_TS.with(|ts_cell: &Cell<f64>| ts_cell.set(0.0));
1060 WEB_RAF_ACCUM_SECS.with(|s_cell: &Cell<f32>| s_cell.set(0.0));
1061 WEB_RAF_ACCUM_FRAMES.with(|f_cell: &Cell<u32>| f_cell.set(0));
1062}
1063
1064#[cfg(target_arch = "wasm32")]
1070fn web_dispatch_system_event(event: SystemEvent) {
1071 let mut should_pump: bool = false;
1072 let mut handled: bool = false;
1073 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1074 if let Ok(mut borrow) = slot.try_borrow_mut()
1075 && let Some((app, _)) = borrow.as_mut()
1076 {
1077 app.dispatch_system_event(event);
1078 should_pump = app.should_pump_frames();
1079 handled = true;
1080 }
1081 });
1082 if !handled {
1083 return;
1084 }
1085 WEB_SHOULD_PUMP.with(|flag: &Cell<bool>| flag.set(should_pump));
1086 if !should_pump {
1087 web_stop_raf_pump();
1088 } else {
1089 WEB_RAF_LAST_TS.with(|ts_cell: &Cell<f64>| ts_cell.set(0.0));
1090 web_mark_needs_frame();
1091 if let Some(win) = window() {
1092 web_start_raf_pump(&win);
1093 }
1094 }
1095}
1096
1097#[cfg(target_arch = "wasm32")]
1107fn web_extract_paste_text(ev: &Event) -> Option<String> {
1108 let data: JsValue =
1109 Reflect::get(ev.as_ref(), &JsValue::from_str(WEB_PROP_CLIPBOARD_DATA)).ok()?;
1110 if data.is_null() || data.is_undefined() {
1111 return None;
1112 }
1113 let get_fn_val: JsValue = Reflect::get(&data, &JsValue::from_str(WEB_PROP_GET_DATA)).ok()?;
1114 let get_fn: Function = get_fn_val.dyn_into::<Function>().ok()?;
1115 let result: JsValue = get_fn
1116 .call1(&data, &JsValue::from_str(WEB_MIME_TEXT_PLAIN))
1117 .ok()?;
1118 result.as_string().filter(|s: &String| !s.is_empty())
1119}
1120
1121#[cfg(target_arch = "wasm32")]
1131fn web_is_copy_proxy_event(ev: &Event) -> bool {
1132 let Some(target) = ev.target() else {
1133 return false;
1134 };
1135 let Ok(el) = target.dyn_into::<Element>() else {
1136 return false;
1137 };
1138 el.get_attribute(WEB_ATTR_COPY_PROXY).as_deref() == Some(WEB_COPY_PROXY_FLAG)
1139}
1140
1141#[cfg(target_arch = "wasm32")]
1147fn web_selected_text_snapshot() -> Option<String> {
1148 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1149 let Ok(guard) = slot.try_borrow() else {
1150 return None;
1151 };
1152 let (app, _): &(App, ShowcaseState) = guard.as_ref()?;
1153 app.get_scene()
1154 .get_selected_text()
1155 .filter(|s: &String| !s.is_empty())
1156 })
1157}
1158
1159#[cfg(target_arch = "wasm32")]
1170fn web_write_copy_event_text(ev: &Event, text: &str) -> bool {
1171 let Ok(data) = Reflect::get(ev.as_ref(), &JsValue::from_str(WEB_PROP_CLIPBOARD_DATA)) else {
1172 return false;
1173 };
1174 if data.is_null() || data.is_undefined() {
1175 return false;
1176 }
1177 let Ok(set_fn_val) = Reflect::get(&data, &JsValue::from_str(WEB_PROP_SET_DATA)) else {
1178 return false;
1179 };
1180 let Ok(set_fn) = set_fn_val.dyn_into::<Function>() else {
1181 return false;
1182 };
1183 set_fn
1184 .call2(
1185 &data,
1186 &JsValue::from_str(WEB_MIME_TEXT_PLAIN),
1187 &JsValue::from_str(text),
1188 )
1189 .is_ok()
1190}
1191
1192#[cfg(target_arch = "wasm32")]
1198fn web_sync_route_from_browser_history(win: &Window) {
1199 let raw_hash: String = win.location().hash().unwrap_or_default();
1200 let prev_guard: bool = WEB_SYNCING_FROM_HISTORY.with(|flag: &Cell<bool>| flag.replace(true));
1201 let mut updated: bool = false;
1202 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1203 if let Ok(mut borrow) = slot.try_borrow_mut()
1204 && let Some((app, state)) = borrow.as_mut()
1205 {
1206 let _: String = apply_showcase_history_route(app, state, &raw_hash);
1207 updated = true;
1208 }
1209 });
1210 WEB_SYNCING_FROM_HISTORY.with(|flag: &Cell<bool>| flag.set(prev_guard));
1211 if updated {
1212 let _: bool = web_sync_safe_area();
1213 web_mark_needs_frame();
1214 web_start_raf_pump(win);
1215 }
1216 if let Ok(href) = win.location().href() {
1217 web_dispatch_system_event(SystemEvent::DeepLink(href));
1218 }
1219}
1220
1221#[cfg(target_arch = "wasm32")]
1231fn web_doc_is_fullscreen(doc: &Document) -> bool {
1232 if doc.fullscreen_element().is_some() {
1233 return true;
1234 }
1235 Reflect::get(
1236 doc.as_ref(),
1237 &JsValue::from_str(WEB_PROP_WEBKIT_FULLSCREEN_ELEMENT),
1238 )
1239 .ok()
1240 .map(|v: JsValue| !v.is_null() && !v.is_undefined())
1241 .unwrap_or(false)
1242}
1243
1244#[cfg(target_arch = "wasm32")]
1252fn web_add_non_passive_listener(target: &EventTarget, event: &str, callback: &Function) {
1253 let opts: Object = Object::new();
1254 let _: Result<bool, JsValue> = Reflect::set(
1255 opts.as_ref(),
1256 &JsValue::from_str(WEB_OPT_PASSIVE),
1257 &JsValue::FALSE,
1258 );
1259 if let Ok(add_val) = Reflect::get(
1260 target.as_ref(),
1261 &JsValue::from_str(WEB_METHOD_ADD_EVENT_LISTENER),
1262 ) && let Ok(add_fn) = add_val.dyn_into::<Function>()
1263 && add_fn
1264 .call3(
1265 target.as_ref(),
1266 &JsValue::from_str(event),
1267 callback.as_ref(),
1268 opts.as_ref(),
1269 )
1270 .is_ok()
1271 {
1272 return;
1273 }
1274 drop(target.add_event_listener_with_callback(event, callback));
1275}
1276
1277#[cfg(target_arch = "wasm32")]
1279fn web_ensure_visible_foreground() {
1280 if WEB_SHOULD_PUMP.with(Cell::get) {
1281 return;
1282 }
1283 let is_hidden: bool = window()
1284 .and_then(|w: Window| w.document())
1285 .map(|d: Document| d.hidden())
1286 .unwrap_or(false);
1287 if !is_hidden {
1288 web_dispatch_system_event(SystemEvent::Foreground);
1289 }
1290}
1291
1292#[cfg(target_arch = "wasm32")]
1299fn web_apply_viewport_resize_immediate(win: &Window, canvas: &HtmlCanvasElement) {
1300 web_ensure_visible_foreground();
1301 let viewport_changed: bool = web_refresh_cached_viewport(win, canvas);
1302 let safe_changed: bool = web_sync_safe_area();
1303 let applied: bool = web_apply_cached_viewport(canvas);
1304 let changed_metrics: bool = viewport_changed || safe_changed;
1305 if changed_metrics || applied {
1306 WEB_VIEWPORT_DIRTY.with(|flag: &Cell<bool>| flag.set(false));
1307 let _: u64 = web_flush_frame(0.0);
1308 web_mark_needs_frame();
1309 web_start_raf_pump(win);
1310 }
1311}
1312
1313#[cfg(target_arch = "wasm32")]
1321fn web_sync_fullscreen_from_dom(win: &Window, doc: &Document, canvas: &HtmlCanvasElement) {
1322 web_ensure_visible_foreground();
1323 let dom_fs: bool = web_doc_is_fullscreen(doc);
1324 if !dom_fs {
1325 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1326 if let Ok(mut borrow) = slot.try_borrow_mut()
1327 && let Some((app, _)) = borrow.as_mut()
1328 && (app.is_immersive_fullscreen()
1329 || is_fullscreen_active()
1330 || EuvOverlayStack::has_fullscreen())
1331 {
1332 let _: usize = sync_external_fullscreen_exit();
1333 app.set_immersive_fullscreen(false);
1334 }
1335 });
1336 }
1337 let _: bool = web_refresh_cached_viewport(win, canvas);
1338 let _: bool = web_sync_safe_area();
1339 let _: bool = web_apply_cached_viewport(canvas);
1340 WEB_VIEWPORT_DIRTY.with(|flag: &Cell<bool>| flag.set(false));
1341 let _: u64 = web_flush_frame(0.0);
1342 web_mark_needs_frame();
1343 web_start_raf_pump(win);
1344}
1345
1346#[cfg(target_arch = "wasm32")]
1352fn web_dispatch_theme_changed(mode: ThemeMode) {
1353 let mut dispatched: bool = false;
1354 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1355 if let Ok(mut borrow) = slot.try_borrow_mut()
1356 && let Some((app, _)) = borrow.as_mut()
1357 {
1358 let wid: WindowId = app.get_window_state().get_id();
1359 app.dispatch_window_event(WindowEvent::ThemeChanged(wid, mode));
1360 dispatched = true;
1361 }
1362 });
1363 if dispatched {
1364 web_mark_needs_frame();
1365 }
1366}
1367
1368#[cfg(target_arch = "wasm32")]
1375fn web_handle_orientation_change(win: &Window, canvas: &HtmlCanvasElement) {
1376 web_apply_viewport_resize_immediate(win, canvas);
1377 let (_, _, css_w, css_h, _): (f64, f64, f64, f64, f32) = WEB_CACHED_VIEWPORT.with(Cell::get);
1378 let orient: ScreenOrientation = if css_w > css_h {
1379 ScreenOrientation::Landscape
1380 } else {
1381 ScreenOrientation::Portrait
1382 };
1383 web_dispatch_system_event(SystemEvent::OrientationChanged(orient));
1384 let _: u64 = web_flush_frame(0.0);
1385 web_mark_needs_frame();
1386 web_start_raf_pump(win);
1387}
1388
1389#[cfg(target_arch = "wasm32")]
1397fn web_attach_system_event_listeners(win: &Window, doc: &Document, canvas: &HtmlCanvasElement) {
1398 let doc_vis: Document = doc.clone();
1399 let win_vis: Window = win.clone();
1400 let canvas_vis: HtmlCanvasElement = canvas.clone();
1401 let on_vis: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1402 if doc_vis.hidden() {
1403 web_queue_pointer_cancel(0);
1404 web_dispatch_system_event(SystemEvent::Background);
1405 } else {
1406 let _: bool = web_refresh_cached_viewport(&win_vis, &canvas_vis);
1407 let _: bool = web_sync_safe_area();
1408 web_dispatch_system_event(SystemEvent::Foreground);
1409 }
1410 }) as Box<dyn FnMut(Event)>);
1411 drop(doc.add_event_listener_with_callback(
1412 WEB_EVENT_VISIBILITY_CHANGE,
1413 on_vis.as_ref().unchecked_ref(),
1414 ));
1415 on_vis.forget();
1416 let win_focus: Window = win.clone();
1417 let canvas_focus: HtmlCanvasElement = canvas.clone();
1418 let on_focus: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1419 let _: bool = web_refresh_cached_viewport(&win_focus, &canvas_focus);
1420 let _: bool = web_sync_safe_area();
1421 web_dispatch_system_event(SystemEvent::Foreground);
1422 web_dispatch_system_event(SystemEvent::FocusChanged(true));
1423 }) as Box<dyn FnMut(Event)>);
1424 drop(win.add_event_listener_with_callback(WEB_EVENT_FOCUS, on_focus.as_ref().unchecked_ref()));
1425 on_focus.forget();
1426 let win_ps: Window = win.clone();
1427 let canvas_ps: HtmlCanvasElement = canvas.clone();
1428 let on_pageshow: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1429 let _: bool = web_refresh_cached_viewport(&win_ps, &canvas_ps);
1430 let _: bool = web_sync_safe_area();
1431 web_sync_route_from_browser_history(&win_ps);
1432 web_dispatch_system_event(SystemEvent::Foreground);
1433 }) as Box<dyn FnMut(Event)>);
1434 drop(win.add_event_listener_with_callback(
1435 WEB_EVENT_PAGE_SHOW,
1436 on_pageshow.as_ref().unchecked_ref(),
1437 ));
1438 on_pageshow.forget();
1439 let on_pagehide: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1440 web_queue_pointer_cancel(0);
1441 web_dispatch_system_event(SystemEvent::Background);
1442 }) as Box<dyn FnMut(Event)>);
1443 drop(win.add_event_listener_with_callback(
1444 WEB_EVENT_PAGE_HIDE,
1445 on_pagehide.as_ref().unchecked_ref(),
1446 ));
1447 on_pagehide.forget();
1448 let on_unload: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1449 web_dispatch_system_event(SystemEvent::Terminate);
1450 }) as Box<dyn FnMut(Event)>);
1451 drop(win.add_event_listener_with_callback(
1452 WEB_EVENT_BEFORE_UNLOAD,
1453 on_unload.as_ref().unchecked_ref(),
1454 ));
1455 on_unload.forget();
1456 let on_online: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1457 web_dispatch_system_event(SystemEvent::NetworkStatusChanged(NetworkStatus::Online));
1458 }) as Box<dyn FnMut(Event)>);
1459 drop(
1460 win.add_event_listener_with_callback(WEB_EVENT_ONLINE, on_online.as_ref().unchecked_ref()),
1461 );
1462 on_online.forget();
1463 let on_offline: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1464 web_dispatch_system_event(SystemEvent::NetworkStatusChanged(NetworkStatus::Offline));
1465 }) as Box<dyn FnMut(Event)>);
1466 drop(
1467 win.add_event_listener_with_callback(
1468 WEB_EVENT_OFFLINE,
1469 on_offline.as_ref().unchecked_ref(),
1470 ),
1471 );
1472 on_offline.forget();
1473 if let Ok(Some(mql)) = win.match_media(WEB_MEDIA_PREFERS_DARK) {
1474 let mql_cb: MediaQueryList = mql.clone();
1475 let on_theme: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1476 let next_theme: ThemeMode = if mql_cb.matches() {
1477 ThemeMode::Dark
1478 } else {
1479 ThemeMode::Light
1480 };
1481 web_dispatch_theme_changed(next_theme);
1482 })
1483 as Box<dyn FnMut(Event)>);
1484 drop(
1485 mql.add_event_listener_with_callback(
1486 WEB_EVENT_CHANGE,
1487 on_theme.as_ref().unchecked_ref(),
1488 ),
1489 );
1490 on_theme.forget();
1491 }
1492 let win_hist: Window = win.clone();
1493 let on_history: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1494 web_sync_route_from_browser_history(&win_hist);
1495 }) as Box<dyn FnMut(Event)>);
1496 drop(win.add_event_listener_with_callback(
1497 WEB_EVENT_HASH_CHANGE,
1498 on_history.as_ref().unchecked_ref(),
1499 ));
1500 drop(win.add_event_listener_with_callback(
1501 WEB_EVENT_POP_STATE,
1502 on_history.as_ref().unchecked_ref(),
1503 ));
1504 on_history.forget();
1505 let win_fs: Window = win.clone();
1506 let doc_fs: Document = doc.clone();
1507 let canvas_fs: HtmlCanvasElement = canvas.clone();
1508 let on_fs_change: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1509 web_sync_fullscreen_from_dom(&win_fs, &doc_fs, &canvas_fs);
1510 }) as Box<dyn FnMut(Event)>);
1511 drop(doc.add_event_listener_with_callback(
1512 WEB_EVENT_FULLSCREEN_CHANGE,
1513 on_fs_change.as_ref().unchecked_ref(),
1514 ));
1515 drop(doc.add_event_listener_with_callback(
1516 WEB_EVENT_WEBKIT_FULLSCREEN_CHANGE,
1517 on_fs_change.as_ref().unchecked_ref(),
1518 ));
1519 on_fs_change.forget();
1520 let win_orient: Window = win.clone();
1521 let canvas_orient: HtmlCanvasElement = canvas.clone();
1522 let on_orient: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1523 web_handle_orientation_change(&win_orient, &canvas_orient);
1524 }) as Box<dyn FnMut(Event)>);
1525 drop(win.add_event_listener_with_callback(
1526 WEB_EVENT_ORIENTATION_CHANGE,
1527 on_orient.as_ref().unchecked_ref(),
1528 ));
1529 if let Ok(screen_val) = Reflect::get(win.as_ref(), &JsValue::from_str(WEB_PROP_SCREEN))
1530 && !screen_val.is_null()
1531 && !screen_val.is_undefined()
1532 && let Ok(orient_val) = Reflect::get(&screen_val, &JsValue::from_str(WEB_PROP_ORIENTATION))
1533 && let Ok(orient_target) = orient_val.dyn_into::<EventTarget>()
1534 {
1535 drop(orient_target.add_event_listener_with_callback(
1536 WEB_EVENT_CHANGE,
1537 on_orient.as_ref().unchecked_ref(),
1538 ));
1539 }
1540 on_orient.forget();
1541 let vv_key: JsValue = JsValue::from_str(WEB_PROP_VISUAL_VIEWPORT);
1542 if let Ok(vv_val) = Reflect::get(win.as_ref(), &vv_key)
1543 && let Ok(vv_target) = vv_val.clone().dyn_into::<EventTarget>()
1544 {
1545 let win_vv: Window = win.clone();
1546 let vv_obj: JsValue = vv_val;
1547 let on_vv_resize: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1548 let inner_h: f32 = win_vv
1549 .inner_height()
1550 .ok()
1551 .and_then(|v: JsValue| v.as_f64())
1552 .unwrap_or(0.0) as f32;
1553 let h_key: JsValue = JsValue::from_str(WEB_PROP_HEIGHT);
1554 let vv_h: f32 = Reflect::get(&vv_obj, &h_key)
1555 .ok()
1556 .and_then(|v: JsValue| v.as_f64())
1557 .unwrap_or(inner_h as f64) as f32;
1558 let kb_delta: f32 = (inner_h - vv_h).max(0.0);
1559 let visible: bool = kb_delta >= WEB_KEYBOARD_MIN_DELTA_PX;
1560 let height: f32 = if visible { kb_delta } else { 0.0 };
1561 web_dispatch_system_event(SystemEvent::KeyboardVisibilityChanged { visible, height });
1562 if web_sync_safe_area() {
1563 web_mark_needs_frame();
1564 }
1565 })
1566 as Box<dyn FnMut(Event)>);
1567 drop(vv_target.add_event_listener_with_callback(
1568 WEB_EVENT_RESIZE,
1569 on_vv_resize.as_ref().unchecked_ref(),
1570 ));
1571 on_vv_resize.forget();
1572 }
1573}
1574
1575#[cfg(target_arch = "wasm32")]
1586fn web_map_key(key: &str, code_str: &str) -> KeyCode {
1587 match code_str {
1588 WEB_CODE_KEY_W => return KeyCode::Character('w'),
1589 WEB_CODE_KEY_A => return KeyCode::Character('a'),
1590 WEB_CODE_KEY_S => return KeyCode::Character('s'),
1591 WEB_CODE_KEY_D => return KeyCode::Character('d'),
1592 WEB_CODE_KEY_E => return KeyCode::Character('e'),
1593 WEB_CODE_KEY_R => return KeyCode::Character('r'),
1594 WEB_CODE_KEY_P => return KeyCode::Character('p'),
1595 WEB_CODE_KEY_J => return KeyCode::Character('j'),
1596 WEB_CODE_KEY_C => return KeyCode::Character('c'),
1597 WEB_CODE_KEY_V => return KeyCode::Character('v'),
1598 WEB_CODE_KEY_X => return KeyCode::Character('x'),
1599 WEB_CODE_KEY_Z => return KeyCode::Character('z'),
1600 WEB_CODE_KEY_K => return KeyCode::Character('k'),
1601 WEB_CODE_SPACE => return KeyCode::Space,
1602 WEB_KEY_ARROW_LEFT => return KeyCode::ArrowLeft,
1603 WEB_KEY_ARROW_RIGHT => return KeyCode::ArrowRight,
1604 WEB_KEY_ARROW_UP => return KeyCode::ArrowUp,
1605 WEB_KEY_ARROW_DOWN => return KeyCode::ArrowDown,
1606 WEB_KEY_HOME => return KeyCode::Home,
1607 WEB_KEY_END => return KeyCode::End,
1608 WEB_KEY_PAGE_UP => return KeyCode::PageUp,
1609 WEB_KEY_PAGE_DOWN => return KeyCode::PageDown,
1610 _ => {}
1611 }
1612 match key {
1613 WEB_KEY_ENTER => KeyCode::Enter,
1614 WEB_KEY_BACKSPACE => KeyCode::Backspace,
1615 WEB_KEY_DELETE => KeyCode::Delete,
1616 WEB_KEY_ESCAPE => KeyCode::Escape,
1617 WEB_KEY_TAB => KeyCode::Tab,
1618 WEB_KEY_SPACE => KeyCode::Space,
1619 WEB_KEY_ARROW_LEFT => KeyCode::ArrowLeft,
1620 WEB_KEY_ARROW_RIGHT => KeyCode::ArrowRight,
1621 WEB_KEY_ARROW_UP => KeyCode::ArrowUp,
1622 WEB_KEY_ARROW_DOWN => KeyCode::ArrowDown,
1623 WEB_KEY_HOME => KeyCode::Home,
1624 WEB_KEY_END => KeyCode::End,
1625 WEB_KEY_PAGE_UP => KeyCode::PageUp,
1626 WEB_KEY_PAGE_DOWN => KeyCode::PageDown,
1627 other => other
1628 .chars()
1629 .next()
1630 .map(KeyCode::Character)
1631 .unwrap_or(KeyCode::Unknown),
1632 }
1633}
1634
1635#[cfg(target_arch = "wasm32")]
1641fn web_has_active_animations() -> bool {
1642 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1643 match slot.try_borrow() {
1644 Ok(guard) => guard
1645 .as_ref()
1646 .map(|(app, _): &(App, ShowcaseState)| app.has_active_animations())
1647 .unwrap_or(false),
1648 Err(_) => false,
1649 }
1650 })
1651}
1652
1653#[cfg(target_arch = "wasm32")]
1655fn web_mark_needs_frame() {
1656 WEB_NEEDS_FRAME.with(|flag: &Cell<bool>| flag.set(true));
1657 let idle: bool = WEB_RAF_ID.with(|id_cell: &Cell<Option<i32>>| id_cell.get().is_none());
1658 if idle && let Some(win) = window() {
1659 web_start_raf_pump(&win);
1660 }
1661}
1662
1663#[cfg(target_arch = "wasm32")]
1673fn web_pointer_id_from_dom(ev: &web_sys::PointerEvent) -> u64 {
1674 (ev.pointer_id() as i64).unsigned_abs().saturating_add(1)
1675}
1676
1677#[cfg(target_arch = "wasm32")]
1688fn web_pointer_from_dom(ev: &web_sys::PointerEvent, force_pressed: Option<bool>) -> PointerEvent {
1689 let (left, top, _, _, _): (f64, f64, f64, f64, f32) = WEB_CACHED_VIEWPORT.with(Cell::get);
1690 let x: f32 = (ev.client_x() as f64 - left) as f32;
1691 let y: f32 = (ev.client_y() as f64 - top) as f32;
1692 let pid: u64 = web_pointer_id_from_dom(ev);
1693 let ptype: String = ev.pointer_type();
1694 let device: PointerDevice = if ptype == WEB_PTR_TYPE_TOUCH {
1695 PointerDevice::Touch
1696 } else if ptype == WEB_PTR_TYPE_PEN {
1697 PointerDevice::Stylus
1698 } else {
1699 PointerDevice::Mouse
1700 };
1701 let is_pressed: bool =
1702 force_pressed.unwrap_or_else(|| ev.buttons() != 0 || device == PointerDevice::Touch);
1703 let pressure: f32 = if is_pressed { 1.0 } else { 0.0 };
1704 let mods: Modifiers =
1705 Modifiers::new(ev.shift_key(), ev.ctrl_key(), ev.alt_key(), ev.meta_key());
1706 PointerEvent::new(
1707 pid,
1708 device,
1709 Point::new(x, y),
1710 PointerButton::Primary,
1711 pressure,
1712 mods,
1713 )
1714}
1715
1716#[cfg(target_arch = "wasm32")]
1722fn web_queue_pointer_move_event(ptr: PointerEvent) {
1723 let mut needs_redraw: bool = false;
1724 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1725 if let Ok(mut borrow) = slot.try_borrow_mut()
1726 && let Some((app, _)) = borrow.as_mut()
1727 {
1728 let rev_before: u64 = app.get_scene().with_read(SceneTree::get_revision, 0);
1729 let cursor_before: CursorIcon = app.get_last_cursor();
1730 let wid: WindowId = app.get_window_state().get_id();
1731 app.dispatch_window_event(WindowEvent::PointerMove(wid, ptr));
1732 let rev_after: u64 = app.get_scene().with_read(SceneTree::get_revision, 0);
1733 let cursor_after: CursorIcon = app.get_last_cursor();
1734 let active_drag: bool =
1735 ptr.get_pressure() > 0.0 || ptr.get_device() != PointerDevice::Mouse;
1736 let has_anim: bool = app
1737 .get_scene()
1738 .with_read(SceneTree::has_active_transitions, false);
1739 needs_redraw = rev_after != rev_before
1740 || cursor_after != cursor_before
1741 || active_drag
1742 || has_anim
1743 || is_frame_needed();
1744 }
1745 });
1746 if needs_redraw {
1747 web_mark_needs_frame();
1748 }
1749}
1750
1751#[cfg(target_arch = "wasm32")]
1757fn web_queue_pointer_down_event(ptr: PointerEvent) {
1758 web_ensure_visible_foreground();
1759 let mut queued: bool = false;
1760 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1761 if let Ok(mut borrow) = slot.try_borrow_mut()
1762 && let Some((app, _)) = borrow.as_mut()
1763 {
1764 let wid: WindowId = app.get_window_state().get_id();
1765 app.dispatch_window_event(WindowEvent::PointerDown(wid, ptr));
1766 queued = true;
1767 }
1768 });
1769 if queued {
1770 web_mark_needs_frame();
1771 }
1772}
1773
1774#[cfg(target_arch = "wasm32")]
1780fn web_queue_pointer_up_event(ptr: PointerEvent) {
1781 let mut queued: bool = false;
1782 let mut fs_exited: bool = false;
1783 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1784 if let Ok(mut borrow) = slot.try_borrow_mut()
1785 && let Some((app, _)) = borrow.as_mut()
1786 {
1787 let was_fs: bool = app.is_immersive_fullscreen() || is_fullscreen_active();
1788 let wid: WindowId = app.get_window_state().get_id();
1789 app.dispatch_window_event(WindowEvent::PointerUp(wid, ptr));
1790 let now_fs: bool = app.is_immersive_fullscreen() || is_fullscreen_active();
1791 fs_exited = was_fs && !now_fs;
1792 queued = true;
1793 }
1794 });
1795 if fs_exited {
1796 let _: u64 = web_flush_frame(0.0);
1797 }
1798 if queued {
1799 web_mark_needs_frame();
1800 }
1801}
1802
1803#[cfg(target_arch = "wasm32")]
1809fn web_queue_pointer_cancel(pointer_id: u64) {
1810 let mut queued: bool = false;
1811 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1812 if let Ok(mut borrow) = slot.try_borrow_mut()
1813 && let Some((app, _)) = borrow.as_mut()
1814 {
1815 let wid: WindowId = app.get_window_state().get_id();
1816 app.dispatch_window_event(WindowEvent::PointerCancel(wid, pointer_id));
1817 queued = true;
1818 }
1819 });
1820 if queued {
1821 web_mark_needs_frame();
1822 }
1823}
1824
1825#[cfg(target_arch = "wasm32")]
1834fn web_queue_scroll_at(x: f32, y: f32, dx: f32, dy: f32) {
1835 web_ensure_visible_foreground();
1836 let mut queued: bool = false;
1837 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1838 if let Ok(mut borrow) = slot.try_borrow_mut()
1839 && let Some((app, _)) = borrow.as_mut()
1840 {
1841 let wid: WindowId = app.get_window_state().get_id();
1842 app.dispatch_window_event(WindowEvent::PointerMove(wid, PointerEvent::mouse(x, y)));
1843 app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(dx, dy)));
1844 queued = true;
1845 }
1846 });
1847 if queued {
1848 web_mark_needs_frame();
1849 }
1850}
1851
1852#[cfg(target_arch = "wasm32")]
1861fn web_queue_key_down(key: &str, code_str: &str, mods: Modifiers, repeat: bool) {
1862 if WEB_IME_COMPOSING.with(Cell::get) {
1863 return;
1864 }
1865 web_ensure_visible_foreground();
1866 let ime_active: bool = WEB_IME_ACTIVE.with(Cell::get);
1867 let mut queued: bool = false;
1868 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1869 if let Ok(mut borrow) = slot.try_borrow_mut()
1870 && let Some((app, _)) = borrow.as_mut()
1871 {
1872 let wid: WindowId = app.get_window_state().get_id();
1873 let code: KeyCode = web_map_key(key, code_str);
1874 let key_ev: WindowEvent = WindowEvent::KeyDown(wid, KeyEvent::new(code, mods, repeat));
1875 app.dispatch_window_event(key_ev);
1876 if web_should_dispatch_text_input(ime_active, mods, key) {
1877 app.dispatch_window_event(WindowEvent::TextInput(wid, key.to_string()));
1878 }
1879 queued = true;
1880 }
1881 });
1882 if queued {
1883 web_mark_needs_frame();
1884 }
1885}
1886
1887#[cfg(target_arch = "wasm32")]
1893fn web_queue_text_input(text: String) {
1894 if text.is_empty() {
1895 return;
1896 }
1897 let mut queued: bool = false;
1898 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1899 if let Ok(mut borrow) = slot.try_borrow_mut()
1900 && let Some((app, _)) = borrow.as_mut()
1901 {
1902 let wid: WindowId = app.get_window_state().get_id();
1903 app.dispatch_window_event(WindowEvent::TextInput(wid, text));
1904 queued = true;
1905 }
1906 });
1907 if queued {
1908 web_mark_needs_frame();
1909 }
1910}
1911
1912#[cfg(target_arch = "wasm32")]
1919fn web_flush_ime_element(el: &HtmlElement, fallback: Option<String>) {
1920 let key: JsValue = JsValue::from_str(WEB_PROP_VALUE);
1921 let el_text: Option<String> = Reflect::get(el.as_ref(), &key)
1922 .ok()
1923 .and_then(|val: JsValue| val.as_string())
1924 .filter(|s: &String| !s.is_empty());
1925 let _: Result<bool, JsValue> = Reflect::set(el.as_ref(), &key, &JsValue::from_str(""));
1926 let committed: Option<String> = el_text.or_else(|| fallback.filter(|s: &String| !s.is_empty()));
1927 if let Some(text) = committed {
1928 web_queue_text_input(text);
1929 }
1930}
1931
1932#[cfg(target_arch = "wasm32")]
1942fn web_event_is_composing(ev: &Event) -> bool {
1943 Reflect::get(ev.as_ref(), &JsValue::from_str(WEB_PROP_IS_COMPOSING))
1944 .ok()
1945 .and_then(|val: JsValue| val.as_bool())
1946 .unwrap_or(false)
1947}
1948
1949#[cfg(target_arch = "wasm32")]
1959fn web_event_data_string(ev: &Event) -> Option<String> {
1960 Reflect::get(ev.as_ref(), &JsValue::from_str(WEB_PROP_DATA))
1961 .ok()
1962 .and_then(|val: JsValue| val.as_string())
1963 .filter(|s: &String| !s.is_empty())
1964}
1965
1966#[cfg(target_arch = "wasm32")]
1972fn web_attach_ime_proxy(doc: &Document) {
1973 let Ok(raw_el) = doc.create_element(WEB_IME_INPUT_TAG) else {
1974 return;
1975 };
1976 let el: Element = raw_el;
1977 drop(el.set_attribute(WEB_IME_ATTR_ID, WEB_IME_INPUT_ID));
1978 drop(el.set_attribute(WEB_IME_ATTR_TYPE, WEB_IME_ATTR_TEXT));
1979 drop(el.set_attribute(WEB_IME_ATTR_AUTOCOMPLETE, WEB_IME_ATTR_OFF));
1980 drop(el.set_attribute(WEB_IME_ATTR_AUTOCORRECT, WEB_IME_ATTR_OFF));
1981 drop(el.set_attribute(WEB_IME_ATTR_AUTOCAPITALIZE, WEB_IME_ATTR_OFF));
1982 drop(el.set_attribute(WEB_IME_ATTR_SPELLCHECK, WEB_IME_ATTR_FALSE));
1983 drop(el.set_attribute(WEB_IME_ATTR_ARIA_LABEL, WEB_IME_ARIA_LABEL));
1984 drop(el.set_attribute(WEB_IME_ATTR_STYLE, WEB_IME_STYLE));
1985 let Ok(html_el) = el.dyn_into::<HtmlElement>() else {
1986 return;
1987 };
1988 if let Some(body) = doc.body() {
1989 drop(body.append_child(&html_el));
1990 }
1991 let on_ime_focus: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1992 WEB_IME_ACTIVE.with(|a: &Cell<bool>| a.set(true));
1993 }) as Box<dyn FnMut(Event)>);
1994 drop(
1995 html_el.add_event_listener_with_callback(
1996 WEB_EVENT_FOCUS,
1997 on_ime_focus.as_ref().unchecked_ref(),
1998 ),
1999 );
2000 on_ime_focus.forget();
2001 let comp_start: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
2002 WEB_IME_COMPOSING.with(|c: &Cell<bool>| c.set(true));
2003 }) as Box<dyn FnMut(Event)>);
2004 drop(html_el.add_event_listener_with_callback(
2005 WEB_EVENT_COMPOSITION_START,
2006 comp_start.as_ref().unchecked_ref(),
2007 ));
2008 comp_start.forget();
2009 let comp_update: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
2010 WEB_IME_COMPOSING.with(|c: &Cell<bool>| c.set(true));
2011 }) as Box<dyn FnMut(Event)>);
2012 drop(html_el.add_event_listener_with_callback(
2013 WEB_EVENT_COMPOSITION_UPDATE,
2014 comp_update.as_ref().unchecked_ref(),
2015 ));
2016 comp_update.forget();
2017 let comp_el: HtmlElement = html_el.clone();
2018 let comp_end: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |ev: Event| {
2019 WEB_IME_COMPOSING.with(|c: &Cell<bool>| c.set(false));
2020 let fallback: Option<String> = web_event_data_string(&ev);
2021 web_flush_ime_element(&comp_el, fallback);
2022 }) as Box<dyn FnMut(Event)>);
2023 drop(html_el.add_event_listener_with_callback(
2024 WEB_EVENT_COMPOSITION_END,
2025 comp_end.as_ref().unchecked_ref(),
2026 ));
2027 comp_end.forget();
2028 let inp_el: HtmlElement = html_el.clone();
2029 let on_input: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |ev: Event| {
2030 if !WEB_IME_COMPOSING.with(Cell::get) && !web_event_is_composing(&ev) {
2031 web_flush_ime_element(&inp_el, None);
2032 }
2033 }) as Box<dyn FnMut(Event)>);
2034 drop(
2035 html_el
2036 .add_event_listener_with_callback(WEB_EVENT_INPUT, on_input.as_ref().unchecked_ref()),
2037 );
2038 on_input.forget();
2039 let on_ime_blur: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
2040 WEB_IME_ACTIVE.with(|a: &Cell<bool>| a.set(false));
2041 WEB_IME_COMPOSING.with(|c: &Cell<bool>| c.set(false));
2042 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2043 if let Ok(mut borrow) = slot.try_borrow_mut()
2044 && let Some((app, _)) = borrow.as_mut()
2045 {
2046 let wid: WindowId = app.get_window_state().get_id();
2047 app.dispatch_window_event(WindowEvent::Ime(wid, ImeEvent::Disabled));
2048 }
2049 });
2050 }) as Box<dyn FnMut(Event)>);
2051 drop(
2052 html_el
2053 .add_event_listener_with_callback(WEB_EVENT_BLUR, on_ime_blur.as_ref().unchecked_ref()),
2054 );
2055 on_ime_blur.forget();
2056 WEB_IME_ELEMENT.with(|slot: &RefCell<Option<HtmlElement>>| {
2057 if let Ok(mut guard) = slot.try_borrow_mut() {
2058 *guard = Some(html_el);
2059 }
2060 });
2061}
2062
2063#[cfg(target_arch = "wasm32")]
2075fn web_native_action_bridge(kind: &str, arg1: &str, _arg2: &str) -> bool {
2076 if kind == NATIVE_ACTION_FULLSCREEN {
2077 if arg1 == WEB_FS_ACTION_ON {
2078 web_set_fullscreen(true);
2079 return true;
2080 }
2081 if arg1 == WEB_FS_ACTION_OFF {
2082 web_set_fullscreen(false);
2083 return true;
2084 }
2085 return false;
2086 }
2087 if kind == NATIVE_ACTION_OPEN_URL {
2088 if !is_valid_external_url(arg1) {
2089 return false;
2090 }
2091 let Some(win) = window() else {
2092 return false;
2093 };
2094 return win
2095 .open_with_url_and_target_and_features(
2096 arg1.trim(),
2097 WEB_OPEN_TARGET_BLANK,
2098 WEB_OPEN_FEATURES_SAFE,
2099 )
2100 .is_ok();
2101 }
2102 if kind != NATIVE_ACTION_IME {
2103 return false;
2104 }
2105 WEB_IME_ELEMENT.with(|slot: &RefCell<Option<HtmlElement>>| {
2106 let Ok(guard) = slot.try_borrow() else {
2107 return false;
2108 };
2109 let Some(el) = guard.as_ref() else {
2110 return false;
2111 };
2112 if arg1 == WEB_IME_ACTION_SHOW {
2113 WEB_IME_ACTIVE.with(|a: &Cell<bool>| a.set(true));
2114 let already_focused: bool = window()
2115 .and_then(|win: Window| win.document())
2116 .and_then(|doc: Document| doc.active_element())
2117 .map(|active_el: Element| active_el.id() == WEB_IME_INPUT_ID)
2118 .unwrap_or(false);
2119 if !already_focused {
2120 drop(el.focus());
2121 }
2122 true
2123 } else if arg1 == WEB_IME_ACTION_HIDE {
2124 WEB_IME_ACTIVE.with(|a: &Cell<bool>| a.set(false));
2125 WEB_IME_COMPOSING.with(|c: &Cell<bool>| c.set(false));
2126 let key: JsValue = JsValue::from_str(WEB_PROP_VALUE);
2127 let _: Result<bool, JsValue> = Reflect::set(el.as_ref(), &key, &JsValue::from_str(""));
2128 drop(el.blur());
2129 true
2130 } else {
2131 false
2132 }
2133 })
2134}
2135
2136#[cfg(target_arch = "wasm32")]
2144fn web_queue_key_up(key: &str, code_str: &str, mods: Modifiers) {
2145 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2146 if let Ok(mut borrow) = slot.try_borrow_mut()
2147 && let Some((app, _)) = borrow.as_mut()
2148 {
2149 let wid: WindowId = app.get_window_state().get_id();
2150 let code: KeyCode = web_map_key(key, code_str);
2151 app.dispatch_window_event(WindowEvent::KeyUp(wid, KeyEvent::new(code, mods, false)));
2152 }
2153 });
2154}
2155
2156#[cfg(target_arch = "wasm32")]
2166fn web_read_window_css_viewport(win: &Window) -> (f64, f64) {
2167 if let Ok(vv) = Reflect::get(win.as_ref(), &JsValue::from_str(WEB_PROP_VISUAL_VIEWPORT))
2168 && !vv.is_null()
2169 && !vv.is_undefined()
2170 {
2171 let vv_scale: f64 = Reflect::get(&vv, &JsValue::from_str(WEB_PROP_SCALE))
2172 .ok()
2173 .and_then(|v: JsValue| v.as_f64())
2174 .filter(|v: &f64| v.is_finite() && *v > 0.0)
2175 .unwrap_or(1.0);
2176 if vv_scale <= WEB_PINCH_ZOOM_THRESHOLD {
2177 let vw: Option<f64> = Reflect::get(&vv, &JsValue::from_str(WEB_PROP_WIDTH))
2178 .ok()
2179 .and_then(|v: JsValue| v.as_f64())
2180 .filter(|v: &f64| v.is_finite() && *v >= 64.0);
2181 let vh: Option<f64> = Reflect::get(&vv, &JsValue::from_str(WEB_PROP_HEIGHT))
2182 .ok()
2183 .and_then(|v: JsValue| v.as_f64())
2184 .filter(|v: &f64| v.is_finite() && *v >= 64.0);
2185 if let (Some(w), Some(h)) = (vw, vh) {
2186 return (w, h);
2187 }
2188 }
2189 }
2190 if let Some(root) = win
2191 .document()
2192 .and_then(|doc: Document| doc.document_element())
2193 {
2194 let cw: f64 = f64::from(root.client_width());
2195 let ch: f64 = f64::from(root.client_height());
2196 if cw >= 64.0 && ch >= 64.0 {
2197 return (cw, ch);
2198 }
2199 }
2200 let w: f64 = win
2201 .inner_width()
2202 .ok()
2203 .and_then(|v: JsValue| v.as_f64())
2204 .filter(|w: &f64| w.is_finite() && *w >= 64.0)
2205 .unwrap_or(SHOWCASE_WINDOW_WIDTH as f64);
2206 let h: f64 = win
2207 .inner_height()
2208 .ok()
2209 .and_then(|v: JsValue| v.as_f64())
2210 .filter(|h: &f64| h.is_finite() && *h >= 64.0)
2211 .unwrap_or(SHOWCASE_WINDOW_HEIGHT as f64);
2212 (w, h)
2213}
2214
2215#[cfg(target_arch = "wasm32")]
2221fn web_query_initial_viewport() -> (f64, f64, f64, f64, f32) {
2222 let Some(win) = window() else {
2223 return (
2224 0.0,
2225 0.0,
2226 SHOWCASE_WINDOW_WIDTH as f64,
2227 SHOWCASE_WINDOW_HEIGHT as f64,
2228 1.0,
2229 );
2230 };
2231 let dpr_raw: f64 = win.device_pixel_ratio();
2232 let dpr: f32 = if dpr_raw.is_finite() && dpr_raw > 0.0 {
2233 (dpr_raw as f32).clamp(WEB_DPR_MIN, WEB_DPR_MAX)
2234 } else {
2235 1.0
2236 };
2237 let mut left: f64 = 0.0;
2238 let mut top: f64 = 0.0;
2239 let mut css_w: f64 = 0.0;
2240 let mut css_h: f64 = 0.0;
2241 if let Some(doc) = win.document()
2242 && let Ok(Some(el)) = doc.query_selector(WEB_SELECTOR_CANVAS)
2243 && let Ok(canvas) = el.dyn_into::<HtmlCanvasElement>()
2244 {
2245 let rect: DomRect = canvas.get_bounding_client_rect();
2246 left = rect.left();
2247 top = rect.top();
2248 css_w = rect.width();
2249 css_h = rect.height();
2250 }
2251 let (win_w, win_h): (f64, f64) = web_read_window_css_viewport(&win);
2252 if !css_w.is_finite() || css_w < 64.0 {
2253 css_w = win_w;
2254 }
2255 if !css_h.is_finite() || css_h < 64.0 {
2256 css_h = win_h;
2257 }
2258 (left, top, css_w, css_h, dpr)
2259}
2260
2261#[cfg(target_arch = "wasm32")]
2272fn web_refresh_cached_viewport(win: &Window, canvas: &HtmlCanvasElement) -> bool {
2273 let rect: DomRect = canvas.get_bounding_client_rect();
2274 let left: f64 = rect.left();
2275 let top: f64 = rect.top();
2276 let (win_w, win_h): (f64, f64) = web_read_window_css_viewport(win);
2277 let css_w: f64 = if rect.width().is_finite() && rect.width() >= 64.0 {
2278 rect.width()
2279 } else {
2280 win_w
2281 };
2282 let css_h: f64 = if rect.height().is_finite() && rect.height() >= 64.0 {
2283 rect.height()
2284 } else {
2285 win_h
2286 };
2287 let dpr_raw: f64 = win.device_pixel_ratio();
2288 let dpr: f32 = if dpr_raw.is_finite() && dpr_raw > 0.0 {
2289 (dpr_raw as f32).clamp(WEB_DPR_MIN, WEB_DPR_MAX)
2290 } else {
2291 1.0
2292 };
2293 let prev: (f64, f64, f64, f64, f32) = WEB_CACHED_VIEWPORT.with(Cell::get);
2294 let changed: bool = (prev.0 - left).abs() > 0.25
2295 || (prev.1 - top).abs() > 0.25
2296 || (prev.2 - css_w).abs() > 0.25
2297 || (prev.3 - css_h).abs() > 0.25
2298 || (prev.4 - dpr).abs() > 0.005;
2299 if changed {
2300 WEB_CACHED_VIEWPORT.with(|cell: &Cell<(f64, f64, f64, f64, f32)>| {
2301 cell.set((left, top, css_w, css_h, dpr));
2302 });
2303 WEB_VIEWPORT_DIRTY.with(|flag: &Cell<bool>| flag.set(true));
2304 }
2305 changed
2306}
2307
2308#[cfg(target_arch = "wasm32")]
2318fn web_apply_cached_viewport(canvas: &HtmlCanvasElement) -> bool {
2319 let (_, _, css_w, css_h, dpr): (f64, f64, f64, f64, f32) = WEB_CACHED_VIEWPORT.with(Cell::get);
2320 let dpr_f64: f64 = f64::from(dpr);
2321 let est_w: u32 = (css_w * dpr_f64)
2322 .round()
2323 .clamp(1.0, WEB_CANVAS_MAX_PHYS_DIM) as u32;
2324 let est_h: u32 = (css_h * dpr_f64)
2325 .round()
2326 .clamp(1.0, WEB_CANVAS_MAX_PHYS_DIM) as u32;
2327 let (obs_w, obs_h): (u32, u32) = WEB_OBSERVED_PHYS_SIZE.with(Cell::get);
2328 let has_obs: bool = obs_w >= 64 && obs_h >= 64;
2329 let matches_obs: bool = has_obs && obs_w.abs_diff(est_w) <= 2 && obs_h.abs_diff(est_h) <= 2;
2330 let (phys_w, phys_h): (u32, u32) = if matches_obs {
2331 (obs_w, obs_h)
2332 } else {
2333 (est_w, est_h)
2334 };
2335 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2336 let Ok(mut borrow) = slot.try_borrow_mut() else {
2337 return false;
2338 };
2339 let Some((app, _)) = borrow.as_mut() else {
2340 return false;
2341 };
2342 let ws: WindowState = app.get_window_state();
2343 let size_diff: bool = ws.get_physical_width() != phys_w
2344 || ws.get_physical_height() != phys_h
2345 || (ws.get_scale_factor() - dpr).abs() > 0.005
2346 || canvas.width() != phys_w
2347 || canvas.height() != phys_h;
2348 if !size_diff {
2349 return false;
2350 }
2351 if canvas.width() != phys_w {
2352 canvas.set_width(phys_w);
2353 }
2354 if canvas.height() != phys_h {
2355 canvas.set_height(phys_h);
2356 }
2357 app.set_exact_physical_viewport(phys_w, phys_h, dpr);
2358 true
2359 })
2360}
2361
2362#[cfg(target_arch = "wasm32")]
2368fn web_sync_safe_area() -> bool {
2369 let measured: SafeAreaInsets = web_query_safe_area_insets();
2370 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2371 let Ok(mut borrow) = slot.try_borrow_mut() else {
2372 return false;
2373 };
2374 let Some((app, _)) = borrow.as_mut() else {
2375 return false;
2376 };
2377 let effective: SafeAreaInsets = if app.is_immersive_fullscreen() {
2378 SafeAreaInsets::default()
2379 } else {
2380 measured
2381 };
2382 let current: SafeAreaInsets = app.get_context().get_safe_area().get_untracked();
2383 if current == effective {
2384 return false;
2385 }
2386 let wid: WindowId = app.get_window_state().get_id();
2387 app.dispatch_window_event(WindowEvent::SafeAreaChanged(wid, effective));
2388 true
2389 })
2390}
2391
2392#[cfg(target_arch = "wasm32")]
2398fn web_report_host_refresh_rate(measured_hz: f32) {
2399 let mut needs_redraw: bool = false;
2400 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2401 if let Ok(mut borrow) = slot.try_borrow_mut()
2402 && let Some((app, _)) = borrow.as_mut()
2403 {
2404 let prev_fps: f32 = app.get_context().get_live_fps().get_untracked();
2405 app.report_host_refresh_rate(measured_hz);
2406 let next_fps: f32 = app.get_context().get_live_fps().get_untracked();
2407 if (next_fps - prev_fps).abs() >= 1.0 {
2408 needs_redraw = true;
2409 }
2410 }
2411 });
2412 if needs_redraw {
2413 web_mark_needs_frame();
2414 }
2415}
2416
2417#[cfg(target_arch = "wasm32")]
2427fn web_flush_frame(dt_secs: f32) -> u64 {
2428 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2429 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2430 Ok(guard) => guard,
2431 Err(_) => return 0,
2432 };
2433 let Some((app, state)) = borrow.as_mut() else {
2434 return 0;
2435 };
2436 let coord: ShowcaseWebDualCanvasCoordinator = web_dual_canvas_snapshot();
2437 state.sync_adaptive_from_web_coordinator(app, &coord);
2438 let hash: u64 = app
2439 .step_game_frame(dt_secs)
2440 .map(|stats: FrameStats| stats.get_frame_hash())
2441 .unwrap_or(0);
2442 state.sync_adaptive_from_web_coordinator(app, &coord);
2443 let pump: bool = app.should_pump_frames();
2444 WEB_SHOULD_PUMP.with(|flag: &Cell<bool>| flag.set(pump));
2445 hash
2446 })
2447}
2448
2449#[cfg(target_arch = "wasm32")]
2455#[wasm_bindgen]
2456pub fn euv_example_web_start() -> u64 {
2457 reset_reactive_runtime();
2458 register_frame_wakeup(web_mark_needs_frame);
2459 let (left, top, css_w, css_h, dpr): (f64, f64, f64, f64, f32) = web_query_initial_viewport();
2460 WEB_CACHED_VIEWPORT.with(|cell: &Cell<(f64, f64, f64, f64, f32)>| {
2461 cell.set((left, top, css_w, css_h, dpr));
2462 });
2463 WEB_VIEWPORT_DIRTY.with(|flag: &Cell<bool>| flag.set(false));
2464 let logical_w: u32 = css_w.round().max(64.0) as u32;
2465 let logical_h: u32 = css_h.round().max(64.0) as u32;
2466 let phys_w: u32 = (css_w * f64::from(dpr))
2467 .round()
2468 .clamp(1.0, WEB_CANVAS_MAX_PHYS_DIM) as u32;
2469 let phys_h: u32 = (css_h * f64::from(dpr))
2470 .round()
2471 .clamp(1.0, WEB_CANVAS_MAX_PHYS_DIM) as u32;
2472 if let Some(win) = window()
2473 && let Some(doc) = win.document()
2474 && let Ok(Some(el)) = doc.query_selector(WEB_SELECTOR_CANVAS)
2475 && let Ok(canvas) = el.dyn_into::<HtmlCanvasElement>()
2476 {
2477 if canvas.width() != phys_w {
2478 canvas.set_width(phys_w);
2479 }
2480 if canvas.height() != phys_h {
2481 canvas.set_height(phys_h);
2482 }
2483 }
2484 match create_showcase_app_with_viewport(false, RenderMode::Auto, logical_w, logical_h, dpr) {
2485 Ok((mut app, state)) => {
2486 app.set_exact_physical_viewport(phys_w, phys_h, dpr);
2487 if let Some(win) = window()
2488 && let Ok(hash_str) = win.location().hash()
2489 {
2490 let initial: String =
2491 resolve_web_hash_route(&hash_str, Some(state.get_dynamic_hub()));
2492 state.get_router().replace(&initial);
2493 let _: bool = state.get_route().set_if_changed(initial);
2494 }
2495 let route_watch: Signal<String> = state.get_route();
2496 let hub_watch: DynamicUpdateHub = state.get_dynamic_hub().clone();
2497 let (hash_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
2498 Effect::new(move || {
2499 let r: String = route_watch.get();
2500 if WEB_SYNCING_FROM_HISTORY.with(Cell::get) {
2501 return;
2502 }
2503 if let Some(win) = window() {
2504 let cur_raw: String = win.location().hash().unwrap_or_default();
2505 let cur_norm: String = resolve_web_hash_route(&cur_raw, Some(&hub_watch));
2506 if cur_norm != r {
2507 let target_hash: String = format!("#{r}");
2508 let _: Result<(), JsValue> = win.location().set_hash(&target_hash);
2509 }
2510 }
2511 })
2512 });
2513 let root_id: NodeId = app
2514 .get_scene()
2515 .with_read(SceneTree::get_root, NodeId::default());
2516 app.get_scene().with_write(
2517 |tree: &mut SceneTree| {
2518 tree.attach_scope(root_id, hash_scope);
2519 },
2520 (),
2521 );
2522 let hash: u64 = app
2523 .step_frame()
2524 .map(|stats: FrameStats| stats.get_frame_hash())
2525 .unwrap_or(0);
2526 let coord: ShowcaseWebDualCanvasCoordinator = web_dual_canvas_snapshot();
2527 state.sync_adaptive_from_web_coordinator(&mut app, &coord);
2528 let pump: bool = app.should_pump_frames();
2529 WEB_SHOULD_PUMP.with(|flag: &Cell<bool>| flag.set(pump));
2530 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2531 if let Ok(mut borrow) = slot.try_borrow_mut() {
2532 *borrow = Some((app, state));
2533 }
2534 });
2535 hash
2536 }
2537 Err(_) => 0,
2538 }
2539}
2540
2541#[cfg(target_arch = "wasm32")]
2551#[wasm_bindgen]
2552pub fn euv_example_render_route(route: &str) -> u64 {
2553 let has_runtime: bool = WEB_SHOWCASE_RUNTIME.with(
2554 |slot: &RefCell<Option<(App, ShowcaseState)>>| matches!(slot.try_borrow(), Ok(guard) if guard.is_some()),
2555 );
2556 if !has_runtime {
2557 let _: u64 = euv_example_web_start();
2558 }
2559 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2560 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2561 Ok(guard) => guard,
2562 Err(_) => return 0,
2563 };
2564 let Some((app, state)) = borrow.as_mut() else {
2565 return 0;
2566 };
2567 let _: bool = state.get_route().set_if_changed(route.to_string());
2568 app.step_frame()
2569 .map(|stats: FrameStats| stats.get_frame_hash())
2570 .unwrap_or(0)
2571 })
2572}
2573
2574#[cfg(target_arch = "wasm32")]
2585#[wasm_bindgen]
2586pub fn euv_web_pointer_move(x: f32, y: f32) -> u64 {
2587 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2588 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2589 Ok(guard) => guard,
2590 Err(_) => return 0,
2591 };
2592 let Some((app, _)) = borrow.as_mut() else {
2593 return 0;
2594 };
2595 let wid: WindowId = app.get_window_state().get_id();
2596 app.dispatch_window_event(WindowEvent::PointerMove(wid, PointerEvent::mouse(x, y)));
2597 app.step_frame()
2598 .map(|stats: FrameStats| stats.get_frame_hash())
2599 .unwrap_or(0)
2600 })
2601}
2602
2603#[cfg(target_arch = "wasm32")]
2614#[wasm_bindgen]
2615pub fn euv_web_pointer_down(x: f32, y: f32) -> u64 {
2616 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2617 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2618 Ok(guard) => guard,
2619 Err(_) => return 0,
2620 };
2621 let Some((app, _)) = borrow.as_mut() else {
2622 return 0;
2623 };
2624 let wid: WindowId = app.get_window_state().get_id();
2625 app.dispatch_window_event(WindowEvent::PointerDown(wid, PointerEvent::mouse(x, y)));
2626 app.step_frame()
2627 .map(|stats: FrameStats| stats.get_frame_hash())
2628 .unwrap_or(0)
2629 })
2630}
2631
2632#[cfg(target_arch = "wasm32")]
2643#[wasm_bindgen]
2644pub fn euv_web_pointer_up(x: f32, y: f32) -> u64 {
2645 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2646 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2647 Ok(guard) => guard,
2648 Err(_) => return 0,
2649 };
2650 let Some((app, _)) = borrow.as_mut() else {
2651 return 0;
2652 };
2653 let wid: WindowId = app.get_window_state().get_id();
2654 app.dispatch_window_event(WindowEvent::PointerUp(wid, PointerEvent::mouse(x, y)));
2655 app.step_frame()
2656 .map(|stats: FrameStats| stats.get_frame_hash())
2657 .unwrap_or(0)
2658 })
2659}
2660
2661#[cfg(target_arch = "wasm32")]
2672#[wasm_bindgen]
2673pub fn euv_web_scroll(dx: f32, dy: f32) -> u64 {
2674 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2675 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2676 Ok(guard) => guard,
2677 Err(_) => return 0,
2678 };
2679 let Some((app, _)) = borrow.as_mut() else {
2680 return 0;
2681 };
2682 let wid: WindowId = app.get_window_state().get_id();
2683 app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(dx, dy)));
2684 app.step_frame()
2685 .map(|stats: FrameStats| stats.get_frame_hash())
2686 .unwrap_or(0)
2687 })
2688}
2689
2690#[cfg(target_arch = "wasm32")]
2700#[wasm_bindgen]
2701pub fn euv_web_key_down(key: &str) -> u64 {
2702 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2703 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2704 Ok(guard) => guard,
2705 Err(_) => return 0,
2706 };
2707 let Some((app, state)) = borrow.as_mut() else {
2708 return 0;
2709 };
2710 let wid: WindowId = app.get_window_state().get_id();
2711 let code: KeyCode = match key {
2712 WEB_KEY_ENTER => KeyCode::Enter,
2713 WEB_KEY_BACKSPACE => KeyCode::Backspace,
2714 WEB_KEY_DELETE => KeyCode::Delete,
2715 WEB_KEY_ESCAPE => KeyCode::Escape,
2716 WEB_KEY_TAB => KeyCode::Tab,
2717 WEB_KEY_SPACE => KeyCode::Space,
2718 WEB_KEY_ARROW_LEFT => KeyCode::ArrowLeft,
2719 WEB_KEY_ARROW_RIGHT => KeyCode::ArrowRight,
2720 WEB_KEY_ARROW_UP => KeyCode::ArrowUp,
2721 WEB_KEY_ARROW_DOWN => KeyCode::ArrowDown,
2722 other => other
2723 .chars()
2724 .next()
2725 .map(KeyCode::Character)
2726 .unwrap_or(KeyCode::Unknown),
2727 };
2728 let key_ev: WindowEvent =
2729 WindowEvent::KeyDown(wid, KeyEvent::new(code, Modifiers::default(), false));
2730 state.get_game_host().ingest_event(&key_ev);
2731 app.dispatch_window_event(key_ev);
2732 if key.chars().count() == 1 {
2733 app.dispatch_window_event(WindowEvent::TextInput(wid, key.to_string()));
2734 }
2735 app.step_frame()
2736 .map(|stats: FrameStats| stats.get_frame_hash())
2737 .unwrap_or(0)
2738 })
2739}
2740
2741#[cfg(target_arch = "wasm32")]
2751#[wasm_bindgen]
2752pub fn euv_web_tick(dt_secs: f32) -> u64 {
2753 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2754 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2755 Ok(guard) => guard,
2756 Err(_) => return 0,
2757 };
2758 let Some((app, state)) = borrow.as_mut() else {
2759 return 0;
2760 };
2761 if !app.should_pump_frames() {
2762 return app.get_renderer().get_last_stats().get_frame_hash();
2763 }
2764 let cur_route: String = state.get_route().get_untracked();
2765 let on_game: bool =
2766 cur_route == ROUTE_GAME || cur_route == ROUTE_GAME_3D || cur_route == ROUTE_WATER;
2767 if on_game || app.has_active_animations() {
2768 return app
2769 .step_game_frame(dt_secs)
2770 .map(|stats: FrameStats| stats.get_frame_hash())
2771 .unwrap_or(0);
2772 }
2773 app.get_renderer().get_last_stats().get_frame_hash()
2774 })
2775}
2776
2777#[cfg(target_arch = "wasm32")]
2789#[wasm_bindgen]
2790pub fn euv_web_resize(width: u32, height: u32, dpr: f32) -> u64 {
2791 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2792 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2793 Ok(guard) => guard,
2794 Err(_) => return 0,
2795 };
2796 let Some((app, _)) = borrow.as_mut() else {
2797 return 0;
2798 };
2799 let w: u32 = width.max(64);
2800 let h: u32 = height.max(64);
2801 let scale: f32 = if dpr.is_finite() && dpr > 0.0 {
2802 dpr.clamp(WEB_DPR_MIN, WEB_DPR_MAX)
2803 } else {
2804 1.0
2805 };
2806 let phys_w: u32 = ((w as f64) * (scale as f64))
2807 .round()
2808 .clamp(1.0, WEB_CANVAS_MAX_PHYS_DIM) as u32;
2809 let phys_h: u32 = ((h as f64) * (scale as f64))
2810 .round()
2811 .clamp(1.0, WEB_CANVAS_MAX_PHYS_DIM) as u32;
2812 WEB_OBSERVED_PHYS_SIZE.with(|cell: &Cell<(u32, u32)>| cell.set((0, 0)));
2813 let (prev_l, prev_t, _, _, _): (f64, f64, f64, f64, f32) =
2814 WEB_CACHED_VIEWPORT.with(Cell::get);
2815 WEB_CACHED_VIEWPORT.with(|cell: &Cell<(f64, f64, f64, f64, f32)>| {
2816 cell.set((prev_l, prev_t, f64::from(w), f64::from(h), scale));
2817 });
2818 WEB_VIEWPORT_DIRTY.with(|flag: &Cell<bool>| flag.set(false));
2819 if let Some(win) = window()
2820 && let Some(doc) = win.document()
2821 && let Ok(Some(el)) = doc.query_selector(WEB_SELECTOR_CANVAS)
2822 && let Ok(canvas) = el.dyn_into::<HtmlCanvasElement>()
2823 {
2824 if canvas.width() != phys_w {
2825 canvas.set_width(phys_w);
2826 }
2827 if canvas.height() != phys_h {
2828 canvas.set_height(phys_h);
2829 }
2830 }
2831 app.set_exact_physical_viewport(phys_w, phys_h, scale);
2832 app.step_frame()
2833 .map(|stats: FrameStats| stats.get_frame_hash())
2834 .unwrap_or(0)
2835 })
2836}
2837
2838#[cfg(any(debug_assertions, test))]
2850#[must_use]
2851pub fn dispatch_automation_uri(app: &mut App, state: &ShowcaseState, uri: &str) -> Option<String> {
2852 let hooks: AiAppHooks = state.build_ai_hooks();
2853 AiSchemaProtocol::handle_uri_with_hooks(app, uri, Some(&hooks))
2854}
2855
2856#[cfg(all(debug_assertions, target_arch = "wasm32"))]
2862fn web_attach_dev_automation_bridge(win: &Window) {
2863 let on_json: Closure<dyn FnMut(String) -> String> =
2864 Closure::wrap(Box::new(|req_json: String| euv_dev_ai_schema(&req_json))
2865 as Box<dyn FnMut(String) -> String>);
2866 let _: Result<bool, JsValue> = Reflect::set(
2867 win.as_ref(),
2868 &JsValue::from_str(WEB_PROP_EUV_AUTOMATION),
2869 on_json.as_ref(),
2870 );
2871 on_json.forget();
2872 let on_uri: Closure<dyn FnMut(String) -> String> =
2873 Closure::wrap(
2874 Box::new(|uri: String| euv_dev_ai_uri(&uri)) as Box<dyn FnMut(String) -> String>
2875 );
2876 let _: Result<bool, JsValue> = Reflect::set(
2877 win.as_ref(),
2878 &JsValue::from_str(WEB_PROP_EUV_AUTOMATION_URI),
2879 on_uri.as_ref(),
2880 );
2881 on_uri.forget();
2882}
2883
2884#[cfg(all(debug_assertions, target_arch = "wasm32"))]
2894#[wasm_bindgen]
2895pub fn euv_dev_ai_schema(request_json: &str) -> String {
2896 let out: String = WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2897 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2898 Ok(guard) => guard,
2899 Err(_) => return String::new(),
2900 };
2901 let Some((app, state)) = borrow.as_mut() else {
2902 return String::new();
2903 };
2904 let hooks: AiAppHooks = state.build_ai_hooks();
2905 AiSchemaProtocol::handle_json_with_hooks(app, request_json, Some(&hooks))
2906 });
2907 web_mark_needs_frame();
2908 out
2909}
2910
2911#[cfg(all(debug_assertions, target_arch = "wasm32"))]
2921#[wasm_bindgen]
2922pub fn euv_dev_ai_uri(uri: &str) -> String {
2923 let out: String = WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2924 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2925 Ok(guard) => guard,
2926 Err(_) => return String::new(),
2927 };
2928 let Some((app, state)) = borrow.as_mut() else {
2929 return String::new();
2930 };
2931 let hooks: AiAppHooks = state.build_ai_hooks();
2932 AiSchemaProtocol::handle_uri_with_hooks(app, uri, Some(&hooks)).unwrap_or_default()
2933 });
2934 web_mark_needs_frame();
2935 out
2936}
2937
2938#[cfg(target_arch = "wasm32")]
2944#[wasm_bindgen]
2945pub fn euv_web_current_route() -> String {
2946 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2947 match slot.try_borrow() {
2948 Ok(guard) => guard
2949 .as_ref()
2950 .map(|(_, state): &(App, ShowcaseState)| state.get_route().get_untracked())
2951 .unwrap_or_default(),
2952 Err(_) => String::new(),
2953 }
2954 })
2955}