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 let mut fs_exited: bool = false;
1781 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1782 if let Ok(mut borrow) = slot.try_borrow_mut()
1783 && let Some((app, _)) = borrow.as_mut()
1784 {
1785 let was_fs: bool = app.is_immersive_fullscreen() || is_fullscreen_active();
1786 let wid: WindowId = app.get_window_state().get_id();
1787 app.dispatch_window_event(WindowEvent::PointerUp(wid, ptr));
1788 let now_fs: bool = app.is_immersive_fullscreen() || is_fullscreen_active();
1789 fs_exited = was_fs && !now_fs;
1790 queued = true;
1791 }
1792 });
1793 if fs_exited {
1794 let _: u64 = web_flush_frame(0.0);
1795 }
1796 if queued {
1797 web_mark_needs_frame();
1798 }
1799}
1800
1801#[cfg(target_arch = "wasm32")]
1807fn web_queue_pointer_cancel(pointer_id: u64) {
1808 let mut queued: bool = false;
1809 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1810 if let Ok(mut borrow) = slot.try_borrow_mut()
1811 && let Some((app, _)) = borrow.as_mut()
1812 {
1813 let wid: WindowId = app.get_window_state().get_id();
1814 app.dispatch_window_event(WindowEvent::PointerCancel(wid, pointer_id));
1815 queued = true;
1816 }
1817 });
1818 if queued {
1819 web_mark_needs_frame();
1820 }
1821}
1822
1823#[cfg(target_arch = "wasm32")]
1832fn web_queue_scroll_at(x: f32, y: f32, dx: f32, dy: f32) {
1833 web_ensure_visible_foreground();
1834 let mut queued: bool = false;
1835 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1836 if let Ok(mut borrow) = slot.try_borrow_mut()
1837 && let Some((app, _)) = borrow.as_mut()
1838 {
1839 let wid: WindowId = app.get_window_state().get_id();
1840 app.dispatch_window_event(WindowEvent::PointerMove(wid, PointerEvent::mouse(x, y)));
1841 app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(dx, dy)));
1842 queued = true;
1843 }
1844 });
1845 if queued {
1846 web_mark_needs_frame();
1847 }
1848}
1849
1850#[cfg(target_arch = "wasm32")]
1859fn web_queue_key_down(key: &str, code_str: &str, mods: Modifiers, repeat: bool) {
1860 if WEB_IME_COMPOSING.with(Cell::get) {
1861 return;
1862 }
1863 web_ensure_visible_foreground();
1864 let ime_active: bool = WEB_IME_ACTIVE.with(Cell::get);
1865 let mut queued: bool = false;
1866 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1867 if let Ok(mut borrow) = slot.try_borrow_mut()
1868 && let Some((app, _)) = borrow.as_mut()
1869 {
1870 let wid: WindowId = app.get_window_state().get_id();
1871 let code: KeyCode = web_map_key(key, code_str);
1872 let key_ev: WindowEvent = WindowEvent::KeyDown(wid, KeyEvent::new(code, mods, repeat));
1873 app.dispatch_window_event(key_ev);
1874 if web_should_dispatch_text_input(ime_active, mods, key) {
1875 app.dispatch_window_event(WindowEvent::TextInput(wid, key.to_string()));
1876 }
1877 queued = true;
1878 }
1879 });
1880 if queued {
1881 web_mark_needs_frame();
1882 }
1883}
1884
1885#[cfg(target_arch = "wasm32")]
1891fn web_queue_text_input(text: String) {
1892 if text.is_empty() {
1893 return;
1894 }
1895 let mut queued: bool = false;
1896 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1897 if let Ok(mut borrow) = slot.try_borrow_mut()
1898 && let Some((app, _)) = borrow.as_mut()
1899 {
1900 let wid: WindowId = app.get_window_state().get_id();
1901 app.dispatch_window_event(WindowEvent::TextInput(wid, text));
1902 queued = true;
1903 }
1904 });
1905 if queued {
1906 web_mark_needs_frame();
1907 }
1908}
1909
1910#[cfg(target_arch = "wasm32")]
1917fn web_flush_ime_element(el: &HtmlElement, fallback: Option<String>) {
1918 let key: JsValue = JsValue::from_str(WEB_PROP_VALUE);
1919 let el_text: Option<String> = Reflect::get(el.as_ref(), &key)
1920 .ok()
1921 .and_then(|val: JsValue| val.as_string())
1922 .filter(|s: &String| !s.is_empty());
1923 let _: Result<bool, JsValue> = Reflect::set(el.as_ref(), &key, &JsValue::from_str(""));
1924 let committed: Option<String> = el_text.or_else(|| fallback.filter(|s: &String| !s.is_empty()));
1925 if let Some(text) = committed {
1926 web_queue_text_input(text);
1927 }
1928}
1929
1930#[cfg(target_arch = "wasm32")]
1940fn web_event_is_composing(ev: &Event) -> bool {
1941 Reflect::get(ev.as_ref(), &JsValue::from_str(WEB_PROP_IS_COMPOSING))
1942 .ok()
1943 .and_then(|val: JsValue| val.as_bool())
1944 .unwrap_or(false)
1945}
1946
1947#[cfg(target_arch = "wasm32")]
1957fn web_event_data_string(ev: &Event) -> Option<String> {
1958 Reflect::get(ev.as_ref(), &JsValue::from_str(WEB_PROP_DATA))
1959 .ok()
1960 .and_then(|val: JsValue| val.as_string())
1961 .filter(|s: &String| !s.is_empty())
1962}
1963
1964#[cfg(target_arch = "wasm32")]
1970fn web_attach_ime_proxy(doc: &Document) {
1971 let Ok(raw_el) = doc.create_element(WEB_IME_INPUT_TAG) else {
1972 return;
1973 };
1974 let el: Element = raw_el;
1975 drop(el.set_attribute(WEB_IME_ATTR_ID, WEB_IME_INPUT_ID));
1976 drop(el.set_attribute(WEB_IME_ATTR_TYPE, WEB_IME_ATTR_TEXT));
1977 drop(el.set_attribute(WEB_IME_ATTR_AUTOCOMPLETE, WEB_IME_ATTR_OFF));
1978 drop(el.set_attribute(WEB_IME_ATTR_AUTOCORRECT, WEB_IME_ATTR_OFF));
1979 drop(el.set_attribute(WEB_IME_ATTR_AUTOCAPITALIZE, WEB_IME_ATTR_OFF));
1980 drop(el.set_attribute(WEB_IME_ATTR_SPELLCHECK, WEB_IME_ATTR_FALSE));
1981 drop(el.set_attribute(WEB_IME_ATTR_ARIA_LABEL, WEB_IME_ARIA_LABEL));
1982 drop(el.set_attribute(WEB_IME_ATTR_STYLE, WEB_IME_STYLE));
1983 let Ok(html_el) = el.dyn_into::<HtmlElement>() else {
1984 return;
1985 };
1986 if let Some(body) = doc.body() {
1987 drop(body.append_child(&html_el));
1988 }
1989 let on_ime_focus: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1990 WEB_IME_ACTIVE.with(|a: &Cell<bool>| a.set(true));
1991 }) as Box<dyn FnMut(Event)>);
1992 drop(
1993 html_el.add_event_listener_with_callback(
1994 WEB_EVENT_FOCUS,
1995 on_ime_focus.as_ref().unchecked_ref(),
1996 ),
1997 );
1998 on_ime_focus.forget();
1999 let comp_start: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
2000 WEB_IME_COMPOSING.with(|c: &Cell<bool>| c.set(true));
2001 }) as Box<dyn FnMut(Event)>);
2002 drop(html_el.add_event_listener_with_callback(
2003 WEB_EVENT_COMPOSITION_START,
2004 comp_start.as_ref().unchecked_ref(),
2005 ));
2006 comp_start.forget();
2007 let comp_update: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
2008 WEB_IME_COMPOSING.with(|c: &Cell<bool>| c.set(true));
2009 }) as Box<dyn FnMut(Event)>);
2010 drop(html_el.add_event_listener_with_callback(
2011 WEB_EVENT_COMPOSITION_UPDATE,
2012 comp_update.as_ref().unchecked_ref(),
2013 ));
2014 comp_update.forget();
2015 let comp_el: HtmlElement = html_el.clone();
2016 let comp_end: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |ev: Event| {
2017 WEB_IME_COMPOSING.with(|c: &Cell<bool>| c.set(false));
2018 let fallback: Option<String> = web_event_data_string(&ev);
2019 web_flush_ime_element(&comp_el, fallback);
2020 }) as Box<dyn FnMut(Event)>);
2021 drop(html_el.add_event_listener_with_callback(
2022 WEB_EVENT_COMPOSITION_END,
2023 comp_end.as_ref().unchecked_ref(),
2024 ));
2025 comp_end.forget();
2026 let inp_el: HtmlElement = html_el.clone();
2027 let on_input: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |ev: Event| {
2028 if !WEB_IME_COMPOSING.with(Cell::get) && !web_event_is_composing(&ev) {
2029 web_flush_ime_element(&inp_el, None);
2030 }
2031 }) as Box<dyn FnMut(Event)>);
2032 drop(
2033 html_el
2034 .add_event_listener_with_callback(WEB_EVENT_INPUT, on_input.as_ref().unchecked_ref()),
2035 );
2036 on_input.forget();
2037 let on_ime_blur: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
2038 WEB_IME_ACTIVE.with(|a: &Cell<bool>| a.set(false));
2039 WEB_IME_COMPOSING.with(|c: &Cell<bool>| c.set(false));
2040 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2041 if let Ok(mut borrow) = slot.try_borrow_mut()
2042 && let Some((app, _)) = borrow.as_mut()
2043 {
2044 let wid: WindowId = app.get_window_state().get_id();
2045 app.dispatch_window_event(WindowEvent::Ime(wid, ImeEvent::Disabled));
2046 }
2047 });
2048 }) as Box<dyn FnMut(Event)>);
2049 drop(
2050 html_el
2051 .add_event_listener_with_callback(WEB_EVENT_BLUR, on_ime_blur.as_ref().unchecked_ref()),
2052 );
2053 on_ime_blur.forget();
2054 WEB_IME_ELEMENT.with(|slot: &RefCell<Option<HtmlElement>>| {
2055 if let Ok(mut guard) = slot.try_borrow_mut() {
2056 *guard = Some(html_el);
2057 }
2058 });
2059}
2060
2061#[cfg(target_arch = "wasm32")]
2073fn web_native_action_bridge(kind: &str, arg1: &str, _arg2: &str) -> bool {
2074 if kind == NATIVE_ACTION_FULLSCREEN {
2075 if arg1 == WEB_FS_ACTION_ON {
2076 web_set_fullscreen(true);
2077 return true;
2078 }
2079 if arg1 == WEB_FS_ACTION_OFF {
2080 web_set_fullscreen(false);
2081 return true;
2082 }
2083 return false;
2084 }
2085 if kind == NATIVE_ACTION_OPEN_URL {
2086 if !is_valid_external_url(arg1) {
2087 return false;
2088 }
2089 let Some(win) = window() else {
2090 return false;
2091 };
2092 return win
2093 .open_with_url_and_target_and_features(
2094 arg1.trim(),
2095 WEB_OPEN_TARGET_BLANK,
2096 WEB_OPEN_FEATURES_SAFE,
2097 )
2098 .is_ok();
2099 }
2100 if kind != NATIVE_ACTION_IME {
2101 return false;
2102 }
2103 WEB_IME_ELEMENT.with(|slot: &RefCell<Option<HtmlElement>>| {
2104 let Ok(guard) = slot.try_borrow() else {
2105 return false;
2106 };
2107 let Some(el) = guard.as_ref() else {
2108 return false;
2109 };
2110 if arg1 == WEB_IME_ACTION_SHOW {
2111 WEB_IME_ACTIVE.with(|a: &Cell<bool>| a.set(true));
2112 let already_focused: bool = window()
2113 .and_then(|win: Window| win.document())
2114 .and_then(|doc: Document| doc.active_element())
2115 .map(|active_el: Element| active_el.id() == WEB_IME_INPUT_ID)
2116 .unwrap_or(false);
2117 if !already_focused {
2118 drop(el.focus());
2119 }
2120 true
2121 } else if arg1 == WEB_IME_ACTION_HIDE {
2122 WEB_IME_ACTIVE.with(|a: &Cell<bool>| a.set(false));
2123 WEB_IME_COMPOSING.with(|c: &Cell<bool>| c.set(false));
2124 let key: JsValue = JsValue::from_str(WEB_PROP_VALUE);
2125 let _: Result<bool, JsValue> = Reflect::set(el.as_ref(), &key, &JsValue::from_str(""));
2126 drop(el.blur());
2127 true
2128 } else {
2129 false
2130 }
2131 })
2132}
2133
2134#[cfg(target_arch = "wasm32")]
2142fn web_queue_key_up(key: &str, code_str: &str, mods: Modifiers) {
2143 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2144 if let Ok(mut borrow) = slot.try_borrow_mut()
2145 && let Some((app, _)) = borrow.as_mut()
2146 {
2147 let wid: WindowId = app.get_window_state().get_id();
2148 let code: KeyCode = web_map_key(key, code_str);
2149 app.dispatch_window_event(WindowEvent::KeyUp(wid, KeyEvent::new(code, mods, false)));
2150 }
2151 });
2152}
2153
2154#[cfg(target_arch = "wasm32")]
2164fn web_read_window_css_viewport(win: &Window) -> (f64, f64) {
2165 if let Ok(vv) = Reflect::get(win.as_ref(), &JsValue::from_str(WEB_PROP_VISUAL_VIEWPORT))
2166 && !vv.is_null()
2167 && !vv.is_undefined()
2168 {
2169 let vv_scale: f64 = Reflect::get(&vv, &JsValue::from_str(WEB_PROP_SCALE))
2170 .ok()
2171 .and_then(|v: JsValue| v.as_f64())
2172 .filter(|v: &f64| v.is_finite() && *v > 0.0)
2173 .unwrap_or(1.0);
2174 if vv_scale <= WEB_PINCH_ZOOM_THRESHOLD {
2175 let vw: Option<f64> = Reflect::get(&vv, &JsValue::from_str(WEB_PROP_WIDTH))
2176 .ok()
2177 .and_then(|v: JsValue| v.as_f64())
2178 .filter(|v: &f64| v.is_finite() && *v >= 64.0);
2179 let vh: Option<f64> = Reflect::get(&vv, &JsValue::from_str(WEB_PROP_HEIGHT))
2180 .ok()
2181 .and_then(|v: JsValue| v.as_f64())
2182 .filter(|v: &f64| v.is_finite() && *v >= 64.0);
2183 if let (Some(w), Some(h)) = (vw, vh) {
2184 return (w, h);
2185 }
2186 }
2187 }
2188 if let Some(root) = win
2189 .document()
2190 .and_then(|doc: Document| doc.document_element())
2191 {
2192 let cw: f64 = f64::from(root.client_width());
2193 let ch: f64 = f64::from(root.client_height());
2194 if cw >= 64.0 && ch >= 64.0 {
2195 return (cw, ch);
2196 }
2197 }
2198 let w: f64 = win
2199 .inner_width()
2200 .ok()
2201 .and_then(|v: JsValue| v.as_f64())
2202 .filter(|w: &f64| w.is_finite() && *w >= 64.0)
2203 .unwrap_or(SHOWCASE_WINDOW_WIDTH as f64);
2204 let h: f64 = win
2205 .inner_height()
2206 .ok()
2207 .and_then(|v: JsValue| v.as_f64())
2208 .filter(|h: &f64| h.is_finite() && *h >= 64.0)
2209 .unwrap_or(SHOWCASE_WINDOW_HEIGHT as f64);
2210 (w, h)
2211}
2212
2213#[cfg(target_arch = "wasm32")]
2219fn web_query_initial_viewport() -> (f64, f64, f64, f64, f32) {
2220 let Some(win) = window() else {
2221 return (
2222 0.0,
2223 0.0,
2224 SHOWCASE_WINDOW_WIDTH as f64,
2225 SHOWCASE_WINDOW_HEIGHT as f64,
2226 1.0,
2227 );
2228 };
2229 let dpr_raw: f64 = win.device_pixel_ratio();
2230 let dpr: f32 = if dpr_raw.is_finite() && dpr_raw > 0.0 {
2231 (dpr_raw as f32).clamp(WEB_DPR_MIN, WEB_DPR_MAX)
2232 } else {
2233 1.0
2234 };
2235 let mut left: f64 = 0.0;
2236 let mut top: f64 = 0.0;
2237 let mut css_w: f64 = 0.0;
2238 let mut css_h: f64 = 0.0;
2239 if let Some(doc) = win.document()
2240 && let Ok(Some(el)) = doc.query_selector(WEB_SELECTOR_CANVAS)
2241 && let Ok(canvas) = el.dyn_into::<HtmlCanvasElement>()
2242 {
2243 let rect: DomRect = canvas.get_bounding_client_rect();
2244 left = rect.left();
2245 top = rect.top();
2246 css_w = rect.width();
2247 css_h = rect.height();
2248 }
2249 let (win_w, win_h): (f64, f64) = web_read_window_css_viewport(&win);
2250 if !css_w.is_finite() || css_w < 64.0 {
2251 css_w = win_w;
2252 }
2253 if !css_h.is_finite() || css_h < 64.0 {
2254 css_h = win_h;
2255 }
2256 (left, top, css_w, css_h, dpr)
2257}
2258
2259#[cfg(target_arch = "wasm32")]
2270fn web_refresh_cached_viewport(win: &Window, canvas: &HtmlCanvasElement) -> bool {
2271 let rect: DomRect = canvas.get_bounding_client_rect();
2272 let left: f64 = rect.left();
2273 let top: f64 = rect.top();
2274 let (win_w, win_h): (f64, f64) = web_read_window_css_viewport(win);
2275 let css_w: f64 = if rect.width().is_finite() && rect.width() >= 64.0 {
2276 rect.width()
2277 } else {
2278 win_w
2279 };
2280 let css_h: f64 = if rect.height().is_finite() && rect.height() >= 64.0 {
2281 rect.height()
2282 } else {
2283 win_h
2284 };
2285 let dpr_raw: f64 = win.device_pixel_ratio();
2286 let dpr: f32 = if dpr_raw.is_finite() && dpr_raw > 0.0 {
2287 (dpr_raw as f32).clamp(WEB_DPR_MIN, WEB_DPR_MAX)
2288 } else {
2289 1.0
2290 };
2291 let prev: (f64, f64, f64, f64, f32) = WEB_CACHED_VIEWPORT.with(Cell::get);
2292 let changed: bool = (prev.0 - left).abs() > 0.25
2293 || (prev.1 - top).abs() > 0.25
2294 || (prev.2 - css_w).abs() > 0.25
2295 || (prev.3 - css_h).abs() > 0.25
2296 || (prev.4 - dpr).abs() > 0.005;
2297 if changed {
2298 WEB_CACHED_VIEWPORT.with(|cell: &Cell<(f64, f64, f64, f64, f32)>| {
2299 cell.set((left, top, css_w, css_h, dpr));
2300 });
2301 WEB_VIEWPORT_DIRTY.with(|flag: &Cell<bool>| flag.set(true));
2302 }
2303 changed
2304}
2305
2306#[cfg(target_arch = "wasm32")]
2316fn web_apply_cached_viewport(canvas: &HtmlCanvasElement) -> bool {
2317 let (_, _, css_w, css_h, dpr): (f64, f64, f64, f64, f32) = WEB_CACHED_VIEWPORT.with(Cell::get);
2318 let dpr_f64: f64 = f64::from(dpr);
2319 let est_w: u32 = (css_w * dpr_f64)
2320 .round()
2321 .clamp(1.0, WEB_CANVAS_MAX_PHYS_DIM) as u32;
2322 let est_h: u32 = (css_h * dpr_f64)
2323 .round()
2324 .clamp(1.0, WEB_CANVAS_MAX_PHYS_DIM) as u32;
2325 let (obs_w, obs_h): (u32, u32) = WEB_OBSERVED_PHYS_SIZE.with(Cell::get);
2326 let has_obs: bool = obs_w >= 64 && obs_h >= 64;
2327 let matches_obs: bool = has_obs && obs_w.abs_diff(est_w) <= 2 && obs_h.abs_diff(est_h) <= 2;
2328 let (phys_w, phys_h): (u32, u32) = if matches_obs {
2329 (obs_w, obs_h)
2330 } else {
2331 (est_w, est_h)
2332 };
2333 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2334 let Ok(mut borrow) = slot.try_borrow_mut() else {
2335 return false;
2336 };
2337 let Some((app, _)) = borrow.as_mut() else {
2338 return false;
2339 };
2340 let ws: WindowState = app.get_window_state();
2341 let size_diff: bool = ws.get_physical_width() != phys_w
2342 || ws.get_physical_height() != phys_h
2343 || (ws.get_scale_factor() - dpr).abs() > 0.005
2344 || canvas.width() != phys_w
2345 || canvas.height() != phys_h;
2346 if !size_diff {
2347 return false;
2348 }
2349 if canvas.width() != phys_w {
2350 canvas.set_width(phys_w);
2351 }
2352 if canvas.height() != phys_h {
2353 canvas.set_height(phys_h);
2354 }
2355 app.set_exact_physical_viewport(phys_w, phys_h, dpr);
2356 true
2357 })
2358}
2359
2360#[cfg(target_arch = "wasm32")]
2366fn web_sync_safe_area() -> bool {
2367 let measured: SafeAreaInsets = web_query_safe_area_insets();
2368 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2369 let Ok(mut borrow) = slot.try_borrow_mut() else {
2370 return false;
2371 };
2372 let Some((app, _)) = borrow.as_mut() else {
2373 return false;
2374 };
2375 let effective: SafeAreaInsets = if app.is_immersive_fullscreen() {
2376 SafeAreaInsets::default()
2377 } else {
2378 measured
2379 };
2380 let current: SafeAreaInsets = app.get_context().get_safe_area().get_untracked();
2381 if current == effective {
2382 return false;
2383 }
2384 let wid: WindowId = app.get_window_state().get_id();
2385 app.dispatch_window_event(WindowEvent::SafeAreaChanged(wid, effective));
2386 true
2387 })
2388}
2389
2390#[cfg(target_arch = "wasm32")]
2396fn web_report_host_refresh_rate(measured_hz: f32) {
2397 let mut needs_redraw: bool = false;
2398 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2399 if let Ok(mut borrow) = slot.try_borrow_mut()
2400 && let Some((app, _)) = borrow.as_mut()
2401 {
2402 let prev_fps: f32 = app.get_context().get_live_fps().get_untracked();
2403 app.report_host_refresh_rate(measured_hz);
2404 let next_fps: f32 = app.get_context().get_live_fps().get_untracked();
2405 if (next_fps - prev_fps).abs() >= 1.0 {
2406 needs_redraw = true;
2407 }
2408 }
2409 });
2410 if needs_redraw {
2411 web_mark_needs_frame();
2412 }
2413}
2414
2415#[cfg(target_arch = "wasm32")]
2425fn web_flush_frame(dt_secs: f32) -> u64 {
2426 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2427 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2428 Ok(guard) => guard,
2429 Err(_) => return 0,
2430 };
2431 let Some((app, state)) = borrow.as_mut() else {
2432 return 0;
2433 };
2434 let coord: ShowcaseWebDualCanvasCoordinator = web_dual_canvas_snapshot();
2435 state.sync_adaptive_from_web_coordinator(app, &coord);
2436 let hash: u64 = app
2437 .step_game_frame(dt_secs)
2438 .map(|stats: FrameStats| stats.get_frame_hash())
2439 .unwrap_or(0);
2440 state.sync_adaptive_from_web_coordinator(app, &coord);
2441 let pump: bool = app.should_pump_frames();
2442 WEB_SHOULD_PUMP.with(|flag: &Cell<bool>| flag.set(pump));
2443 hash
2444 })
2445}
2446
2447#[cfg(target_arch = "wasm32")]
2453#[wasm_bindgen]
2454pub fn euv_example_web_start() -> u64 {
2455 reset_reactive_runtime();
2456 register_frame_wakeup(web_mark_needs_frame);
2457 let (left, top, css_w, css_h, dpr): (f64, f64, f64, f64, f32) = web_query_initial_viewport();
2458 WEB_CACHED_VIEWPORT.with(|cell: &Cell<(f64, f64, f64, f64, f32)>| {
2459 cell.set((left, top, css_w, css_h, dpr));
2460 });
2461 WEB_VIEWPORT_DIRTY.with(|flag: &Cell<bool>| flag.set(false));
2462 let logical_w: u32 = css_w.round().max(64.0) as u32;
2463 let logical_h: u32 = css_h.round().max(64.0) as u32;
2464 let phys_w: u32 = (css_w * f64::from(dpr))
2465 .round()
2466 .clamp(1.0, WEB_CANVAS_MAX_PHYS_DIM) as u32;
2467 let phys_h: u32 = (css_h * f64::from(dpr))
2468 .round()
2469 .clamp(1.0, WEB_CANVAS_MAX_PHYS_DIM) as u32;
2470 if let Some(win) = window()
2471 && let Some(doc) = win.document()
2472 && let Ok(Some(el)) = doc.query_selector(WEB_SELECTOR_CANVAS)
2473 && let Ok(canvas) = el.dyn_into::<HtmlCanvasElement>()
2474 {
2475 if canvas.width() != phys_w {
2476 canvas.set_width(phys_w);
2477 }
2478 if canvas.height() != phys_h {
2479 canvas.set_height(phys_h);
2480 }
2481 }
2482 match create_showcase_app_with_viewport(false, RenderMode::Auto, logical_w, logical_h, dpr) {
2483 Ok((mut app, state)) => {
2484 app.set_exact_physical_viewport(phys_w, phys_h, dpr);
2485 if let Some(win) = window()
2486 && let Ok(hash_str) = win.location().hash()
2487 {
2488 let initial: String =
2489 resolve_web_hash_route(&hash_str, Some(state.get_dynamic_hub()));
2490 state.get_router().replace(&initial);
2491 let _: bool = state.get_route().set_if_changed(initial);
2492 }
2493 let route_watch: Signal<String> = state.get_route();
2494 let hub_watch: DynamicUpdateHub = state.get_dynamic_hub().clone();
2495 let (hash_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
2496 Effect::new(move || {
2497 let r: String = route_watch.get();
2498 if WEB_SYNCING_FROM_HISTORY.with(Cell::get) {
2499 return;
2500 }
2501 if let Some(win) = window() {
2502 let cur_raw: String = win.location().hash().unwrap_or_default();
2503 let cur_norm: String = resolve_web_hash_route(&cur_raw, Some(&hub_watch));
2504 if cur_norm != r {
2505 let target_hash: String = format!("#{r}");
2506 let _: Result<(), JsValue> = win.location().set_hash(&target_hash);
2507 }
2508 }
2509 })
2510 });
2511 let root_id: NodeId = app
2512 .get_scene()
2513 .with_read(SceneTree::get_root, NodeId::default());
2514 app.get_scene().with_write(
2515 |tree: &mut SceneTree| {
2516 tree.attach_scope(root_id, hash_scope);
2517 },
2518 (),
2519 );
2520 let hash: u64 = app
2521 .step_frame()
2522 .map(|stats: FrameStats| stats.get_frame_hash())
2523 .unwrap_or(0);
2524 let coord: ShowcaseWebDualCanvasCoordinator = web_dual_canvas_snapshot();
2525 state.sync_adaptive_from_web_coordinator(&mut app, &coord);
2526 let pump: bool = app.should_pump_frames();
2527 WEB_SHOULD_PUMP.with(|flag: &Cell<bool>| flag.set(pump));
2528 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2529 if let Ok(mut borrow) = slot.try_borrow_mut() {
2530 *borrow = Some((app, state));
2531 }
2532 });
2533 hash
2534 }
2535 Err(_) => 0,
2536 }
2537}
2538
2539#[cfg(target_arch = "wasm32")]
2549#[wasm_bindgen]
2550pub fn euv_example_render_route(route: &str) -> u64 {
2551 let has_runtime: bool = WEB_SHOWCASE_RUNTIME.with(
2552 |slot: &RefCell<Option<(App, ShowcaseState)>>| matches!(slot.try_borrow(), Ok(guard) if guard.is_some()),
2553 );
2554 if !has_runtime {
2555 let _: u64 = euv_example_web_start();
2556 }
2557 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2558 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2559 Ok(guard) => guard,
2560 Err(_) => return 0,
2561 };
2562 let Some((app, state)) = borrow.as_mut() else {
2563 return 0;
2564 };
2565 let _: bool = state.get_route().set_if_changed(route.to_string());
2566 app.step_frame()
2567 .map(|stats: FrameStats| stats.get_frame_hash())
2568 .unwrap_or(0)
2569 })
2570}
2571
2572#[cfg(target_arch = "wasm32")]
2583#[wasm_bindgen]
2584pub fn euv_web_pointer_move(x: f32, y: f32) -> u64 {
2585 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2586 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2587 Ok(guard) => guard,
2588 Err(_) => return 0,
2589 };
2590 let Some((app, _)) = borrow.as_mut() else {
2591 return 0;
2592 };
2593 let wid: WindowId = app.get_window_state().get_id();
2594 app.dispatch_window_event(WindowEvent::PointerMove(wid, PointerEvent::mouse(x, y)));
2595 app.step_frame()
2596 .map(|stats: FrameStats| stats.get_frame_hash())
2597 .unwrap_or(0)
2598 })
2599}
2600
2601#[cfg(target_arch = "wasm32")]
2612#[wasm_bindgen]
2613pub fn euv_web_pointer_down(x: f32, y: f32) -> u64 {
2614 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2615 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2616 Ok(guard) => guard,
2617 Err(_) => return 0,
2618 };
2619 let Some((app, _)) = borrow.as_mut() else {
2620 return 0;
2621 };
2622 let wid: WindowId = app.get_window_state().get_id();
2623 app.dispatch_window_event(WindowEvent::PointerDown(wid, PointerEvent::mouse(x, y)));
2624 app.step_frame()
2625 .map(|stats: FrameStats| stats.get_frame_hash())
2626 .unwrap_or(0)
2627 })
2628}
2629
2630#[cfg(target_arch = "wasm32")]
2641#[wasm_bindgen]
2642pub fn euv_web_pointer_up(x: f32, y: f32) -> u64 {
2643 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2644 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2645 Ok(guard) => guard,
2646 Err(_) => return 0,
2647 };
2648 let Some((app, _)) = borrow.as_mut() else {
2649 return 0;
2650 };
2651 let wid: WindowId = app.get_window_state().get_id();
2652 app.dispatch_window_event(WindowEvent::PointerUp(wid, PointerEvent::mouse(x, y)));
2653 app.step_frame()
2654 .map(|stats: FrameStats| stats.get_frame_hash())
2655 .unwrap_or(0)
2656 })
2657}
2658
2659#[cfg(target_arch = "wasm32")]
2670#[wasm_bindgen]
2671pub fn euv_web_scroll(dx: f32, dy: f32) -> u64 {
2672 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2673 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2674 Ok(guard) => guard,
2675 Err(_) => return 0,
2676 };
2677 let Some((app, _)) = borrow.as_mut() else {
2678 return 0;
2679 };
2680 let wid: WindowId = app.get_window_state().get_id();
2681 app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(dx, dy)));
2682 app.step_frame()
2683 .map(|stats: FrameStats| stats.get_frame_hash())
2684 .unwrap_or(0)
2685 })
2686}
2687
2688#[cfg(target_arch = "wasm32")]
2698#[wasm_bindgen]
2699pub fn euv_web_key_down(key: &str) -> u64 {
2700 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2701 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2702 Ok(guard) => guard,
2703 Err(_) => return 0,
2704 };
2705 let Some((app, state)) = borrow.as_mut() else {
2706 return 0;
2707 };
2708 let wid: WindowId = app.get_window_state().get_id();
2709 let code: KeyCode = match key {
2710 WEB_KEY_ENTER => KeyCode::Enter,
2711 WEB_KEY_BACKSPACE => KeyCode::Backspace,
2712 WEB_KEY_DELETE => KeyCode::Delete,
2713 WEB_KEY_ESCAPE => KeyCode::Escape,
2714 WEB_KEY_TAB => KeyCode::Tab,
2715 WEB_KEY_SPACE => KeyCode::Space,
2716 WEB_KEY_ARROW_LEFT => KeyCode::ArrowLeft,
2717 WEB_KEY_ARROW_RIGHT => KeyCode::ArrowRight,
2718 WEB_KEY_ARROW_UP => KeyCode::ArrowUp,
2719 WEB_KEY_ARROW_DOWN => KeyCode::ArrowDown,
2720 other => other
2721 .chars()
2722 .next()
2723 .map(KeyCode::Character)
2724 .unwrap_or(KeyCode::Unknown),
2725 };
2726 let key_ev: WindowEvent =
2727 WindowEvent::KeyDown(wid, KeyEvent::new(code, Modifiers::default(), false));
2728 state.get_game_host().ingest_event(&key_ev);
2729 app.dispatch_window_event(key_ev);
2730 if key.chars().count() == 1 {
2731 app.dispatch_window_event(WindowEvent::TextInput(wid, key.to_string()));
2732 }
2733 app.step_frame()
2734 .map(|stats: FrameStats| stats.get_frame_hash())
2735 .unwrap_or(0)
2736 })
2737}
2738
2739#[cfg(target_arch = "wasm32")]
2749#[wasm_bindgen]
2750pub fn euv_web_tick(dt_secs: f32) -> u64 {
2751 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2752 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2753 Ok(guard) => guard,
2754 Err(_) => return 0,
2755 };
2756 let Some((app, state)) = borrow.as_mut() else {
2757 return 0;
2758 };
2759 if !app.should_pump_frames() {
2760 return app.get_renderer().get_last_stats().get_frame_hash();
2761 }
2762 let cur_route: String = state.get_route().get_untracked();
2763 let on_game: bool =
2764 cur_route == ROUTE_GAME || cur_route == ROUTE_GAME_3D || cur_route == ROUTE_WATER;
2765 if on_game || app.has_active_animations() {
2766 return app
2767 .step_game_frame(dt_secs)
2768 .map(|stats: FrameStats| stats.get_frame_hash())
2769 .unwrap_or(0);
2770 }
2771 app.get_renderer().get_last_stats().get_frame_hash()
2772 })
2773}
2774
2775#[cfg(target_arch = "wasm32")]
2787#[wasm_bindgen]
2788pub fn euv_web_resize(width: u32, height: u32, dpr: f32) -> u64 {
2789 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2790 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2791 Ok(guard) => guard,
2792 Err(_) => return 0,
2793 };
2794 let Some((app, _)) = borrow.as_mut() else {
2795 return 0;
2796 };
2797 let w: u32 = width.max(64);
2798 let h: u32 = height.max(64);
2799 let scale: f32 = if dpr.is_finite() && dpr > 0.0 {
2800 dpr.clamp(WEB_DPR_MIN, WEB_DPR_MAX)
2801 } else {
2802 1.0
2803 };
2804 let phys_w: u32 = ((w as f64) * (scale as f64))
2805 .round()
2806 .clamp(1.0, WEB_CANVAS_MAX_PHYS_DIM) as u32;
2807 let phys_h: u32 = ((h as f64) * (scale as f64))
2808 .round()
2809 .clamp(1.0, WEB_CANVAS_MAX_PHYS_DIM) as u32;
2810 WEB_OBSERVED_PHYS_SIZE.with(|cell: &Cell<(u32, u32)>| cell.set((0, 0)));
2811 let (prev_l, prev_t, _, _, _): (f64, f64, f64, f64, f32) =
2812 WEB_CACHED_VIEWPORT.with(Cell::get);
2813 WEB_CACHED_VIEWPORT.with(|cell: &Cell<(f64, f64, f64, f64, f32)>| {
2814 cell.set((prev_l, prev_t, f64::from(w), f64::from(h), scale));
2815 });
2816 WEB_VIEWPORT_DIRTY.with(|flag: &Cell<bool>| flag.set(false));
2817 if let Some(win) = window()
2818 && let Some(doc) = win.document()
2819 && let Ok(Some(el)) = doc.query_selector(WEB_SELECTOR_CANVAS)
2820 && let Ok(canvas) = el.dyn_into::<HtmlCanvasElement>()
2821 {
2822 if canvas.width() != phys_w {
2823 canvas.set_width(phys_w);
2824 }
2825 if canvas.height() != phys_h {
2826 canvas.set_height(phys_h);
2827 }
2828 }
2829 app.set_exact_physical_viewport(phys_w, phys_h, scale);
2830 app.step_frame()
2831 .map(|stats: FrameStats| stats.get_frame_hash())
2832 .unwrap_or(0)
2833 })
2834}
2835
2836#[cfg(all(debug_assertions, target_arch = "wasm32"))]
2846#[wasm_bindgen]
2847pub fn euv_dev_ai_schema(request_json: &str) -> String {
2848 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2849 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2850 Ok(guard) => guard,
2851 Err(_) => return String::new(),
2852 };
2853 let Some((app, state)) = borrow.as_mut() else {
2854 return String::new();
2855 };
2856 let hooks: AiAppHooks = state.build_ai_hooks();
2857 AiSchemaProtocol::handle_json_with_hooks(app, request_json, Some(&hooks))
2858 })
2859}
2860
2861#[cfg(target_arch = "wasm32")]
2867#[wasm_bindgen]
2868pub fn euv_web_current_route() -> String {
2869 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2870 match slot.try_borrow() {
2871 Ok(guard) => guard
2872 .as_ref()
2873 .map(|(_, state): &(App, ShowcaseState)| state.get_route().get_untracked())
2874 .unwrap_or_default(),
2875 Err(_) => String::new(),
2876 }
2877 })
2878}