1use super::*;
2
3#[must_use]
14pub fn default_showcase_render_config(mode: RenderMode, prefer_direct_gpu: bool) -> RenderConfig {
15 match mode {
16 RenderMode::Software => RenderConfig::software(),
17 RenderMode::Hardware => {
18 if prefer_direct_gpu {
19 RenderConfig::hardware_direct()
20 } else {
21 RenderConfig::hardware()
22 }
23 }
24 RenderMode::Hybrid => RenderConfig::hybrid(),
25 RenderMode::Auto => RenderConfig::default(),
26 }
27}
28
29pub fn create_showcase_app_default(headless: bool) -> Result<(App, ShowcaseState), PlatformError> {
39 create_showcase_app(headless, RenderMode::Auto)
40}
41
42fn host_platform_matrix_index(platform: PlatformKind) -> usize {
52 match platform {
53 PlatformKind::Ios => 0,
54 PlatformKind::IpadOs => 1,
55 PlatformKind::Android | PlatformKind::HarmonyOs | PlatformKind::Wearable => 2,
56 PlatformKind::MacOs => 3,
57 PlatformKind::Windows => 4,
58 PlatformKind::Linux | PlatformKind::Terminal | PlatformKind::TerminalCli => 5,
59 PlatformKind::Web
60 | PlatformKind::MiniApp
61 | PlatformKind::QuickApp
62 | PlatformKind::Headless => 6,
63 }
64}
65
66pub fn create_showcase_app_with_viewport(
80 headless: bool,
81 mode: RenderMode,
82 logical_width: u32,
83 logical_height: u32,
84 initial_scale: f32,
85) -> Result<(App, ShowcaseState), PlatformError> {
86 EuvOverlayStack::clear();
87 reset_fullscreen_state();
88 clear_provided_theme();
89 let init_w: u32 = logical_width.max(320);
90 let init_h: u32 = logical_height.max(320);
91 let init_scale: f32 = if initial_scale.is_finite() && initial_scale > 0.0 {
92 initial_scale.clamp(0.5, 4.5)
93 } else {
94 1.0
95 };
96 let 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_should_dispatch_text_input(ime_active: bool, mods: Modifiers, key: &str) -> bool {
550 !ime_active && !mods.get_ctrl() && !mods.get_meta() && key.chars().count() == 1
551}
552
553#[cfg(target_arch = "wasm32")]
555#[wasm_bindgen(start)]
556pub fn euv_web_boot() {
557 let _: u64 = euv_example_web_start();
558 let Some(win): Option<Window> = window() else {
559 return;
560 };
561 let Some(doc): Option<Document> = win.document() else {
562 return;
563 };
564 let Ok(Some(el)) = doc.query_selector(WEB_SELECTOR_CANVAS) else {
565 return;
566 };
567 let Ok(canvas) = el.dyn_into::<HtmlCanvasElement>() else {
568 return;
569 };
570 web_attach_ime_proxy(&doc);
571 register_native_action_bridge(web_native_action_bridge);
572 register_frame_wakeup(web_mark_needs_frame);
573 let _: bool = web_refresh_cached_viewport(&win, &canvas);
574 let _: bool = web_apply_cached_viewport(&canvas);
575 let on_move: Closure<dyn FnMut(web_sys::PointerEvent)> =
576 Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
577 let ptr: PointerEvent = web_pointer_from_dom(&ev, None);
578 web_queue_pointer_move_event(ptr);
579 }) as Box<dyn FnMut(web_sys::PointerEvent)>);
580 drop(canvas.add_event_listener_with_callback(
581 WEB_EVENT_POINTER_MOVE,
582 on_move.as_ref().unchecked_ref(),
583 ));
584 on_move.forget();
585 let canvas_down: HtmlCanvasElement = canvas.clone();
586 let on_down: Closure<dyn FnMut(web_sys::PointerEvent)> =
587 Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
588 drop(canvas_down.set_pointer_capture(ev.pointer_id()));
589 let ptr: PointerEvent = web_pointer_from_dom(&ev, Some(true));
590 web_queue_pointer_down_event(ptr);
591 if !WEB_IME_ACTIVE.with(Cell::get) {
592 drop(canvas_down.focus());
593 }
594 }) as Box<dyn FnMut(web_sys::PointerEvent)>);
595 drop(canvas.add_event_listener_with_callback(
596 WEB_EVENT_POINTER_DOWN,
597 on_down.as_ref().unchecked_ref(),
598 ));
599 on_down.forget();
600 let canvas_up: HtmlCanvasElement = canvas.clone();
601 let on_up: Closure<dyn FnMut(web_sys::PointerEvent)> =
602 Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
603 ev.stop_propagation();
604 let ptr: PointerEvent = web_pointer_from_dom(&ev, Some(false));
605 web_queue_pointer_up_event(ptr);
606 drop(canvas_up.release_pointer_capture(ev.pointer_id()));
607 }) as Box<dyn FnMut(web_sys::PointerEvent)>);
608 drop(
609 canvas
610 .add_event_listener_with_callback(WEB_EVENT_POINTER_UP, on_up.as_ref().unchecked_ref()),
611 );
612 on_up.forget();
613 let on_cancel: Closure<dyn FnMut(web_sys::PointerEvent)> =
614 Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
615 ev.stop_propagation();
616 web_queue_pointer_cancel(web_pointer_id_from_dom(&ev));
617 }) as Box<dyn FnMut(web_sys::PointerEvent)>);
618 drop(canvas.add_event_listener_with_callback(
619 WEB_EVENT_POINTER_CANCEL,
620 on_cancel.as_ref().unchecked_ref(),
621 ));
622 drop(canvas.add_event_listener_with_callback(
623 WEB_EVENT_LOST_POINTER_CAPTURE,
624 on_cancel.as_ref().unchecked_ref(),
625 ));
626 on_cancel.forget();
627 let on_win_up: Closure<dyn FnMut(web_sys::PointerEvent)> =
628 Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
629 let ptr: PointerEvent = web_pointer_from_dom(&ev, Some(false));
630 web_queue_pointer_up_event(ptr);
631 }) as Box<dyn FnMut(web_sys::PointerEvent)>);
632 drop(win.add_event_listener_with_callback(
633 WEB_EVENT_POINTER_UP,
634 on_win_up.as_ref().unchecked_ref(),
635 ));
636 on_win_up.forget();
637 let on_win_cancel: Closure<dyn FnMut(web_sys::PointerEvent)> =
638 Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
639 web_queue_pointer_cancel(web_pointer_id_from_dom(&ev));
640 }) as Box<dyn FnMut(web_sys::PointerEvent)>);
641 drop(win.add_event_listener_with_callback(
642 WEB_EVENT_POINTER_CANCEL,
643 on_win_cancel.as_ref().unchecked_ref(),
644 ));
645 on_win_cancel.forget();
646 let on_touch_cancel: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
647 web_queue_pointer_cancel(0);
648 }) as Box<dyn FnMut(Event)>);
649 drop(canvas.add_event_listener_with_callback(
650 WEB_EVENT_TOUCH_CANCEL,
651 on_touch_cancel.as_ref().unchecked_ref(),
652 ));
653 drop(win.add_event_listener_with_callback(
654 WEB_EVENT_TOUCH_CANCEL,
655 on_touch_cancel.as_ref().unchecked_ref(),
656 ));
657 on_touch_cancel.forget();
658 let on_blur: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
659 web_queue_pointer_cancel(0);
660 web_dispatch_system_event(SystemEvent::FocusChanged(false));
661 }) as Box<dyn FnMut(Event)>);
662 drop(win.add_event_listener_with_callback(WEB_EVENT_BLUR, on_blur.as_ref().unchecked_ref()));
663 on_blur.forget();
664 web_attach_system_event_listeners(&win, &doc, &canvas);
665 let on_wheel: Closure<dyn FnMut(WheelEvent)> = Closure::wrap(Box::new(move |ev: WheelEvent| {
666 ev.prevent_default();
667 let (left, top, _, _, _): (f64, f64, f64, f64, f32) = WEB_CACHED_VIEWPORT.with(Cell::get);
668 let x: f32 = (ev.client_x() as f64 - left) as f32;
669 let y: f32 = (ev.client_y() as f64 - top) as f32;
670 let mult: f32 = match ev.delta_mode() {
671 1 => 20.0,
672 2 => 320.0,
673 _ => 1.0,
674 };
675 web_queue_scroll_at(
676 x,
677 y,
678 (ev.delta_x() as f32) * mult,
679 (ev.delta_y() as f32) * mult,
680 );
681 })
682 as Box<dyn FnMut(WheelEvent)>);
683 web_add_non_passive_listener(
684 canvas.as_ref(),
685 WEB_EVENT_WHEEL,
686 on_wheel.as_ref().unchecked_ref(),
687 );
688 on_wheel.forget();
689 let on_key: Closure<dyn FnMut(KeyboardEvent)> =
690 Closure::wrap(Box::new(move |ev: KeyboardEvent| {
691 let key: String = ev.key();
692 let code_str: String = ev.code();
693 let mods: Modifiers =
694 Modifiers::new(ev.shift_key(), ev.ctrl_key(), ev.alt_key(), ev.meta_key());
695 let ime_active: bool = WEB_IME_ACTIVE.with(Cell::get);
696 let cmd_or_ctrl: bool = mods.get_ctrl() || mods.get_meta();
697 let should_prevent: bool = if cmd_or_ctrl {
698 matches!(code_str.as_str(), WEB_CODE_KEY_K | WEB_CODE_KEY_A)
699 } else if ime_active {
700 matches!(
701 key.as_str(),
702 WEB_KEY_ARROW_UP
703 | WEB_KEY_ARROW_DOWN
704 | WEB_KEY_ARROW_LEFT
705 | WEB_KEY_ARROW_RIGHT
706 | WEB_KEY_BACKSPACE
707 )
708 } else {
709 matches!(
710 key.as_str(),
711 WEB_KEY_ARROW_UP
712 | WEB_KEY_ARROW_DOWN
713 | WEB_KEY_ARROW_LEFT
714 | WEB_KEY_ARROW_RIGHT
715 | WEB_KEY_PAGE_UP
716 | WEB_KEY_PAGE_DOWN
717 | WEB_KEY_HOME
718 | WEB_KEY_END
719 | WEB_KEY_BACKSPACE
720 | WEB_KEY_SPACE
721 )
722 };
723 if should_prevent {
724 ev.prevent_default();
725 }
726 web_queue_key_down(&key, &code_str, mods, ev.repeat());
727 }) as Box<dyn FnMut(KeyboardEvent)>);
728 drop(win.add_event_listener_with_callback(WEB_EVENT_KEY_DOWN, on_key.as_ref().unchecked_ref()));
729 on_key.forget();
730 let on_key_up: Closure<dyn FnMut(KeyboardEvent)> =
731 Closure::wrap(Box::new(move |ev: KeyboardEvent| {
732 let key: String = ev.key();
733 let code_str: String = ev.code();
734 let mods: Modifiers =
735 Modifiers::new(ev.shift_key(), ev.ctrl_key(), ev.alt_key(), ev.meta_key());
736 web_queue_key_up(&key, &code_str, mods);
737 }) as Box<dyn FnMut(KeyboardEvent)>);
738 drop(
739 win.add_event_listener_with_callback(WEB_EVENT_KEY_UP, on_key_up.as_ref().unchecked_ref()),
740 );
741 on_key_up.forget();
742 let on_paste: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |ev: Event| {
743 if let Some(pasted) = web_extract_paste_text(&ev)
744 && !pasted.is_empty()
745 {
746 ev.prevent_default();
747 web_queue_text_input(pasted);
748 }
749 }) as Box<dyn FnMut(Event)>);
750 drop(win.add_event_listener_with_callback(WEB_EVENT_PASTE, on_paste.as_ref().unchecked_ref()));
751 on_paste.forget();
752 let win_resize: Window = win.clone();
753 let canvas_resize: HtmlCanvasElement = canvas.clone();
754 let on_resize: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
755 web_apply_viewport_resize_immediate(&win_resize, &canvas_resize);
756 }) as Box<dyn FnMut(Event)>);
757 drop(
758 win.add_event_listener_with_callback(WEB_EVENT_RESIZE, on_resize.as_ref().unchecked_ref()),
759 );
760 if let Ok(vv) = Reflect::get(win.as_ref(), &JsValue::from_str(WEB_PROP_VISUAL_VIEWPORT))
761 && let Ok(vv_target) = vv.dyn_into::<EventTarget>()
762 {
763 drop(vv_target.add_event_listener_with_callback(
764 WEB_EVENT_RESIZE,
765 on_resize.as_ref().unchecked_ref(),
766 ));
767 }
768 on_resize.forget();
769 let win_ro: Window = win.clone();
770 let canvas_ro: HtmlCanvasElement = canvas.clone();
771 let on_ro: Closure<dyn FnMut()> = Closure::wrap(Box::new(move || {
772 web_apply_viewport_resize_immediate(&win_ro, &canvas_ro);
773 }) as Box<dyn FnMut()>);
774 let attach_ro_fn: Function =
775 Function::new_with_args(WEB_JS_ATTACH_RESIZE_ARGS, WEB_JS_ATTACH_RESIZE_OBSERVER);
776 drop(attach_ro_fn.call2(
777 &JsValue::NULL,
778 canvas.as_ref(),
779 on_ro.as_ref().unchecked_ref(),
780 ));
781 on_ro.forget();
782 let win_dpr: Window = win.clone();
783 let canvas_dpr: HtmlCanvasElement = canvas.clone();
784 let on_dpr: Closure<dyn FnMut()> = Closure::wrap(Box::new(move || {
785 web_apply_viewport_resize_immediate(&win_dpr, &canvas_dpr);
786 }) as Box<dyn FnMut()>);
787 let attach_dpr_fn: Function =
788 Function::new_with_args(WEB_JS_WATCH_DPR_ARGS, WEB_JS_WATCH_DPR_BODY);
789 drop(attach_dpr_fn.call1(&JsValue::NULL, on_dpr.as_ref().unchecked_ref()));
790 on_dpr.forget();
791 let win_raf: Window = win.clone();
792 let canvas_raf: HtmlCanvasElement = canvas.clone();
793 WEB_RAF_CALLBACK.with(|slot: &RefCell<Option<Closure<dyn FnMut(f64)>>>| {
794 if let Ok(mut guard) = slot.try_borrow_mut() {
795 *guard = Some(Closure::wrap(Box::new(move |ts: f64| {
796 WEB_RAF_ID.with(|id_cell: &Cell<Option<i32>>| id_cell.set(None));
797 if !web_should_pump_frames() {
798 WEB_RAF_LAST_TS.with(|ts_cell: &Cell<f64>| ts_cell.set(0.0));
799 WEB_RAF_ACCUM_SECS.with(|s_cell: &Cell<f32>| s_cell.set(0.0));
800 WEB_RAF_ACCUM_FRAMES.with(|f_cell: &Cell<u32>| f_cell.set(0));
801 return;
802 }
803 let prev_ts: f64 = WEB_RAF_LAST_TS.with(|ts_cell: &Cell<f64>| ts_cell.replace(ts));
804 let mut dt: f32 = 1.0 / 60.0;
805 let mut valid_step: bool = false;
806 if prev_ts > 0.0 {
807 let raw_dt: f32 = ((ts - prev_ts) / 1000.0) as f32;
808 if (0.001..=0.1).contains(&raw_dt) {
809 valid_step = true;
810 }
811 dt = raw_dt.clamp(0.001, 0.05);
812 }
813 if valid_step {
814 let next_secs: f32 = WEB_RAF_ACCUM_SECS.with(Cell::get) + dt;
815 let next_frames: u32 = WEB_RAF_ACCUM_FRAMES.with(Cell::get).saturating_add(1);
816 if next_secs >= 0.35 && next_frames >= 8 {
817 let measured_hz: f32 = (next_frames as f32) / next_secs;
818 WEB_RAF_ACCUM_SECS.with(|s_cell: &Cell<f32>| s_cell.set(0.0));
819 WEB_RAF_ACCUM_FRAMES.with(|f_cell: &Cell<u32>| f_cell.set(0));
820 WEB_RAF_CALIBRATED.with(|c: &Cell<bool>| c.set(true));
821 web_report_host_refresh_rate(measured_hz);
822 } else {
823 WEB_RAF_ACCUM_SECS.with(|s_cell: &Cell<f32>| s_cell.set(next_secs));
824 WEB_RAF_ACCUM_FRAMES.with(|f_cell: &Cell<u32>| f_cell.set(next_frames));
825 }
826 }
827 let resized_or_scaled: bool =
828 if WEB_VIEWPORT_DIRTY.with(|flag: &Cell<bool>| flag.replace(false)) {
829 web_apply_cached_viewport(&canvas_raf)
830 } else {
831 false
832 };
833 let cur_route: String = euv_web_current_route();
834 let on_game: bool = cur_route == ROUTE_GAME
835 || cur_route == ROUTE_GAME_3D
836 || cur_route == ROUTE_WATER;
837 let animating: bool = web_has_active_animations();
838 let dirty: bool = WEB_NEEDS_FRAME.with(|flag: &Cell<bool>| flag.replace(false))
839 || is_frame_needed();
840 let needs_continuous: bool = resized_or_scaled || on_game;
841 let needs_redraw: bool = animating || dirty;
842 if needs_continuous || needs_redraw {
843 let _: u64 = web_flush_frame(dt);
844 web_record_raf_submission_proxy_tick(&canvas_raf);
845 }
846 let calibrated: bool = WEB_RAF_CALIBRATED.with(Cell::get);
847 let still_active: bool = on_game
848 || web_has_active_animations()
849 || WEB_NEEDS_FRAME.with(Cell::get)
850 || is_frame_needed()
851 || !calibrated;
852 if still_active && web_should_pump_frames() {
853 web_start_raf_pump(&win_raf);
854 } else {
855 WEB_RAF_LAST_TS.with(|ts_cell: &Cell<f64>| ts_cell.set(0.0));
856 }
857 }) as Box<dyn FnMut(f64)>));
858 }
859 });
860 if doc.hidden() {
861 web_dispatch_system_event(SystemEvent::Background);
862 } else {
863 web_start_raf_pump(&win);
864 }
865}
866
867#[cfg(target_arch = "wasm32")]
873fn web_record_raf_submission_proxy_tick(canvas: &HtmlCanvasElement) {
874 let pixel_bytes: u64 = u64::from(canvas.width())
875 .saturating_mul(u64::from(canvas.height()))
876 .saturating_mul(4);
877 WEB_DUAL_CANVAS_COORDINATOR.with(|cell: &RefCell<ShowcaseWebDualCanvasCoordinator>| {
878 if let Ok(mut coord) = cell.try_borrow_mut() {
879 coord.record_raf_proxy_tick(pixel_bytes);
880 }
881 });
882}
883
884#[cfg(target_arch = "wasm32")]
896#[must_use]
897pub fn web_begin_independent_canvas_switch(
898 target: ShowcaseWebPresentationPath,
899 width: u32,
900 height: u32,
901) -> bool {
902 WEB_DUAL_CANVAS_COORDINATOR.with(|cell: &RefCell<ShowcaseWebDualCanvasCoordinator>| {
903 cell.try_borrow_mut()
904 .map(|mut coord: RefMut<'_, ShowcaseWebDualCanvasCoordinator>| {
905 coord.begin_switch(target, width, height)
906 })
907 .unwrap_or(false)
908 })
909}
910
911#[cfg(target_arch = "wasm32")]
923#[must_use]
924pub fn web_commit_independent_canvas_switch(
925 expected_width: u32,
926 expected_height: u32,
927 expected_scene_version: u64,
928) -> bool {
929 WEB_DUAL_CANVAS_COORDINATOR.with(|cell: &RefCell<ShowcaseWebDualCanvasCoordinator>| {
930 cell.try_borrow_mut()
931 .map(|mut coord: RefMut<'_, ShowcaseWebDualCanvasCoordinator>| {
932 coord.commit_at_frame_boundary(
933 expected_width,
934 expected_height,
935 expected_scene_version,
936 )
937 })
938 .unwrap_or(false)
939 })
940}
941
942#[cfg(target_arch = "wasm32")]
948#[must_use]
949pub fn web_dual_canvas_snapshot() -> ShowcaseWebDualCanvasCoordinator {
950 WEB_DUAL_CANVAS_COORDINATOR
951 .with(|cell: &RefCell<ShowcaseWebDualCanvasCoordinator>| cell.borrow().clone())
952}
953
954#[cfg(target_arch = "wasm32")]
960fn web_should_pump_frames() -> bool {
961 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
962 match slot.try_borrow() {
963 Ok(guard) => {
964 let pump: bool = guard
965 .as_ref()
966 .map(|(app, _): &(App, ShowcaseState)| app.should_pump_frames())
967 .unwrap_or(false);
968 WEB_SHOULD_PUMP.with(|flag: &Cell<bool>| flag.set(pump));
969 pump
970 }
971 Err(_) => WEB_SHOULD_PUMP.with(Cell::get),
972 }
973 })
974}
975
976#[cfg(target_arch = "wasm32")]
982fn web_start_raf_pump(win: &Window) {
983 if !web_should_pump_frames() {
984 return;
985 }
986 let already_scheduled: bool =
987 WEB_RAF_ID.with(|id_cell: &Cell<Option<i32>>| id_cell.get().is_some());
988 if already_scheduled {
989 return;
990 }
991 WEB_RAF_CALLBACK.with(|slot: &RefCell<Option<Closure<dyn FnMut(f64)>>>| {
992 if let Ok(cb_ref) = slot.try_borrow()
993 && let Some(cb) = cb_ref.as_ref()
994 {
995 let func: &Function = cb.as_ref().unchecked_ref();
996 if let Ok(req_id) = win.request_animation_frame(func) {
997 WEB_RAF_ID.with(|id_cell: &Cell<Option<i32>>| id_cell.set(Some(req_id)));
998 }
999 }
1000 });
1001}
1002
1003#[cfg(target_arch = "wasm32")]
1005fn web_stop_raf_pump() {
1006 let pending_id: Option<i32> = WEB_RAF_ID.with(|id_cell: &Cell<Option<i32>>| id_cell.take());
1007 if let Some(req_id) = pending_id
1008 && let Some(win) = window()
1009 {
1010 drop(win.cancel_animation_frame(req_id));
1011 }
1012 WEB_RAF_LAST_TS.with(|ts_cell: &Cell<f64>| ts_cell.set(0.0));
1013 WEB_RAF_ACCUM_SECS.with(|s_cell: &Cell<f32>| s_cell.set(0.0));
1014 WEB_RAF_ACCUM_FRAMES.with(|f_cell: &Cell<u32>| f_cell.set(0));
1015}
1016
1017#[cfg(target_arch = "wasm32")]
1023fn web_dispatch_system_event(event: SystemEvent) {
1024 let mut should_pump: bool = false;
1025 let mut handled: bool = false;
1026 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1027 if let Ok(mut borrow) = slot.try_borrow_mut()
1028 && let Some((app, _)) = borrow.as_mut()
1029 {
1030 app.dispatch_system_event(event);
1031 should_pump = app.should_pump_frames();
1032 handled = true;
1033 }
1034 });
1035 if !handled {
1036 return;
1037 }
1038 WEB_SHOULD_PUMP.with(|flag: &Cell<bool>| flag.set(should_pump));
1039 if !should_pump {
1040 web_stop_raf_pump();
1041 } else {
1042 WEB_RAF_LAST_TS.with(|ts_cell: &Cell<f64>| ts_cell.set(0.0));
1043 web_mark_needs_frame();
1044 if let Some(win) = window() {
1045 web_start_raf_pump(&win);
1046 }
1047 }
1048}
1049
1050#[cfg(target_arch = "wasm32")]
1060fn web_extract_paste_text(ev: &Event) -> Option<String> {
1061 let data: JsValue =
1062 Reflect::get(ev.as_ref(), &JsValue::from_str(WEB_PROP_CLIPBOARD_DATA)).ok()?;
1063 if data.is_null() || data.is_undefined() {
1064 return None;
1065 }
1066 let get_fn_val: JsValue = Reflect::get(&data, &JsValue::from_str(WEB_PROP_GET_DATA)).ok()?;
1067 let get_fn: Function = get_fn_val.dyn_into::<Function>().ok()?;
1068 let result: JsValue = get_fn
1069 .call1(&data, &JsValue::from_str(WEB_MIME_TEXT_PLAIN))
1070 .ok()?;
1071 result.as_string().filter(|s: &String| !s.is_empty())
1072}
1073
1074#[cfg(target_arch = "wasm32")]
1080fn web_sync_route_from_browser_history(win: &Window) {
1081 let raw_hash: String = win.location().hash().unwrap_or_default();
1082 let prev_guard: bool = WEB_SYNCING_FROM_HISTORY.with(|flag: &Cell<bool>| flag.replace(true));
1083 let mut updated: bool = false;
1084 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1085 if let Ok(mut borrow) = slot.try_borrow_mut()
1086 && let Some((app, state)) = borrow.as_mut()
1087 {
1088 let _: String = apply_showcase_history_route(app, state, &raw_hash);
1089 updated = true;
1090 }
1091 });
1092 WEB_SYNCING_FROM_HISTORY.with(|flag: &Cell<bool>| flag.set(prev_guard));
1093 if updated {
1094 let _: bool = web_sync_safe_area();
1095 web_mark_needs_frame();
1096 web_start_raf_pump(win);
1097 }
1098 if let Ok(href) = win.location().href() {
1099 web_dispatch_system_event(SystemEvent::DeepLink(href));
1100 }
1101}
1102
1103#[cfg(target_arch = "wasm32")]
1113fn web_doc_is_fullscreen(doc: &Document) -> bool {
1114 if doc.fullscreen_element().is_some() {
1115 return true;
1116 }
1117 Reflect::get(
1118 doc.as_ref(),
1119 &JsValue::from_str(WEB_PROP_WEBKIT_FULLSCREEN_ELEMENT),
1120 )
1121 .ok()
1122 .map(|v: JsValue| !v.is_null() && !v.is_undefined())
1123 .unwrap_or(false)
1124}
1125
1126#[cfg(target_arch = "wasm32")]
1134fn web_add_non_passive_listener(target: &EventTarget, event: &str, callback: &Function) {
1135 let opts: Object = Object::new();
1136 let _: Result<bool, JsValue> = Reflect::set(
1137 opts.as_ref(),
1138 &JsValue::from_str(WEB_OPT_PASSIVE),
1139 &JsValue::FALSE,
1140 );
1141 if let Ok(add_val) = Reflect::get(
1142 target.as_ref(),
1143 &JsValue::from_str(WEB_METHOD_ADD_EVENT_LISTENER),
1144 ) && let Ok(add_fn) = add_val.dyn_into::<Function>()
1145 && add_fn
1146 .call3(
1147 target.as_ref(),
1148 &JsValue::from_str(event),
1149 callback.as_ref(),
1150 opts.as_ref(),
1151 )
1152 .is_ok()
1153 {
1154 return;
1155 }
1156 drop(target.add_event_listener_with_callback(event, callback));
1157}
1158
1159#[cfg(target_arch = "wasm32")]
1161fn web_ensure_visible_foreground() {
1162 if WEB_SHOULD_PUMP.with(Cell::get) {
1163 return;
1164 }
1165 let is_hidden: bool = window()
1166 .and_then(|w: Window| w.document())
1167 .map(|d: Document| d.hidden())
1168 .unwrap_or(false);
1169 if !is_hidden {
1170 web_dispatch_system_event(SystemEvent::Foreground);
1171 }
1172}
1173
1174#[cfg(target_arch = "wasm32")]
1181fn web_apply_viewport_resize_immediate(win: &Window, canvas: &HtmlCanvasElement) {
1182 web_ensure_visible_foreground();
1183 let viewport_changed: bool = web_refresh_cached_viewport(win, canvas);
1184 let safe_changed: bool = web_sync_safe_area();
1185 let applied: bool = web_apply_cached_viewport(canvas);
1186 let changed_metrics: bool = viewport_changed || safe_changed;
1187 if changed_metrics || applied {
1188 WEB_VIEWPORT_DIRTY.with(|flag: &Cell<bool>| flag.set(false));
1189 let _: u64 = web_flush_frame(0.0);
1190 web_mark_needs_frame();
1191 web_start_raf_pump(win);
1192 }
1193}
1194
1195#[cfg(target_arch = "wasm32")]
1203fn web_sync_fullscreen_from_dom(win: &Window, doc: &Document, canvas: &HtmlCanvasElement) {
1204 web_ensure_visible_foreground();
1205 let dom_fs: bool = web_doc_is_fullscreen(doc);
1206 if !dom_fs {
1207 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1208 if let Ok(mut borrow) = slot.try_borrow_mut()
1209 && let Some((app, _)) = borrow.as_mut()
1210 && (app.is_immersive_fullscreen()
1211 || is_fullscreen_active()
1212 || EuvOverlayStack::has_fullscreen())
1213 {
1214 let _: usize = sync_external_fullscreen_exit();
1215 app.set_immersive_fullscreen(false);
1216 }
1217 });
1218 }
1219 let _: bool = web_refresh_cached_viewport(win, canvas);
1220 let _: bool = web_sync_safe_area();
1221 let _: bool = web_apply_cached_viewport(canvas);
1222 WEB_VIEWPORT_DIRTY.with(|flag: &Cell<bool>| flag.set(false));
1223 let _: u64 = web_flush_frame(0.0);
1224 web_mark_needs_frame();
1225 web_start_raf_pump(win);
1226}
1227
1228#[cfg(target_arch = "wasm32")]
1234fn web_dispatch_theme_changed(mode: ThemeMode) {
1235 let mut dispatched: bool = false;
1236 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1237 if let Ok(mut borrow) = slot.try_borrow_mut()
1238 && let Some((app, _)) = borrow.as_mut()
1239 {
1240 let wid: WindowId = app.get_window_state().get_id();
1241 app.dispatch_window_event(WindowEvent::ThemeChanged(wid, mode));
1242 dispatched = true;
1243 }
1244 });
1245 if dispatched {
1246 web_mark_needs_frame();
1247 }
1248}
1249
1250#[cfg(target_arch = "wasm32")]
1257fn web_handle_orientation_change(win: &Window, canvas: &HtmlCanvasElement) {
1258 web_apply_viewport_resize_immediate(win, canvas);
1259 let (_, _, css_w, css_h, _): (f64, f64, f64, f64, f32) = WEB_CACHED_VIEWPORT.with(Cell::get);
1260 let orient: ScreenOrientation = if css_w > css_h {
1261 ScreenOrientation::Landscape
1262 } else {
1263 ScreenOrientation::Portrait
1264 };
1265 web_dispatch_system_event(SystemEvent::OrientationChanged(orient));
1266 let _: u64 = web_flush_frame(0.0);
1267 web_mark_needs_frame();
1268 web_start_raf_pump(win);
1269}
1270
1271#[cfg(target_arch = "wasm32")]
1279fn web_attach_system_event_listeners(win: &Window, doc: &Document, canvas: &HtmlCanvasElement) {
1280 let doc_vis: Document = doc.clone();
1281 let win_vis: Window = win.clone();
1282 let canvas_vis: HtmlCanvasElement = canvas.clone();
1283 let on_vis: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1284 if doc_vis.hidden() {
1285 web_queue_pointer_cancel(0);
1286 web_dispatch_system_event(SystemEvent::Background);
1287 } else {
1288 let _: bool = web_refresh_cached_viewport(&win_vis, &canvas_vis);
1289 let _: bool = web_sync_safe_area();
1290 web_dispatch_system_event(SystemEvent::Foreground);
1291 }
1292 }) as Box<dyn FnMut(Event)>);
1293 drop(doc.add_event_listener_with_callback(
1294 WEB_EVENT_VISIBILITY_CHANGE,
1295 on_vis.as_ref().unchecked_ref(),
1296 ));
1297 on_vis.forget();
1298 let win_focus: Window = win.clone();
1299 let canvas_focus: HtmlCanvasElement = canvas.clone();
1300 let on_focus: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1301 let _: bool = web_refresh_cached_viewport(&win_focus, &canvas_focus);
1302 let _: bool = web_sync_safe_area();
1303 web_dispatch_system_event(SystemEvent::Foreground);
1304 web_dispatch_system_event(SystemEvent::FocusChanged(true));
1305 }) as Box<dyn FnMut(Event)>);
1306 drop(win.add_event_listener_with_callback(WEB_EVENT_FOCUS, on_focus.as_ref().unchecked_ref()));
1307 on_focus.forget();
1308 let win_ps: Window = win.clone();
1309 let canvas_ps: HtmlCanvasElement = canvas.clone();
1310 let on_pageshow: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1311 let _: bool = web_refresh_cached_viewport(&win_ps, &canvas_ps);
1312 let _: bool = web_sync_safe_area();
1313 web_sync_route_from_browser_history(&win_ps);
1314 web_dispatch_system_event(SystemEvent::Foreground);
1315 }) as Box<dyn FnMut(Event)>);
1316 drop(win.add_event_listener_with_callback(
1317 WEB_EVENT_PAGE_SHOW,
1318 on_pageshow.as_ref().unchecked_ref(),
1319 ));
1320 on_pageshow.forget();
1321 let on_pagehide: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1322 web_queue_pointer_cancel(0);
1323 web_dispatch_system_event(SystemEvent::Background);
1324 }) as Box<dyn FnMut(Event)>);
1325 drop(win.add_event_listener_with_callback(
1326 WEB_EVENT_PAGE_HIDE,
1327 on_pagehide.as_ref().unchecked_ref(),
1328 ));
1329 on_pagehide.forget();
1330 let on_unload: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1331 web_dispatch_system_event(SystemEvent::Terminate);
1332 }) as Box<dyn FnMut(Event)>);
1333 drop(win.add_event_listener_with_callback(
1334 WEB_EVENT_BEFORE_UNLOAD,
1335 on_unload.as_ref().unchecked_ref(),
1336 ));
1337 on_unload.forget();
1338 let on_online: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1339 web_dispatch_system_event(SystemEvent::NetworkStatusChanged(NetworkStatus::Online));
1340 }) as Box<dyn FnMut(Event)>);
1341 drop(
1342 win.add_event_listener_with_callback(WEB_EVENT_ONLINE, on_online.as_ref().unchecked_ref()),
1343 );
1344 on_online.forget();
1345 let on_offline: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1346 web_dispatch_system_event(SystemEvent::NetworkStatusChanged(NetworkStatus::Offline));
1347 }) as Box<dyn FnMut(Event)>);
1348 drop(
1349 win.add_event_listener_with_callback(
1350 WEB_EVENT_OFFLINE,
1351 on_offline.as_ref().unchecked_ref(),
1352 ),
1353 );
1354 on_offline.forget();
1355 if let Ok(Some(mql)) = win.match_media(WEB_MEDIA_PREFERS_DARK) {
1356 let mql_cb: MediaQueryList = mql.clone();
1357 let on_theme: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1358 let next_theme: ThemeMode = if mql_cb.matches() {
1359 ThemeMode::Dark
1360 } else {
1361 ThemeMode::Light
1362 };
1363 web_dispatch_theme_changed(next_theme);
1364 })
1365 as Box<dyn FnMut(Event)>);
1366 drop(
1367 mql.add_event_listener_with_callback(
1368 WEB_EVENT_CHANGE,
1369 on_theme.as_ref().unchecked_ref(),
1370 ),
1371 );
1372 on_theme.forget();
1373 }
1374 let win_hist: Window = win.clone();
1375 let on_history: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1376 web_sync_route_from_browser_history(&win_hist);
1377 }) as Box<dyn FnMut(Event)>);
1378 drop(win.add_event_listener_with_callback(
1379 WEB_EVENT_HASH_CHANGE,
1380 on_history.as_ref().unchecked_ref(),
1381 ));
1382 drop(win.add_event_listener_with_callback(
1383 WEB_EVENT_POP_STATE,
1384 on_history.as_ref().unchecked_ref(),
1385 ));
1386 on_history.forget();
1387 let win_fs: Window = win.clone();
1388 let doc_fs: Document = doc.clone();
1389 let canvas_fs: HtmlCanvasElement = canvas.clone();
1390 let on_fs_change: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1391 web_sync_fullscreen_from_dom(&win_fs, &doc_fs, &canvas_fs);
1392 }) as Box<dyn FnMut(Event)>);
1393 drop(doc.add_event_listener_with_callback(
1394 WEB_EVENT_FULLSCREEN_CHANGE,
1395 on_fs_change.as_ref().unchecked_ref(),
1396 ));
1397 drop(doc.add_event_listener_with_callback(
1398 WEB_EVENT_WEBKIT_FULLSCREEN_CHANGE,
1399 on_fs_change.as_ref().unchecked_ref(),
1400 ));
1401 on_fs_change.forget();
1402 let win_orient: Window = win.clone();
1403 let canvas_orient: HtmlCanvasElement = canvas.clone();
1404 let on_orient: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1405 web_handle_orientation_change(&win_orient, &canvas_orient);
1406 }) as Box<dyn FnMut(Event)>);
1407 drop(win.add_event_listener_with_callback(
1408 WEB_EVENT_ORIENTATION_CHANGE,
1409 on_orient.as_ref().unchecked_ref(),
1410 ));
1411 if let Ok(screen_val) = Reflect::get(win.as_ref(), &JsValue::from_str(WEB_PROP_SCREEN))
1412 && !screen_val.is_null()
1413 && !screen_val.is_undefined()
1414 && let Ok(orient_val) = Reflect::get(&screen_val, &JsValue::from_str(WEB_PROP_ORIENTATION))
1415 && let Ok(orient_target) = orient_val.dyn_into::<EventTarget>()
1416 {
1417 drop(orient_target.add_event_listener_with_callback(
1418 WEB_EVENT_CHANGE,
1419 on_orient.as_ref().unchecked_ref(),
1420 ));
1421 }
1422 on_orient.forget();
1423 let vv_key: JsValue = JsValue::from_str(WEB_PROP_VISUAL_VIEWPORT);
1424 if let Ok(vv_val) = Reflect::get(win.as_ref(), &vv_key)
1425 && let Ok(vv_target) = vv_val.clone().dyn_into::<EventTarget>()
1426 {
1427 let win_vv: Window = win.clone();
1428 let vv_obj: JsValue = vv_val;
1429 let on_vv_resize: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1430 let inner_h: f32 = win_vv
1431 .inner_height()
1432 .ok()
1433 .and_then(|v: JsValue| v.as_f64())
1434 .unwrap_or(0.0) as f32;
1435 let h_key: JsValue = JsValue::from_str(WEB_PROP_HEIGHT);
1436 let vv_h: f32 = Reflect::get(&vv_obj, &h_key)
1437 .ok()
1438 .and_then(|v: JsValue| v.as_f64())
1439 .unwrap_or(inner_h as f64) as f32;
1440 let kb_delta: f32 = (inner_h - vv_h).max(0.0);
1441 let visible: bool = kb_delta >= WEB_KEYBOARD_MIN_DELTA_PX;
1442 let height: f32 = if visible { kb_delta } else { 0.0 };
1443 web_dispatch_system_event(SystemEvent::KeyboardVisibilityChanged { visible, height });
1444 if web_sync_safe_area() {
1445 web_mark_needs_frame();
1446 }
1447 })
1448 as Box<dyn FnMut(Event)>);
1449 drop(vv_target.add_event_listener_with_callback(
1450 WEB_EVENT_RESIZE,
1451 on_vv_resize.as_ref().unchecked_ref(),
1452 ));
1453 on_vv_resize.forget();
1454 }
1455}
1456
1457#[cfg(target_arch = "wasm32")]
1468fn web_map_key(key: &str, code_str: &str) -> KeyCode {
1469 match code_str {
1470 WEB_CODE_KEY_W => return KeyCode::Character('w'),
1471 WEB_CODE_KEY_A => return KeyCode::Character('a'),
1472 WEB_CODE_KEY_S => return KeyCode::Character('s'),
1473 WEB_CODE_KEY_D => return KeyCode::Character('d'),
1474 WEB_CODE_KEY_E => return KeyCode::Character('e'),
1475 WEB_CODE_KEY_R => return KeyCode::Character('r'),
1476 WEB_CODE_KEY_P => return KeyCode::Character('p'),
1477 WEB_CODE_KEY_J => return KeyCode::Character('j'),
1478 WEB_CODE_KEY_C => return KeyCode::Character('c'),
1479 WEB_CODE_KEY_V => return KeyCode::Character('v'),
1480 WEB_CODE_KEY_X => return KeyCode::Character('x'),
1481 WEB_CODE_KEY_Z => return KeyCode::Character('z'),
1482 WEB_CODE_KEY_K => return KeyCode::Character('k'),
1483 WEB_CODE_SPACE => return KeyCode::Space,
1484 WEB_KEY_ARROW_LEFT => return KeyCode::ArrowLeft,
1485 WEB_KEY_ARROW_RIGHT => return KeyCode::ArrowRight,
1486 WEB_KEY_ARROW_UP => return KeyCode::ArrowUp,
1487 WEB_KEY_ARROW_DOWN => return KeyCode::ArrowDown,
1488 WEB_KEY_HOME => return KeyCode::Home,
1489 WEB_KEY_END => return KeyCode::End,
1490 WEB_KEY_PAGE_UP => return KeyCode::PageUp,
1491 WEB_KEY_PAGE_DOWN => return KeyCode::PageDown,
1492 _ => {}
1493 }
1494 match key {
1495 WEB_KEY_ENTER => KeyCode::Enter,
1496 WEB_KEY_BACKSPACE => KeyCode::Backspace,
1497 WEB_KEY_DELETE => KeyCode::Delete,
1498 WEB_KEY_ESCAPE => KeyCode::Escape,
1499 WEB_KEY_TAB => KeyCode::Tab,
1500 WEB_KEY_SPACE => KeyCode::Space,
1501 WEB_KEY_ARROW_LEFT => KeyCode::ArrowLeft,
1502 WEB_KEY_ARROW_RIGHT => KeyCode::ArrowRight,
1503 WEB_KEY_ARROW_UP => KeyCode::ArrowUp,
1504 WEB_KEY_ARROW_DOWN => KeyCode::ArrowDown,
1505 WEB_KEY_HOME => KeyCode::Home,
1506 WEB_KEY_END => KeyCode::End,
1507 WEB_KEY_PAGE_UP => KeyCode::PageUp,
1508 WEB_KEY_PAGE_DOWN => KeyCode::PageDown,
1509 other => other
1510 .chars()
1511 .next()
1512 .map(KeyCode::Character)
1513 .unwrap_or(KeyCode::Unknown),
1514 }
1515}
1516
1517#[cfg(target_arch = "wasm32")]
1523fn web_has_active_animations() -> bool {
1524 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1525 match slot.try_borrow() {
1526 Ok(guard) => guard
1527 .as_ref()
1528 .map(|(app, _): &(App, ShowcaseState)| app.has_active_animations())
1529 .unwrap_or(false),
1530 Err(_) => false,
1531 }
1532 })
1533}
1534
1535#[cfg(target_arch = "wasm32")]
1537fn web_mark_needs_frame() {
1538 WEB_NEEDS_FRAME.with(|flag: &Cell<bool>| flag.set(true));
1539 let idle: bool = WEB_RAF_ID.with(|id_cell: &Cell<Option<i32>>| id_cell.get().is_none());
1540 if idle && let Some(win) = window() {
1541 web_start_raf_pump(&win);
1542 }
1543}
1544
1545#[cfg(target_arch = "wasm32")]
1555fn web_pointer_id_from_dom(ev: &web_sys::PointerEvent) -> u64 {
1556 (ev.pointer_id() as i64).unsigned_abs().saturating_add(1)
1557}
1558
1559#[cfg(target_arch = "wasm32")]
1570fn web_pointer_from_dom(ev: &web_sys::PointerEvent, force_pressed: Option<bool>) -> PointerEvent {
1571 let (left, top, _, _, _): (f64, f64, f64, f64, f32) = WEB_CACHED_VIEWPORT.with(Cell::get);
1572 let x: f32 = (ev.client_x() as f64 - left) as f32;
1573 let y: f32 = (ev.client_y() as f64 - top) as f32;
1574 let pid: u64 = web_pointer_id_from_dom(ev);
1575 let ptype: String = ev.pointer_type();
1576 let device: PointerDevice = if ptype == WEB_PTR_TYPE_TOUCH {
1577 PointerDevice::Touch
1578 } else if ptype == WEB_PTR_TYPE_PEN {
1579 PointerDevice::Stylus
1580 } else {
1581 PointerDevice::Mouse
1582 };
1583 let is_pressed: bool =
1584 force_pressed.unwrap_or_else(|| ev.buttons() != 0 || device == PointerDevice::Touch);
1585 let pressure: f32 = if is_pressed { 1.0 } else { 0.0 };
1586 let mods: Modifiers =
1587 Modifiers::new(ev.shift_key(), ev.ctrl_key(), ev.alt_key(), ev.meta_key());
1588 PointerEvent::new(
1589 pid,
1590 device,
1591 Point::new(x, y),
1592 PointerButton::Primary,
1593 pressure,
1594 mods,
1595 )
1596}
1597
1598#[cfg(target_arch = "wasm32")]
1604fn web_queue_pointer_move_event(ptr: PointerEvent) {
1605 let mut needs_redraw: bool = false;
1606 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1607 if let Ok(mut borrow) = slot.try_borrow_mut()
1608 && let Some((app, _)) = borrow.as_mut()
1609 {
1610 let rev_before: u64 = app.get_scene().with_read(SceneTree::get_revision, 0);
1611 let cursor_before: CursorIcon = app.get_last_cursor();
1612 let wid: WindowId = app.get_window_state().get_id();
1613 app.dispatch_window_event(WindowEvent::PointerMove(wid, ptr));
1614 let rev_after: u64 = app.get_scene().with_read(SceneTree::get_revision, 0);
1615 let cursor_after: CursorIcon = app.get_last_cursor();
1616 let active_drag: bool =
1617 ptr.get_pressure() > 0.0 || ptr.get_device() != PointerDevice::Mouse;
1618 let has_anim: bool = app
1619 .get_scene()
1620 .with_read(SceneTree::has_active_transitions, false);
1621 needs_redraw = rev_after != rev_before
1622 || cursor_after != cursor_before
1623 || active_drag
1624 || has_anim
1625 || is_frame_needed();
1626 }
1627 });
1628 if needs_redraw {
1629 web_mark_needs_frame();
1630 }
1631}
1632
1633#[cfg(target_arch = "wasm32")]
1639fn web_queue_pointer_down_event(ptr: PointerEvent) {
1640 web_ensure_visible_foreground();
1641 let mut queued: bool = false;
1642 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1643 if let Ok(mut borrow) = slot.try_borrow_mut()
1644 && let Some((app, _)) = borrow.as_mut()
1645 {
1646 let wid: WindowId = app.get_window_state().get_id();
1647 app.dispatch_window_event(WindowEvent::PointerDown(wid, ptr));
1648 queued = true;
1649 }
1650 });
1651 if queued {
1652 web_mark_needs_frame();
1653 }
1654}
1655
1656#[cfg(target_arch = "wasm32")]
1662fn web_queue_pointer_up_event(ptr: PointerEvent) {
1663 let mut queued: bool = false;
1664 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1665 if let Ok(mut borrow) = slot.try_borrow_mut()
1666 && let Some((app, _)) = borrow.as_mut()
1667 {
1668 let wid: WindowId = app.get_window_state().get_id();
1669 app.dispatch_window_event(WindowEvent::PointerUp(wid, ptr));
1670 queued = true;
1671 }
1672 });
1673 if queued {
1674 web_mark_needs_frame();
1675 }
1676}
1677
1678#[cfg(target_arch = "wasm32")]
1684fn web_queue_pointer_cancel(pointer_id: u64) {
1685 let mut queued: bool = false;
1686 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1687 if let Ok(mut borrow) = slot.try_borrow_mut()
1688 && let Some((app, _)) = borrow.as_mut()
1689 {
1690 let wid: WindowId = app.get_window_state().get_id();
1691 app.dispatch_window_event(WindowEvent::PointerCancel(wid, pointer_id));
1692 queued = true;
1693 }
1694 });
1695 if queued {
1696 web_mark_needs_frame();
1697 }
1698}
1699
1700#[cfg(target_arch = "wasm32")]
1709fn web_queue_scroll_at(x: f32, y: f32, dx: f32, dy: f32) {
1710 web_ensure_visible_foreground();
1711 let mut queued: bool = false;
1712 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1713 if let Ok(mut borrow) = slot.try_borrow_mut()
1714 && let Some((app, _)) = borrow.as_mut()
1715 {
1716 let wid: WindowId = app.get_window_state().get_id();
1717 app.dispatch_window_event(WindowEvent::PointerMove(wid, PointerEvent::mouse(x, y)));
1718 app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(dx, dy)));
1719 queued = true;
1720 }
1721 });
1722 if queued {
1723 web_mark_needs_frame();
1724 }
1725}
1726
1727#[cfg(target_arch = "wasm32")]
1736fn web_queue_key_down(key: &str, code_str: &str, mods: Modifiers, repeat: bool) {
1737 if WEB_IME_COMPOSING.with(Cell::get) {
1738 return;
1739 }
1740 web_ensure_visible_foreground();
1741 let ime_active: bool = WEB_IME_ACTIVE.with(Cell::get);
1742 let mut queued: bool = false;
1743 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1744 if let Ok(mut borrow) = slot.try_borrow_mut()
1745 && let Some((app, _)) = borrow.as_mut()
1746 {
1747 let wid: WindowId = app.get_window_state().get_id();
1748 let code: KeyCode = web_map_key(key, code_str);
1749 let key_ev: WindowEvent = WindowEvent::KeyDown(wid, KeyEvent::new(code, mods, repeat));
1750 app.dispatch_window_event(key_ev);
1751 if web_should_dispatch_text_input(ime_active, mods, key) {
1752 app.dispatch_window_event(WindowEvent::TextInput(wid, key.to_string()));
1753 }
1754 queued = true;
1755 }
1756 });
1757 if queued {
1758 web_mark_needs_frame();
1759 }
1760}
1761
1762#[cfg(target_arch = "wasm32")]
1768fn web_queue_text_input(text: String) {
1769 if text.is_empty() {
1770 return;
1771 }
1772 let mut queued: bool = false;
1773 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1774 if let Ok(mut borrow) = slot.try_borrow_mut()
1775 && let Some((app, _)) = borrow.as_mut()
1776 {
1777 let wid: WindowId = app.get_window_state().get_id();
1778 app.dispatch_window_event(WindowEvent::TextInput(wid, text));
1779 queued = true;
1780 }
1781 });
1782 if queued {
1783 web_mark_needs_frame();
1784 }
1785}
1786
1787#[cfg(target_arch = "wasm32")]
1793fn web_flush_ime_element(el: &HtmlElement) {
1794 let key: JsValue = JsValue::from_str(WEB_PROP_VALUE);
1795 if let Ok(val) = Reflect::get(el.as_ref(), &key)
1796 && let Some(text) = val.as_string()
1797 && !text.is_empty()
1798 {
1799 let _: Result<bool, JsValue> = Reflect::set(el.as_ref(), &key, &JsValue::from_str(""));
1800 web_queue_text_input(text);
1801 }
1802}
1803
1804#[cfg(target_arch = "wasm32")]
1810fn web_attach_ime_proxy(doc: &Document) {
1811 let Ok(raw_el) = doc.create_element(WEB_IME_INPUT_TAG) else {
1812 return;
1813 };
1814 let el: Element = raw_el;
1815 drop(el.set_attribute(WEB_IME_ATTR_ID, WEB_IME_INPUT_ID));
1816 drop(el.set_attribute(WEB_IME_ATTR_TYPE, WEB_IME_ATTR_TEXT));
1817 drop(el.set_attribute(WEB_IME_ATTR_AUTOCOMPLETE, WEB_IME_ATTR_OFF));
1818 drop(el.set_attribute(WEB_IME_ATTR_AUTOCORRECT, WEB_IME_ATTR_OFF));
1819 drop(el.set_attribute(WEB_IME_ATTR_AUTOCAPITALIZE, WEB_IME_ATTR_OFF));
1820 drop(el.set_attribute(WEB_IME_ATTR_SPELLCHECK, WEB_IME_ATTR_FALSE));
1821 drop(el.set_attribute(WEB_IME_ATTR_ARIA_LABEL, WEB_IME_ARIA_LABEL));
1822 drop(el.set_attribute(WEB_IME_ATTR_STYLE, WEB_IME_STYLE));
1823 let Ok(html_el) = el.dyn_into::<HtmlElement>() else {
1824 return;
1825 };
1826 if let Some(body) = doc.body() {
1827 drop(body.append_child(&html_el));
1828 }
1829 let comp_start: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1830 WEB_IME_COMPOSING.with(|c: &Cell<bool>| c.set(true));
1831 }) as Box<dyn FnMut(Event)>);
1832 drop(html_el.add_event_listener_with_callback(
1833 WEB_EVENT_COMPOSITION_START,
1834 comp_start.as_ref().unchecked_ref(),
1835 ));
1836 comp_start.forget();
1837 let comp_el: HtmlElement = html_el.clone();
1838 let comp_end: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1839 WEB_IME_COMPOSING.with(|c: &Cell<bool>| c.set(false));
1840 web_flush_ime_element(&comp_el);
1841 }) as Box<dyn FnMut(Event)>);
1842 drop(html_el.add_event_listener_with_callback(
1843 WEB_EVENT_COMPOSITION_END,
1844 comp_end.as_ref().unchecked_ref(),
1845 ));
1846 comp_end.forget();
1847 let inp_el: HtmlElement = html_el.clone();
1848 let on_input: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1849 if !WEB_IME_COMPOSING.with(Cell::get) {
1850 web_flush_ime_element(&inp_el);
1851 }
1852 }) as Box<dyn FnMut(Event)>);
1853 drop(
1854 html_el
1855 .add_event_listener_with_callback(WEB_EVENT_INPUT, on_input.as_ref().unchecked_ref()),
1856 );
1857 on_input.forget();
1858 let on_ime_blur: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1859 WEB_IME_ACTIVE.with(|a: &Cell<bool>| a.set(false));
1860 WEB_IME_COMPOSING.with(|c: &Cell<bool>| c.set(false));
1861 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1862 if let Ok(mut borrow) = slot.try_borrow_mut()
1863 && let Some((app, _)) = borrow.as_mut()
1864 {
1865 let wid: WindowId = app.get_window_state().get_id();
1866 app.dispatch_window_event(WindowEvent::Ime(wid, ImeEvent::Disabled));
1867 }
1868 });
1869 }) as Box<dyn FnMut(Event)>);
1870 drop(
1871 html_el
1872 .add_event_listener_with_callback(WEB_EVENT_BLUR, on_ime_blur.as_ref().unchecked_ref()),
1873 );
1874 on_ime_blur.forget();
1875 WEB_IME_ELEMENT.with(|slot: &RefCell<Option<HtmlElement>>| {
1876 if let Ok(mut guard) = slot.try_borrow_mut() {
1877 *guard = Some(html_el);
1878 }
1879 });
1880}
1881
1882#[cfg(target_arch = "wasm32")]
1894fn web_native_action_bridge(kind: &str, arg1: &str, _arg2: &str) -> bool {
1895 if kind == NATIVE_ACTION_FULLSCREEN {
1896 if arg1 == WEB_FS_ACTION_ON {
1897 web_set_fullscreen(true);
1898 return true;
1899 }
1900 if arg1 == WEB_FS_ACTION_OFF {
1901 web_set_fullscreen(false);
1902 return true;
1903 }
1904 return false;
1905 }
1906 if kind == NATIVE_ACTION_OPEN_URL {
1907 if !is_valid_external_url(arg1) {
1908 return false;
1909 }
1910 let Some(win) = window() else {
1911 return false;
1912 };
1913 return win
1914 .open_with_url_and_target_and_features(
1915 arg1.trim(),
1916 WEB_OPEN_TARGET_BLANK,
1917 WEB_OPEN_FEATURES_SAFE,
1918 )
1919 .is_ok();
1920 }
1921 if kind != NATIVE_ACTION_IME {
1922 return false;
1923 }
1924 WEB_IME_ELEMENT.with(|slot: &RefCell<Option<HtmlElement>>| {
1925 let Ok(guard) = slot.try_borrow() else {
1926 return false;
1927 };
1928 let Some(el) = guard.as_ref() else {
1929 return false;
1930 };
1931 if arg1 == WEB_IME_ACTION_SHOW {
1932 WEB_IME_ACTIVE.with(|a: &Cell<bool>| a.set(true));
1933 if let Some(win) = window()
1934 && let Some(doc) = win.document()
1935 && let Some(active_el) = doc.active_element()
1936 && active_el.id() == WEB_IME_INPUT_ID
1937 {
1938 drop(el.blur());
1939 }
1940 drop(el.focus());
1941 true
1942 } else if arg1 == WEB_IME_ACTION_HIDE {
1943 WEB_IME_ACTIVE.with(|a: &Cell<bool>| a.set(false));
1944 WEB_IME_COMPOSING.with(|c: &Cell<bool>| c.set(false));
1945 let key: JsValue = JsValue::from_str(WEB_PROP_VALUE);
1946 let _: Result<bool, JsValue> = Reflect::set(el.as_ref(), &key, &JsValue::from_str(""));
1947 drop(el.blur());
1948 true
1949 } else {
1950 false
1951 }
1952 })
1953}
1954
1955#[cfg(target_arch = "wasm32")]
1963fn web_queue_key_up(key: &str, code_str: &str, mods: Modifiers) {
1964 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1965 if let Ok(mut borrow) = slot.try_borrow_mut()
1966 && let Some((app, _)) = borrow.as_mut()
1967 {
1968 let wid: WindowId = app.get_window_state().get_id();
1969 let code: KeyCode = web_map_key(key, code_str);
1970 app.dispatch_window_event(WindowEvent::KeyUp(wid, KeyEvent::new(code, mods, false)));
1971 }
1972 });
1973}
1974
1975#[cfg(target_arch = "wasm32")]
1985fn web_read_window_css_viewport(win: &Window) -> (f64, f64) {
1986 if let Ok(vv) = Reflect::get(win.as_ref(), &JsValue::from_str(WEB_PROP_VISUAL_VIEWPORT))
1987 && !vv.is_null()
1988 && !vv.is_undefined()
1989 {
1990 let vw: Option<f64> = Reflect::get(&vv, &JsValue::from_str(WEB_PROP_WIDTH))
1991 .ok()
1992 .and_then(|v: JsValue| v.as_f64())
1993 .filter(|v: &f64| v.is_finite() && *v >= 64.0);
1994 let vh: Option<f64> = Reflect::get(&vv, &JsValue::from_str(WEB_PROP_HEIGHT))
1995 .ok()
1996 .and_then(|v: JsValue| v.as_f64())
1997 .filter(|v: &f64| v.is_finite() && *v >= 64.0);
1998 if let (Some(w), Some(h)) = (vw, vh) {
1999 return (w, h);
2000 }
2001 }
2002 if let Some(root) = win
2003 .document()
2004 .and_then(|doc: Document| doc.document_element())
2005 {
2006 let cw: f64 = f64::from(root.client_width());
2007 let ch: f64 = f64::from(root.client_height());
2008 if cw >= 64.0 && ch >= 64.0 {
2009 return (cw, ch);
2010 }
2011 }
2012 let w: f64 = win
2013 .inner_width()
2014 .ok()
2015 .and_then(|v: JsValue| v.as_f64())
2016 .filter(|w: &f64| w.is_finite() && *w >= 64.0)
2017 .unwrap_or(SHOWCASE_WINDOW_WIDTH as f64);
2018 let h: f64 = win
2019 .inner_height()
2020 .ok()
2021 .and_then(|v: JsValue| v.as_f64())
2022 .filter(|h: &f64| h.is_finite() && *h >= 64.0)
2023 .unwrap_or(SHOWCASE_WINDOW_HEIGHT as f64);
2024 (w, h)
2025}
2026
2027#[cfg(target_arch = "wasm32")]
2033fn web_query_initial_viewport() -> (f64, f64, f64, f64, f32) {
2034 let Some(win) = window() else {
2035 return (
2036 0.0,
2037 0.0,
2038 SHOWCASE_WINDOW_WIDTH as f64,
2039 SHOWCASE_WINDOW_HEIGHT as f64,
2040 1.0,
2041 );
2042 };
2043 let dpr_raw: f64 = win.device_pixel_ratio();
2044 let dpr: f32 = if dpr_raw.is_finite() && dpr_raw > 0.0 {
2045 dpr_raw.clamp(1.0, 4.5) as f32
2046 } else {
2047 1.0
2048 };
2049 let mut left: f64 = 0.0;
2050 let mut top: f64 = 0.0;
2051 let mut css_w: f64 = 0.0;
2052 let mut css_h: f64 = 0.0;
2053 if let Some(doc) = win.document()
2054 && let Ok(Some(el)) = doc.query_selector(WEB_SELECTOR_CANVAS)
2055 && let Ok(canvas) = el.dyn_into::<HtmlCanvasElement>()
2056 {
2057 let rect: DomRect = canvas.get_bounding_client_rect();
2058 left = rect.left();
2059 top = rect.top();
2060 css_w = rect.width();
2061 css_h = rect.height();
2062 }
2063 let (win_w, win_h): (f64, f64) = web_read_window_css_viewport(&win);
2064 if !css_w.is_finite() || css_w < 64.0 {
2065 css_w = win_w;
2066 }
2067 if !css_h.is_finite() || css_h < 64.0 {
2068 css_h = win_h;
2069 }
2070 (left, top, css_w, css_h, dpr)
2071}
2072
2073#[cfg(target_arch = "wasm32")]
2084fn web_refresh_cached_viewport(win: &Window, canvas: &HtmlCanvasElement) -> bool {
2085 let rect: DomRect = canvas.get_bounding_client_rect();
2086 let left: f64 = rect.left();
2087 let top: f64 = rect.top();
2088 let (win_w, win_h): (f64, f64) = web_read_window_css_viewport(win);
2089 let css_w: f64 = if rect.width().is_finite() && rect.width() >= 64.0 {
2090 rect.width()
2091 } else {
2092 win_w
2093 };
2094 let css_h: f64 = if rect.height().is_finite() && rect.height() >= 64.0 {
2095 rect.height()
2096 } else {
2097 win_h
2098 };
2099 let dpr_raw: f64 = win.device_pixel_ratio();
2100 let dpr: f32 = if dpr_raw.is_finite() && dpr_raw > 0.0 {
2101 dpr_raw.clamp(1.0, 4.5) as f32
2102 } else {
2103 1.0
2104 };
2105 let prev: (f64, f64, f64, f64, f32) = WEB_CACHED_VIEWPORT.with(Cell::get);
2106 let changed: bool = (prev.0 - left).abs() > 0.25
2107 || (prev.1 - top).abs() > 0.25
2108 || (prev.2 - css_w).abs() > 0.25
2109 || (prev.3 - css_h).abs() > 0.25
2110 || (prev.4 - dpr).abs() > 0.005;
2111 if changed {
2112 WEB_CACHED_VIEWPORT.with(|cell: &Cell<(f64, f64, f64, f64, f32)>| {
2113 cell.set((left, top, css_w, css_h, dpr));
2114 });
2115 WEB_VIEWPORT_DIRTY.with(|flag: &Cell<bool>| flag.set(true));
2116 }
2117 changed
2118}
2119
2120#[cfg(target_arch = "wasm32")]
2130fn web_apply_cached_viewport(canvas: &HtmlCanvasElement) -> bool {
2131 let (_, _, css_w, css_h, dpr): (f64, f64, f64, f64, f32) = WEB_CACHED_VIEWPORT.with(Cell::get);
2132 let dpr_f64: f64 = f64::from(dpr);
2133 let phys_w: u32 = (css_w * dpr_f64).round().max(1.0) as u32;
2134 let phys_h: u32 = (css_h * dpr_f64).round().max(1.0) as u32;
2135 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2136 let Ok(mut borrow) = slot.try_borrow_mut() else {
2137 return false;
2138 };
2139 let Some((app, _)) = borrow.as_mut() else {
2140 return false;
2141 };
2142 let ws: WindowState = app.get_window_state();
2143 let size_diff: bool = ws.get_physical_width() != phys_w
2144 || ws.get_physical_height() != phys_h
2145 || (ws.get_scale_factor() - dpr).abs() > 0.005
2146 || canvas.width() != phys_w
2147 || canvas.height() != phys_h;
2148 if !size_diff {
2149 return false;
2150 }
2151 if canvas.width() != phys_w {
2152 canvas.set_width(phys_w);
2153 }
2154 if canvas.height() != phys_h {
2155 canvas.set_height(phys_h);
2156 }
2157 app.set_exact_physical_viewport(phys_w, phys_h, dpr);
2158 true
2159 })
2160}
2161
2162#[cfg(target_arch = "wasm32")]
2168fn web_sync_safe_area() -> bool {
2169 let measured: SafeAreaInsets = web_query_safe_area_insets();
2170 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2171 let Ok(mut borrow) = slot.try_borrow_mut() else {
2172 return false;
2173 };
2174 let Some((app, _)) = borrow.as_mut() else {
2175 return false;
2176 };
2177 let effective: SafeAreaInsets = if app.is_immersive_fullscreen() {
2178 SafeAreaInsets::default()
2179 } else {
2180 measured
2181 };
2182 let current: SafeAreaInsets = app.get_context().get_safe_area().get_untracked();
2183 if current == effective {
2184 return false;
2185 }
2186 let wid: WindowId = app.get_window_state().get_id();
2187 app.dispatch_window_event(WindowEvent::SafeAreaChanged(wid, effective));
2188 true
2189 })
2190}
2191
2192#[cfg(target_arch = "wasm32")]
2198fn web_report_host_refresh_rate(measured_hz: f32) {
2199 let mut needs_redraw: bool = false;
2200 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2201 if let Ok(mut borrow) = slot.try_borrow_mut()
2202 && let Some((app, _)) = borrow.as_mut()
2203 {
2204 let prev_fps: f32 = app.get_context().get_live_fps().get_untracked();
2205 app.report_host_refresh_rate(measured_hz);
2206 let next_fps: f32 = app.get_context().get_live_fps().get_untracked();
2207 if (next_fps - prev_fps).abs() >= 1.0 {
2208 needs_redraw = true;
2209 }
2210 }
2211 });
2212 if needs_redraw {
2213 web_mark_needs_frame();
2214 }
2215}
2216
2217#[cfg(target_arch = "wasm32")]
2227fn web_flush_frame(dt_secs: f32) -> u64 {
2228 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2229 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2230 Ok(guard) => guard,
2231 Err(_) => return 0,
2232 };
2233 let Some((app, state)) = borrow.as_mut() else {
2234 return 0;
2235 };
2236 let coord: ShowcaseWebDualCanvasCoordinator = web_dual_canvas_snapshot();
2237 state.sync_adaptive_from_web_coordinator(app, &coord);
2238 let hash: u64 = app
2239 .step_game_frame(dt_secs)
2240 .map(|stats: FrameStats| stats.get_frame_hash())
2241 .unwrap_or(0);
2242 state.sync_adaptive_from_web_coordinator(app, &coord);
2243 let pump: bool = app.should_pump_frames();
2244 WEB_SHOULD_PUMP.with(|flag: &Cell<bool>| flag.set(pump));
2245 hash
2246 })
2247}
2248
2249#[cfg(target_arch = "wasm32")]
2255#[wasm_bindgen]
2256pub fn euv_example_web_start() -> u64 {
2257 reset_reactive_runtime();
2258 register_frame_wakeup(web_mark_needs_frame);
2259 let (left, top, css_w, css_h, dpr): (f64, f64, f64, f64, f32) = web_query_initial_viewport();
2260 WEB_CACHED_VIEWPORT.with(|cell: &Cell<(f64, f64, f64, f64, f32)>| {
2261 cell.set((left, top, css_w, css_h, dpr));
2262 });
2263 WEB_VIEWPORT_DIRTY.with(|flag: &Cell<bool>| flag.set(false));
2264 let logical_w: u32 = css_w.round().max(64.0) as u32;
2265 let logical_h: u32 = css_h.round().max(64.0) as u32;
2266 let phys_w: u32 = (css_w * f64::from(dpr)).round().max(1.0) as u32;
2267 let phys_h: u32 = (css_h * f64::from(dpr)).round().max(1.0) as u32;
2268 if let Some(win) = window()
2269 && let Some(doc) = win.document()
2270 && let Ok(Some(el)) = doc.query_selector(WEB_SELECTOR_CANVAS)
2271 && let Ok(canvas) = el.dyn_into::<HtmlCanvasElement>()
2272 {
2273 if canvas.width() != phys_w {
2274 canvas.set_width(phys_w);
2275 }
2276 if canvas.height() != phys_h {
2277 canvas.set_height(phys_h);
2278 }
2279 }
2280 match create_showcase_app_with_viewport(false, RenderMode::Auto, logical_w, logical_h, dpr) {
2281 Ok((mut app, state)) => {
2282 app.set_exact_physical_viewport(phys_w, phys_h, dpr);
2283 if let Some(win) = window()
2284 && let Ok(hash_str) = win.location().hash()
2285 {
2286 let initial: String =
2287 resolve_web_hash_route(&hash_str, Some(state.get_dynamic_hub()));
2288 let _: bool = state.get_route().set_if_changed(initial);
2289 }
2290 let route_watch: Signal<String> = state.get_route();
2291 let hub_watch: DynamicUpdateHub = state.get_dynamic_hub().clone();
2292 let (hash_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
2293 Effect::new(move || {
2294 let r: String = route_watch.get();
2295 if WEB_SYNCING_FROM_HISTORY.with(Cell::get) {
2296 return;
2297 }
2298 if let Some(win) = window() {
2299 let cur_raw: String = win.location().hash().unwrap_or_default();
2300 let cur_norm: String = resolve_web_hash_route(&cur_raw, Some(&hub_watch));
2301 if cur_norm != r {
2302 let target_hash: String = format!("#{r}");
2303 let _: Result<(), JsValue> = win.location().set_hash(&target_hash);
2304 }
2305 }
2306 })
2307 });
2308 let root_id: NodeId = app
2309 .get_scene()
2310 .with_read(SceneTree::get_root, NodeId::default());
2311 app.get_scene().with_write(
2312 |tree: &mut SceneTree| {
2313 tree.attach_scope(root_id, hash_scope);
2314 },
2315 (),
2316 );
2317 let hash: u64 = app
2318 .step_frame()
2319 .map(|stats: FrameStats| stats.get_frame_hash())
2320 .unwrap_or(0);
2321 let coord: ShowcaseWebDualCanvasCoordinator = web_dual_canvas_snapshot();
2322 state.sync_adaptive_from_web_coordinator(&mut app, &coord);
2323 let pump: bool = app.should_pump_frames();
2324 WEB_SHOULD_PUMP.with(|flag: &Cell<bool>| flag.set(pump));
2325 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2326 if let Ok(mut borrow) = slot.try_borrow_mut() {
2327 *borrow = Some((app, state));
2328 }
2329 });
2330 hash
2331 }
2332 Err(_) => 0,
2333 }
2334}
2335
2336#[cfg(target_arch = "wasm32")]
2346#[wasm_bindgen]
2347pub fn euv_example_render_route(route: &str) -> u64 {
2348 let has_runtime: bool = WEB_SHOWCASE_RUNTIME.with(
2349 |slot: &RefCell<Option<(App, ShowcaseState)>>| matches!(slot.try_borrow(), Ok(guard) if guard.is_some()),
2350 );
2351 if !has_runtime {
2352 let _: u64 = euv_example_web_start();
2353 }
2354 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2355 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2356 Ok(guard) => guard,
2357 Err(_) => return 0,
2358 };
2359 let Some((app, state)) = borrow.as_mut() else {
2360 return 0;
2361 };
2362 let _: bool = state.get_route().set_if_changed(route.to_string());
2363 app.step_frame()
2364 .map(|stats: FrameStats| stats.get_frame_hash())
2365 .unwrap_or(0)
2366 })
2367}
2368
2369#[cfg(target_arch = "wasm32")]
2380#[wasm_bindgen]
2381pub fn euv_web_pointer_move(x: f32, y: f32) -> u64 {
2382 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2383 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2384 Ok(guard) => guard,
2385 Err(_) => return 0,
2386 };
2387 let Some((app, _)) = borrow.as_mut() else {
2388 return 0;
2389 };
2390 let wid: WindowId = app.get_window_state().get_id();
2391 app.dispatch_window_event(WindowEvent::PointerMove(wid, PointerEvent::mouse(x, y)));
2392 app.step_frame()
2393 .map(|stats: FrameStats| stats.get_frame_hash())
2394 .unwrap_or(0)
2395 })
2396}
2397
2398#[cfg(target_arch = "wasm32")]
2409#[wasm_bindgen]
2410pub fn euv_web_pointer_down(x: f32, y: f32) -> u64 {
2411 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2412 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2413 Ok(guard) => guard,
2414 Err(_) => return 0,
2415 };
2416 let Some((app, _)) = borrow.as_mut() else {
2417 return 0;
2418 };
2419 let wid: WindowId = app.get_window_state().get_id();
2420 app.dispatch_window_event(WindowEvent::PointerDown(wid, PointerEvent::mouse(x, y)));
2421 app.step_frame()
2422 .map(|stats: FrameStats| stats.get_frame_hash())
2423 .unwrap_or(0)
2424 })
2425}
2426
2427#[cfg(target_arch = "wasm32")]
2438#[wasm_bindgen]
2439pub fn euv_web_pointer_up(x: f32, y: f32) -> u64 {
2440 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2441 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2442 Ok(guard) => guard,
2443 Err(_) => return 0,
2444 };
2445 let Some((app, _)) = borrow.as_mut() else {
2446 return 0;
2447 };
2448 let wid: WindowId = app.get_window_state().get_id();
2449 app.dispatch_window_event(WindowEvent::PointerUp(wid, PointerEvent::mouse(x, y)));
2450 app.step_frame()
2451 .map(|stats: FrameStats| stats.get_frame_hash())
2452 .unwrap_or(0)
2453 })
2454}
2455
2456#[cfg(target_arch = "wasm32")]
2467#[wasm_bindgen]
2468pub fn euv_web_scroll(dx: f32, dy: f32) -> u64 {
2469 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2470 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2471 Ok(guard) => guard,
2472 Err(_) => return 0,
2473 };
2474 let Some((app, _)) = borrow.as_mut() else {
2475 return 0;
2476 };
2477 let wid: WindowId = app.get_window_state().get_id();
2478 app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(dx, dy)));
2479 app.step_frame()
2480 .map(|stats: FrameStats| stats.get_frame_hash())
2481 .unwrap_or(0)
2482 })
2483}
2484
2485#[cfg(target_arch = "wasm32")]
2495#[wasm_bindgen]
2496pub fn euv_web_key_down(key: &str) -> u64 {
2497 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2498 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2499 Ok(guard) => guard,
2500 Err(_) => return 0,
2501 };
2502 let Some((app, state)) = borrow.as_mut() else {
2503 return 0;
2504 };
2505 let wid: WindowId = app.get_window_state().get_id();
2506 let code: KeyCode = match key {
2507 WEB_KEY_ENTER => KeyCode::Enter,
2508 WEB_KEY_BACKSPACE => KeyCode::Backspace,
2509 WEB_KEY_DELETE => KeyCode::Delete,
2510 WEB_KEY_ESCAPE => KeyCode::Escape,
2511 WEB_KEY_TAB => KeyCode::Tab,
2512 WEB_KEY_SPACE => KeyCode::Space,
2513 WEB_KEY_ARROW_LEFT => KeyCode::ArrowLeft,
2514 WEB_KEY_ARROW_RIGHT => KeyCode::ArrowRight,
2515 WEB_KEY_ARROW_UP => KeyCode::ArrowUp,
2516 WEB_KEY_ARROW_DOWN => KeyCode::ArrowDown,
2517 other => other
2518 .chars()
2519 .next()
2520 .map(KeyCode::Character)
2521 .unwrap_or(KeyCode::Unknown),
2522 };
2523 let key_ev: WindowEvent =
2524 WindowEvent::KeyDown(wid, KeyEvent::new(code, Modifiers::default(), false));
2525 state.get_game_host().ingest_event(&key_ev);
2526 app.dispatch_window_event(key_ev);
2527 if key.chars().count() == 1 {
2528 app.dispatch_window_event(WindowEvent::TextInput(wid, key.to_string()));
2529 }
2530 app.step_frame()
2531 .map(|stats: FrameStats| stats.get_frame_hash())
2532 .unwrap_or(0)
2533 })
2534}
2535
2536#[cfg(target_arch = "wasm32")]
2546#[wasm_bindgen]
2547pub fn euv_web_tick(dt_secs: f32) -> u64 {
2548 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2549 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2550 Ok(guard) => guard,
2551 Err(_) => return 0,
2552 };
2553 let Some((app, state)) = borrow.as_mut() else {
2554 return 0;
2555 };
2556 if !app.should_pump_frames() {
2557 return app.get_renderer().get_last_stats().get_frame_hash();
2558 }
2559 let cur_route: String = state.get_route().get_untracked();
2560 let on_game: bool =
2561 cur_route == ROUTE_GAME || cur_route == ROUTE_GAME_3D || cur_route == ROUTE_WATER;
2562 if on_game || app.has_active_animations() {
2563 return app
2564 .step_game_frame(dt_secs)
2565 .map(|stats: FrameStats| stats.get_frame_hash())
2566 .unwrap_or(0);
2567 }
2568 app.get_renderer().get_last_stats().get_frame_hash()
2569 })
2570}
2571
2572#[cfg(target_arch = "wasm32")]
2584#[wasm_bindgen]
2585pub fn euv_web_resize(width: u32, height: u32, dpr: f32) -> u64 {
2586 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2587 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2588 Ok(guard) => guard,
2589 Err(_) => return 0,
2590 };
2591 let Some((app, _)) = borrow.as_mut() else {
2592 return 0;
2593 };
2594 let w: u32 = width.max(64);
2595 let h: u32 = height.max(64);
2596 let scale: f32 = if dpr.is_finite() && dpr > 0.0 {
2597 dpr.clamp(1.0, 4.5)
2598 } else {
2599 1.0
2600 };
2601 let phys_w: u32 = ((w as f64) * (scale as f64)).round().max(1.0) as u32;
2602 let phys_h: u32 = ((h as f64) * (scale as f64)).round().max(1.0) as u32;
2603 let (prev_l, prev_t, _, _, _): (f64, f64, f64, f64, f32) =
2604 WEB_CACHED_VIEWPORT.with(Cell::get);
2605 WEB_CACHED_VIEWPORT.with(|cell: &Cell<(f64, f64, f64, f64, f32)>| {
2606 cell.set((prev_l, prev_t, f64::from(w), f64::from(h), scale));
2607 });
2608 WEB_VIEWPORT_DIRTY.with(|flag: &Cell<bool>| flag.set(false));
2609 if let Some(win) = window()
2610 && let Some(doc) = win.document()
2611 && let Ok(Some(el)) = doc.query_selector(WEB_SELECTOR_CANVAS)
2612 && let Ok(canvas) = el.dyn_into::<HtmlCanvasElement>()
2613 {
2614 if canvas.width() != phys_w {
2615 canvas.set_width(phys_w);
2616 }
2617 if canvas.height() != phys_h {
2618 canvas.set_height(phys_h);
2619 }
2620 }
2621 app.set_exact_physical_viewport(phys_w, phys_h, scale);
2622 app.step_frame()
2623 .map(|stats: FrameStats| stats.get_frame_hash())
2624 .unwrap_or(0)
2625 })
2626}
2627
2628#[cfg(all(debug_assertions, target_arch = "wasm32"))]
2638#[wasm_bindgen]
2639pub fn euv_dev_ai_schema(request_json: &str) -> String {
2640 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2641 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2642 Ok(guard) => guard,
2643 Err(_) => return String::new(),
2644 };
2645 let Some((app, state)) = borrow.as_mut() else {
2646 return String::new();
2647 };
2648 let hooks: AiAppHooks = state.build_ai_hooks();
2649 AiSchemaProtocol::handle_json_with_hooks(app, request_json, Some(&hooks))
2650 })
2651}
2652
2653#[cfg(target_arch = "wasm32")]
2659#[wasm_bindgen]
2660pub fn euv_web_current_route() -> String {
2661 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2662 match slot.try_borrow() {
2663 Ok(guard) => guard
2664 .as_ref()
2665 .map(|(_, state): &(App, ShowcaseState)| state.get_route().get_untracked())
2666 .unwrap_or_default(),
2667 Err(_) => String::new(),
2668 }
2669 })
2670}