Skip to main content

euv_example/app/
fn.rs

1use super::*;
2
3/// Builds the default highest-performance `RenderConfig` for `mode` (hardware-first, dirty rects enabled, uncapped refresh).
4///
5/// # Arguments
6///
7/// - `RenderMode` - Requested pipeline mode.
8/// - `bool` - When `true`, enables zero-readback GPU direct-draw on explicit `RenderMode::Hardware`.
9///
10/// # Returns
11///
12/// - `RenderConfig` - Maximum-performance rendering configuration.
13#[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
29/// Builds an `App` and reactive `ShowcaseState` using the default max-performance configuration (`RenderMode::Auto`).
30///
31/// # Arguments
32///
33/// - `bool` - When `true`, uses deterministic `HeadlessPlatform`; otherwise uses the active native OS backend.
34///
35/// # Returns
36///
37/// - `Result<(App, ShowcaseState), PlatformError>` - Initialized showcase app and state.
38pub fn create_showcase_app_default(headless: bool) -> Result<(App, ShowcaseState), PlatformError> {
39    create_showcase_app(headless, RenderMode::Auto)
40}
41
42/// Maps an active `PlatformKind` to its selector index in the `/window` platform matrix.
43///
44/// # Arguments
45///
46/// - `PlatformKind` - Active host platform kind.
47///
48/// # Returns
49///
50/// - `usize` - Index in `0..7`.
51fn 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
66/// Builds an `App` and reactive `ShowcaseState` configured with explicit initial logical viewport dimensions and DPR scale.
67///
68/// # Arguments
69///
70/// - `bool` - When `true`, uses deterministic `HeadlessPlatform`; otherwise uses the active native OS backend.
71/// - `RenderMode` - Initial rendering pipeline mode.
72/// - `u32` - Initial logical viewport width in pixels.
73/// - `u32` - Initial logical viewport height in pixels.
74/// - `f32` - Initial device pixel ratio (`>= 0.5`).
75///
76/// # Returns
77///
78/// - `Result<(App, ShowcaseState), PlatformError>` - Initialized showcase app and state.
79pub 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    if !headless {
127        bootstrap_showcase_hot_updates(state.get_dynamic_hub());
128    }
129    Ok((app, state))
130}
131
132/// Builds an `App` and reactive `ShowcaseState` configured for either native OS or headless mode.
133///
134/// # Arguments
135///
136/// - `bool` - When `true`, uses deterministic `HeadlessPlatform`; otherwise uses the active native OS backend.
137/// - `RenderMode` - Initial rendering pipeline mode.
138///
139/// # Returns
140///
141/// - `Result<(App, ShowcaseState), PlatformError>` - Initialized showcase app and state.
142pub fn create_showcase_app(
143    headless: bool,
144    mode: RenderMode,
145) -> Result<(App, ShowcaseState), PlatformError> {
146    create_showcase_app_with_viewport(
147        headless,
148        mode,
149        SHOWCASE_WINDOW_WIDTH,
150        SHOWCASE_WINDOW_HEIGHT,
151        1.0,
152    )
153}
154
155/// Builds an `App` and reactive `ShowcaseState` reporting a specific host `PlatformKind` (for native mobile hosts).
156///
157/// # Arguments
158///
159/// - `PlatformKind` - Active native host platform identity (e.g. `PlatformKind::Android`, `PlatformKind::Ios`).
160/// - `RenderMode` - Initial rendering pipeline mode.
161///
162/// # Returns
163///
164/// - `Result<(App, ShowcaseState), PlatformError>` - Initialized showcase app and state.
165pub fn create_showcase_app_for_platform(
166    platform: PlatformKind,
167    mode: RenderMode,
168) -> Result<(App, ShowcaseState), PlatformError> {
169    create_showcase_app_for_platform_with_viewport(
170        platform,
171        mode,
172        SHOWCASE_WINDOW_WIDTH,
173        SHOWCASE_WINDOW_HEIGHT,
174        1.0,
175        SafeAreaInsets::default(),
176    )
177}
178
179/// Builds an `App` and reactive `ShowcaseState` reporting a specific host `PlatformKind` with explicit logical viewport, DPR, and safe-area insets.
180///
181/// Supports compact smartwatch viewports down to `120x120` logical dp without enforcing desktop/mobile 320px clamping.
182///
183/// # Arguments
184///
185/// - `PlatformKind` - Active host platform identity (`MiniApp`, `QuickApp`, `Wearable`, `HarmonyOs`, `Android`, `Ios`, etc.).
186/// - `RenderMode` - Initial rendering pipeline mode.
187/// - `u32` - Initial logical viewport width in dp.
188/// - `u32` - Initial logical viewport height in dp.
189/// - `f32` - Display pixel ratio (`>= 0.5`).
190/// - `SafeAreaInsets` - Initial host safe-area / capsule / round-dial insets.
191///
192/// # Returns
193///
194/// - `Result<(App, ShowcaseState), PlatformError>` - Initialized showcase app and state.
195pub fn create_showcase_app_for_platform_with_viewport(
196    platform: PlatformKind,
197    mode: RenderMode,
198    logical_width: u32,
199    logical_height: u32,
200    initial_scale: f32,
201    safe_area: SafeAreaInsets,
202) -> Result<(App, ShowcaseState), PlatformError> {
203    EuvOverlayStack::clear();
204    reset_fullscreen_state();
205    clear_provided_theme();
206    let init_w: u32 = logical_width.max(HOST_MIN_VIEWPORT_DIM);
207    let init_h: u32 = logical_height.max(HOST_MIN_VIEWPORT_DIM);
208    let init_scale: f32 = if initial_scale.is_finite() && initial_scale > 0.0 {
209        initial_scale.clamp(0.5, 6.0)
210    } else {
211        1.0
212    };
213    let render_cfg: RenderConfig = default_showcase_render_config(mode, false);
214    let mut window_cfg: WindowConfig = WindowConfig::default();
215    window_cfg
216        .set_title(SHOWCASE_WINDOW_TITLE.to_string())
217        .set_size(init_w, init_h)
218        .set_render(render_cfg)
219        .set_icon(Some(euv_brand_logo_image()));
220    let mut app_cfg: AppConfig = AppConfig::default();
221    app_cfg.set_window(window_cfg);
222    let backend: Box<dyn PlatformBackend> =
223        Box::new(HeadlessPlatform::emulating(platform, init_scale, safe_area));
224    let mut app: App = App::with_platform(app_cfg, backend)?;
225    let phys_w: u32 = ((init_w as f64) * (init_scale as f64)).round().max(1.0) as u32;
226    let phys_h: u32 = ((init_h as f64) * (init_scale as f64)).round().max(1.0) as u32;
227    app.set_exact_physical_viewport(phys_w, phys_h, init_scale);
228    let wid: WindowId = app.get_window_state().get_id();
229    app.dispatch_window_event(WindowEvent::SafeAreaChanged(wid, safe_area));
230    app.dispatch_window_event(WindowEvent::System(SystemEvent::SafeAreaChanged(safe_area)));
231    let state: ShowcaseState = ShowcaseState::new_with_hub(app.get_dynamic_hub().clone(), false);
232    state.set_default_host_platform_idx(host_platform_matrix_index(app.platform_kind()));
233    app.attach_game_host(state.get_game_host().clone());
234    app.attach_game_host(state.get_game3d_host().clone());
235    app.attach_game_host(state.get_water_host().clone());
236    let mount_state: ShowcaseState = state.clone();
237    let _: NodeId = app.mount(move || mount_showcase_root(&mount_state));
238    state.sync_adaptive_from_app(&mut app);
239    if matches!(platform, PlatformKind::Ios)
240        || matches!(platform, PlatformKind::IpadOs)
241        || matches!(platform, PlatformKind::Android)
242        || matches!(platform, PlatformKind::MacOs)
243        || matches!(platform, PlatformKind::Windows)
244        || matches!(platform, PlatformKind::Linux)
245    {
246        bootstrap_showcase_hot_updates(state.get_dynamic_hub());
247    }
248    Ok((app, state))
249}
250
251/// Runs a complete headless smoke render of the showcase and returns frame telemetry.
252///
253/// # Arguments
254///
255/// - `RenderMode` - Rendering pipeline mode to verify.
256///
257/// # Returns
258///
259/// - `Result<FrameStats, PlatformError>` - Rendered frame statistics and deterministic pixel hash.
260pub fn run_headless_smoke(mode: RenderMode) -> Result<FrameStats, PlatformError> {
261    let (mut app, _): (App, ShowcaseState) = create_showcase_app(true, mode)?;
262    app.step_frame()
263}
264
265/// Steps one frame and writes the rendered RGBA framebuffer to `<out_dir>/<name>.rgba`.
266///
267/// # Arguments
268///
269/// - `&mut App` - Active headless application instance.
270/// - `&Path` - Output directory path.
271/// - `&str` - Frame file basename without extension.
272/// - `&mut String` - Manifest accumulator receiving `<name> <width> <height>` lines.
273/// - `&mut usize` - Running captured frame counter.
274///
275/// # Returns
276///
277/// - `Result<(), PlatformError>` - Success or platform/filesystem error.
278#[cfg(not(target_arch = "wasm32"))]
279fn dump_rgba_frame(
280    app: &mut App,
281    out_dir: &Path,
282    name: &str,
283    manifest: &mut String,
284    count: &mut usize,
285) -> Result<(), PlatformError> {
286    let _: FrameStats = app.step_frame()?;
287    for _ in 0..20 {
288        if !app.has_active_animations() {
289            break;
290        }
291        let _: FrameStats = app.step_game_frame(1.0 / 60.0)?;
292    }
293    if let Some(fb) = app.get_renderer().framebuffer() {
294        let file_name: String = format!("{name}.rgba");
295        let file_path: PathBuf = out_dir.join(&file_name);
296        fs::write(&file_path, fb.get_pixels().as_slice())
297            .map_err(|err: Error| PlatformError::SurfaceError(err.to_string()))?;
298        manifest.push_str(&format!("{name} {} {}\n", fb.get_width(), fb.get_height()));
299        *count += 1;
300    }
301    Ok(())
302}
303
304/// Renders all showcase routes, responsive viewports, dark mode, scroll positions, and overlays to raw RGBA files using native system fonts.
305///
306/// # Arguments
307///
308/// - `&Path` - Destination directory for captured `.rgba` frames and `manifest.txt`.
309///
310/// # Returns
311///
312/// - `Result<usize, PlatformError>` - Total number of captured frames.
313#[cfg(not(target_arch = "wasm32"))]
314pub fn capture_showcase_screenshots(out_dir: &Path) -> Result<usize, PlatformError> {
315    reset_reactive_runtime();
316    EuvOverlayStack::clear();
317    reset_fullscreen_state();
318    clear_provided_theme();
319    fs::create_dir_all(out_dir)
320        .map_err(|err: Error| PlatformError::InitializationFailed(err.to_string()))?;
321    let mut window_cfg: WindowConfig = WindowConfig::default();
322    window_cfg
323        .set_title(SHOWCASE_WINDOW_TITLE.to_string())
324        .set_size(1200, 800)
325        .set_render(RenderConfig::software())
326        .set_icon(Some(euv_brand_logo_image()));
327    let mut app_cfg: AppConfig = AppConfig::default();
328    app_cfg.set_window(window_cfg);
329    let backend: Box<dyn PlatformBackend> = Box::new(HeadlessPlatform::emulating(
330        PlatformKind::Headless,
331        2.0,
332        SafeAreaInsets::default(),
333    ));
334    let mut app: App = App::with_platform(app_cfg, backend)?;
335    let state: ShowcaseState = ShowcaseState::new_with_hub(app.get_dynamic_hub().clone(), false);
336    app.attach_game_host(state.get_game_host().clone());
337    app.attach_game_host(state.get_game3d_host().clone());
338    app.attach_game_host(state.get_water_host().clone());
339    let mount_state: ShowcaseState = state.clone();
340    let _: NodeId = app.mount(move || mount_showcase_root(&mount_state));
341    app.get_mut_renderer()
342        .get_mut_software()
343        .set_font_provider(NativeSystemFont::system());
344    let wid: WindowId = app.get_window_state().get_id();
345    let mut manifest: String = String::new();
346    let mut count: usize = 0;
347    app.dispatch_window_event(WindowEvent::Resized(wid, 1200, 800, 2.0));
348    let desktop_routes: [(&str, &str); 12] = [
349        (ROUTE_OVERVIEW, "01_overview_desktop"),
350        (ROUTE_REACTIVE, "02_reactive_desktop"),
351        (ROUTE_RENDER, "03_render_desktop"),
352        (ROUTE_WINDOW, "04_window_desktop"),
353        (ROUTE_FORMS, "05_forms_desktop"),
354        (ROUTE_THEMES, "06_themes_desktop"),
355        (ROUTE_DATA, "07_data_desktop"),
356        (ROUTE_GAME, "08_game_desktop"),
357        (ROUTE_GAME_3D, "08b_game3d_desktop"),
358        (ROUTE_MEDIA, "08c_media_desktop"),
359        (ROUTE_OVERLAYS, "09_overlays_desktop"),
360        (ROUTE_DYNAMIC, "10_dynamic_desktop"),
361    ];
362    for (route, label) in desktop_routes.iter() {
363        let _: bool = state.get_route().set_if_changed((*route).to_string());
364        if *route == ROUTE_OVERVIEW {
365            app.dispatch_window_event(WindowEvent::PointerMove(
366                wid,
367                PointerEvent::mouse(100.0, 108.0),
368            ));
369        }
370        dump_rgba_frame(&mut app, out_dir, label, &mut manifest, &mut count)?;
371    }
372    let _: bool = state.get_route().set_if_changed(ROUTE_FORMS.to_string());
373    let _: FrameStats = app.step_frame()?;
374    app.dispatch_window_event(WindowEvent::PointerMove(
375        wid,
376        PointerEvent::mouse(600.0, 400.0),
377    ));
378    app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(0.0, 420.0)));
379    dump_rgba_frame(
380        &mut app,
381        out_dir,
382        "05b_forms_scrolled",
383        &mut manifest,
384        &mut count,
385    )?;
386    let _: bool = state.get_route().set_if_changed(ROUTE_DATA.to_string());
387    let _: FrameStats = app.step_frame()?;
388    app.dispatch_window_event(WindowEvent::PointerMove(
389        wid,
390        PointerEvent::mouse(600.0, 400.0),
391    ));
392    app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(0.0, 460.0)));
393    dump_rgba_frame(
394        &mut app,
395        out_dir,
396        "07b_data_vlist_scrolled",
397        &mut manifest,
398        &mut count,
399    )?;
400    app.dispatch_window_event(WindowEvent::PointerMove(
401        wid,
402        PointerEvent::mouse(320.0, 120.0),
403    ));
404    app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(0.0, 720.0)));
405    dump_rgba_frame(
406        &mut app,
407        out_dir,
408        "07c_data_bottom",
409        &mut manifest,
410        &mut count,
411    )?;
412    let _: bool = state.get_route().set_if_changed(ROUTE_OVERVIEW.to_string());
413    let _: FrameStats = app.step_frame()?;
414    app.dispatch_window_event(WindowEvent::PointerMove(
415        wid,
416        PointerEvent::mouse(100.0, 108.0),
417    ));
418    dump_rgba_frame(
419        &mut app,
420        out_dir,
421        "01b_overview_hovered",
422        &mut manifest,
423        &mut count,
424    )?;
425    let _: bool = state.get_route().set_if_changed(ROUTE_OVERLAYS.to_string());
426    let _: bool = state.get_modal_open().set_if_changed(true);
427    dump_rgba_frame(
428        &mut app,
429        out_dir,
430        "09b_overlays_modal",
431        &mut manifest,
432        &mut count,
433    )?;
434    let _: bool = state.get_modal_open().set_if_changed(false);
435    let _: bool = state.get_alert_dialog_open().set_if_changed(true);
436    dump_rgba_frame(
437        &mut app,
438        out_dir,
439        "09c_overlays_alert",
440        &mut manifest,
441        &mut count,
442    )?;
443    let _: bool = state.get_alert_dialog_open().set_if_changed(false);
444    let _: bool = state.get_hover_card_open().set_if_changed(true);
445    dump_rgba_frame(
446        &mut app,
447        out_dir,
448        "09d_overlays_hovercard",
449        &mut manifest,
450        &mut count,
451    )?;
452    let _: bool = state.get_hover_card_open().set_if_changed(false);
453    let _: bool = state.get_route().set_if_changed(ROUTE_THEMES.to_string());
454    state.toggle_theme_mode();
455    dump_rgba_frame(
456        &mut app,
457        out_dir,
458        "06b_themes_dark",
459        &mut manifest,
460        &mut count,
461    )?;
462    state.toggle_theme_mode();
463    let _: bool = state.get_route().set_if_changed(ROUTE_OVERVIEW.to_string());
464    app.dispatch_window_event(WindowEvent::Resized(wid, 768, 1024, 2.0));
465    dump_rgba_frame(
466        &mut app,
467        out_dir,
468        "11_overview_tablet",
469        &mut manifest,
470        &mut count,
471    )?;
472    app.dispatch_window_event(WindowEvent::Resized(wid, 390, 844, 2.0));
473    dump_rgba_frame(
474        &mut app,
475        out_dir,
476        "12_overview_mobile",
477        &mut manifest,
478        &mut count,
479    )?;
480    app.dispatch_window_event(WindowEvent::PointerDown(
481        wid,
482        PointerEvent::mouse(350.0, 26.0),
483    ));
484    app.dispatch_window_event(WindowEvent::PointerUp(
485        wid,
486        PointerEvent::mouse(350.0, 26.0),
487    ));
488    dump_rgba_frame(
489        &mut app,
490        out_dir,
491        "12b_mobile_menu_open",
492        &mut manifest,
493        &mut count,
494    )?;
495    app.dispatch_window_event(WindowEvent::PointerDown(
496        wid,
497        PointerEvent::mouse(240.0, 26.0),
498    ));
499    app.dispatch_window_event(WindowEvent::PointerUp(
500        wid,
501        PointerEvent::mouse(240.0, 26.0),
502    ));
503    let _: bool = state.get_route().set_if_changed(ROUTE_FORMS.to_string());
504    dump_rgba_frame(
505        &mut app,
506        out_dir,
507        "13_forms_mobile",
508        &mut manifest,
509        &mut count,
510    )?;
511    fs::write(out_dir.join("manifest.txt"), manifest)
512        .map_err(|err: Error| PlatformError::SurfaceError(err.to_string()))?;
513    Ok(count)
514}
515
516/// Normalizes a raw browser URL hash into a valid showcase route, falling back to `"/"` for unknown routes.
517///
518/// # Arguments
519///
520/// - `&str` - Raw `window.location.hash` string (for example `""`, `"#"`, `"#/charts?x=1"`, or `"#//unknown"`).
521///
522/// # Returns
523///
524/// - `String` - Canonical known showcase route path.
525#[must_use]
526pub fn normalize_web_hash_route(raw_hash: &str) -> String {
527    resolve_web_hash_route(raw_hash, None)
528}
529
530/// Normalizes a raw browser URL hash against both static `SHOWCASE_ROUTES` and optional dynamic `DynamicUpdateHub` routes.
531///
532/// # Arguments
533///
534/// - `&str` - Raw `window.location.hash` string.
535/// - `Option<&DynamicUpdateHub>` - Optional live dynamic hub holding OTA-registered routes.
536///
537/// # Returns
538///
539/// - `String` - Canonical known route path, or `"/"` when the target is empty or unknown.
540#[must_use]
541pub fn resolve_web_hash_route(raw_hash: &str, hub: Option<&DynamicUpdateHub>) -> String {
542    let trimmed: &str = raw_hash.trim().trim_start_matches('#');
543    let without_query: &str = trimmed.split(['?', '#']).next().unwrap_or("").trim();
544    let segments: Vec<&str> = without_query
545        .split('/')
546        .filter(|seg: &&str| !seg.is_empty())
547        .collect();
548    if segments.is_empty() {
549        return ROUTE_OVERVIEW.to_string();
550    }
551    let candidate: String = format!("/{}", segments.join("/"));
552    let is_static: bool = SHOWCASE_ROUTES
553        .iter()
554        .any(|spec: &ShowcaseRouteSpec| spec.get_path() == candidate.as_str());
555    let is_dynamic: bool = hub
556        .map(|h: &DynamicUpdateHub| h.has_dynamic_page(&candidate))
557        .unwrap_or(false);
558    if is_static || is_dynamic {
559        candidate
560    } else {
561        ROUTE_OVERVIEW.to_string()
562    }
563}
564
565/// Applies an incoming browser history route (`popstate` / `hashchange`) to `app` and `state`, dismissing overlays and exiting fullscreen first.
566///
567/// # Arguments
568///
569/// - `&mut App` - Live showcase application instance.
570/// - `&ShowcaseState` - Shared reactive showcase state.
571/// - `&str` - Raw `window.location.hash` string from the browser history entry.
572///
573/// # Returns
574///
575/// - `String` - Normalized route path applied to `state`.
576pub fn apply_showcase_history_route(
577    app: &mut App,
578    state: &ShowcaseState,
579    raw_hash: &str,
580) -> String {
581    let next: String = resolve_web_hash_route(raw_hash, Some(state.get_dynamic_hub()));
582    let _: usize = EuvOverlayStack::dismiss_all();
583    let _: bool = state.get_cmd_palette_open().set_if_changed(false);
584    if app.is_immersive_fullscreen() || is_fullscreen_active() || EuvOverlayStack::has_fullscreen()
585    {
586        let _: usize = sync_external_fullscreen_exit();
587        app.set_immersive_fullscreen(false);
588    }
589    let _: bool = state.get_route().set_if_changed(next.clone());
590    next
591}
592
593/// Returns `true` when a browser `keydown` event belongs to an active IME composition and must not emit raw English text.
594///
595/// # Arguments
596///
597/// - `bool` - DOM `KeyboardEvent.isComposing` flag.
598/// - `&str` - DOM `KeyboardEvent.key` string.
599/// - `u32` - DOM `KeyboardEvent.keyCode` value.
600///
601/// # Returns
602///
603/// - `bool` - `true` when the keystroke is being consumed by an active OS/browser IME.
604#[must_use]
605pub fn web_is_ime_composition_key(is_composing: bool, key: &str, key_code: u32) -> bool {
606    is_composing || key == WEB_KEY_PROCESS || key_code == WEB_KEY_CODE_IME_PROCESS
607}
608
609/// Returns `true` when a browser `keydown` event should also emit a printable `WindowEvent::TextInput`.
610///
611/// # Arguments
612///
613/// - `bool` - Whether the hidden browser IME proxy `<input>` is currently active.
614/// - `Modifiers` - Active keyboard modifiers on the DOM `KeyboardEvent`.
615/// - `&str` - DOM `KeyboardEvent.key` string.
616///
617/// # Returns
618///
619/// - `bool` - `true` only for unmodified printable single-character keys while IME proxy is inactive.
620#[must_use]
621pub fn web_should_dispatch_text_input(ime_active: bool, mods: Modifiers, key: &str) -> bool {
622    !ime_active && !mods.get_ctrl() && !mods.get_meta() && key.chars().count() == 1
623}
624
625/// Automatically boots the WebAssembly showcase and attaches all browser canvas, input, resize, and frame listeners in pure Rust.
626#[cfg(target_arch = "wasm32")]
627#[wasm_bindgen(start)]
628pub fn euv_web_boot() {
629    let external_host_mode: bool =
630        Reflect::get(&global(), &JsValue::from_str(HOST_GLOBAL_MODE_KEY))
631            .ok()
632            .and_then(|val: JsValue| val.as_string())
633            .map(|s: String| !s.is_empty())
634            .unwrap_or(false);
635    if external_host_mode {
636        return;
637    }
638    let Some(win): Option<Window> = window() else {
639        return;
640    };
641    let Some(doc): Option<Document> = win.document() else {
642        return;
643    };
644    let Ok(Some(el)) = doc.query_selector(WEB_SELECTOR_CANVAS) else {
645        return;
646    };
647    let Ok(canvas) = el.dyn_into::<HtmlCanvasElement>() else {
648        return;
649    };
650    let _: u64 = euv_example_web_start();
651    #[cfg(debug_assertions)]
652    web_attach_dev_automation_bridge(&win);
653    web_attach_ime_proxy(&doc);
654    register_native_action_bridge(web_native_action_bridge);
655    register_frame_wakeup(web_mark_needs_frame);
656    let _: bool = web_refresh_cached_viewport(&win, &canvas);
657    let _: bool = web_apply_cached_viewport(&canvas);
658    let on_move: Closure<dyn FnMut(web_sys::PointerEvent)> =
659        Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
660            let ptype: String = ev.pointer_type();
661            if ptype == WEB_PTR_TYPE_TOUCH {
662                WEB_LAST_TOUCH_TS_MS.with(|c: &Cell<f64>| c.set(ev.time_stamp()));
663            } else if ev.buttons() == 0
664                && (ev.time_stamp() - WEB_LAST_TOUCH_TS_MS.with(Cell::get)).abs() < 600.0
665            {
666                return;
667            }
668            let ptr: PointerEvent = web_pointer_from_dom(&ev, None);
669            web_queue_pointer_move_event(ptr);
670        }) as Box<dyn FnMut(web_sys::PointerEvent)>);
671    drop(canvas.add_event_listener_with_callback(
672        WEB_EVENT_POINTER_MOVE,
673        on_move.as_ref().unchecked_ref(),
674    ));
675    on_move.forget();
676    let canvas_down: HtmlCanvasElement = canvas.clone();
677    let on_down: Closure<dyn FnMut(web_sys::PointerEvent)> =
678        Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
679            if ev.pointer_type() == WEB_PTR_TYPE_TOUCH {
680                WEB_LAST_TOUCH_TS_MS.with(|c: &Cell<f64>| c.set(ev.time_stamp()));
681            }
682            drop(canvas_down.set_pointer_capture(ev.pointer_id()));
683            let ptr: PointerEvent = web_pointer_from_dom(&ev, Some(true));
684            web_queue_pointer_down_event(ptr);
685            if !WEB_IME_ACTIVE.with(Cell::get) {
686                drop(canvas_down.focus());
687            }
688        }) as Box<dyn FnMut(web_sys::PointerEvent)>);
689    drop(canvas.add_event_listener_with_callback(
690        WEB_EVENT_POINTER_DOWN,
691        on_down.as_ref().unchecked_ref(),
692    ));
693    on_down.forget();
694    let canvas_up: HtmlCanvasElement = canvas.clone();
695    let on_up: Closure<dyn FnMut(web_sys::PointerEvent)> =
696        Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
697            ev.stop_propagation();
698            if ev.pointer_type() == WEB_PTR_TYPE_TOUCH {
699                WEB_LAST_TOUCH_TS_MS.with(|c: &Cell<f64>| c.set(ev.time_stamp()));
700            }
701            let ptr: PointerEvent = web_pointer_from_dom(&ev, Some(false));
702            web_queue_pointer_up_event(ptr);
703            drop(canvas_up.release_pointer_capture(ev.pointer_id()));
704        }) as Box<dyn FnMut(web_sys::PointerEvent)>);
705    drop(
706        canvas
707            .add_event_listener_with_callback(WEB_EVENT_POINTER_UP, on_up.as_ref().unchecked_ref()),
708    );
709    on_up.forget();
710    let on_cancel: Closure<dyn FnMut(web_sys::PointerEvent)> =
711        Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
712            ev.stop_propagation();
713            web_queue_pointer_cancel(web_pointer_id_from_dom(&ev));
714        }) as Box<dyn FnMut(web_sys::PointerEvent)>);
715    drop(canvas.add_event_listener_with_callback(
716        WEB_EVENT_POINTER_CANCEL,
717        on_cancel.as_ref().unchecked_ref(),
718    ));
719    drop(canvas.add_event_listener_with_callback(
720        WEB_EVENT_LOST_POINTER_CAPTURE,
721        on_cancel.as_ref().unchecked_ref(),
722    ));
723    on_cancel.forget();
724    let on_win_up: Closure<dyn FnMut(web_sys::PointerEvent)> =
725        Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
726            if ev.pointer_type() == WEB_PTR_TYPE_TOUCH {
727                WEB_LAST_TOUCH_TS_MS.with(|c: &Cell<f64>| c.set(ev.time_stamp()));
728            }
729            let ptr: PointerEvent = web_pointer_from_dom(&ev, Some(false));
730            web_queue_pointer_up_event(ptr);
731        }) as Box<dyn FnMut(web_sys::PointerEvent)>);
732    drop(win.add_event_listener_with_callback(
733        WEB_EVENT_POINTER_UP,
734        on_win_up.as_ref().unchecked_ref(),
735    ));
736    on_win_up.forget();
737    let on_win_cancel: Closure<dyn FnMut(web_sys::PointerEvent)> =
738        Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
739            web_queue_pointer_cancel(web_pointer_id_from_dom(&ev));
740        }) as Box<dyn FnMut(web_sys::PointerEvent)>);
741    drop(win.add_event_listener_with_callback(
742        WEB_EVENT_POINTER_CANCEL,
743        on_win_cancel.as_ref().unchecked_ref(),
744    ));
745    on_win_cancel.forget();
746    let on_touch_cancel: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
747        web_queue_pointer_cancel(0);
748    }) as Box<dyn FnMut(Event)>);
749    drop(canvas.add_event_listener_with_callback(
750        WEB_EVENT_TOUCH_CANCEL,
751        on_touch_cancel.as_ref().unchecked_ref(),
752    ));
753    drop(win.add_event_listener_with_callback(
754        WEB_EVENT_TOUCH_CANCEL,
755        on_touch_cancel.as_ref().unchecked_ref(),
756    ));
757    on_touch_cancel.forget();
758    let on_blur: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
759        web_queue_pointer_cancel(0);
760        web_dispatch_system_event(SystemEvent::FocusChanged(false));
761    }) as Box<dyn FnMut(Event)>);
762    drop(win.add_event_listener_with_callback(WEB_EVENT_BLUR, on_blur.as_ref().unchecked_ref()));
763    on_blur.forget();
764    web_attach_system_event_listeners(&win, &doc, &canvas);
765    let on_wheel: Closure<dyn FnMut(WheelEvent)> = Closure::wrap(Box::new(move |ev: WheelEvent| {
766        ev.prevent_default();
767        let (left, top, _, _, _): (f64, f64, f64, f64, f32) = WEB_CACHED_VIEWPORT.with(Cell::get);
768        let x: f32 = (ev.client_x() as f64 - left) as f32;
769        let y: f32 = (ev.client_y() as f64 - top) as f32;
770        let mult: f32 = match ev.delta_mode() {
771            1 => 20.0,
772            2 => 320.0,
773            _ => 1.0,
774        };
775        web_queue_scroll_at(
776            x,
777            y,
778            (ev.delta_x() as f32) * mult,
779            (ev.delta_y() as f32) * mult,
780        );
781    })
782        as Box<dyn FnMut(WheelEvent)>);
783    web_add_non_passive_listener(
784        canvas.as_ref(),
785        WEB_EVENT_WHEEL,
786        on_wheel.as_ref().unchecked_ref(),
787    );
788    on_wheel.forget();
789    let on_key: Closure<dyn FnMut(KeyboardEvent)> =
790        Closure::wrap(Box::new(move |ev: KeyboardEvent| {
791            let key: String = ev.key();
792            if WEB_IME_COMPOSING.with(Cell::get)
793                || web_is_ime_composition_key(ev.is_composing(), &key, ev.key_code())
794            {
795                return;
796            }
797            let code_str: String = ev.code();
798            let mods: Modifiers =
799                Modifiers::new(ev.shift_key(), ev.ctrl_key(), ev.alt_key(), ev.meta_key());
800            let ime_active: bool = WEB_IME_ACTIVE.with(Cell::get);
801            let cmd_or_ctrl: bool = mods.get_ctrl() || mods.get_meta();
802            let is_nav_or_edit_key: bool = matches!(
803                key.as_str(),
804                WEB_KEY_ARROW_UP
805                    | WEB_KEY_ARROW_DOWN
806                    | WEB_KEY_ARROW_LEFT
807                    | WEB_KEY_ARROW_RIGHT
808                    | WEB_KEY_HOME
809                    | WEB_KEY_END
810                    | WEB_KEY_BACKSPACE
811                    | WEB_KEY_DELETE
812            );
813            let should_prevent: bool = if cmd_or_ctrl {
814                matches!(code_str.as_str(), WEB_CODE_KEY_K | WEB_CODE_KEY_A)
815                    || (ime_active && is_nav_or_edit_key)
816            } else if ime_active {
817                is_nav_or_edit_key || key.as_str() == WEB_KEY_TAB
818            } else {
819                is_nav_or_edit_key
820                    || key.as_str() == WEB_KEY_PAGE_UP
821                    || key.as_str() == WEB_KEY_PAGE_DOWN
822                    || key.as_str() == WEB_KEY_SPACE
823            };
824            if should_prevent {
825                ev.prevent_default();
826            }
827            web_queue_key_down(&key, &code_str, mods, ev.repeat());
828        }) as Box<dyn FnMut(KeyboardEvent)>);
829    drop(win.add_event_listener_with_callback(WEB_EVENT_KEY_DOWN, on_key.as_ref().unchecked_ref()));
830    on_key.forget();
831    let on_key_up: Closure<dyn FnMut(KeyboardEvent)> =
832        Closure::wrap(Box::new(move |ev: KeyboardEvent| {
833            let key: String = ev.key();
834            let code_str: String = ev.code();
835            let mods: Modifiers =
836                Modifiers::new(ev.shift_key(), ev.ctrl_key(), ev.alt_key(), ev.meta_key());
837            web_queue_key_up(&key, &code_str, mods);
838        }) as Box<dyn FnMut(KeyboardEvent)>);
839    drop(
840        win.add_event_listener_with_callback(WEB_EVENT_KEY_UP, on_key_up.as_ref().unchecked_ref()),
841    );
842    on_key_up.forget();
843    let on_paste: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |ev: Event| {
844        if let Some(pasted) = web_extract_paste_text(&ev)
845            && !pasted.is_empty()
846        {
847            ev.prevent_default();
848            web_queue_text_input(pasted);
849        }
850    }) as Box<dyn FnMut(Event)>);
851    drop(win.add_event_listener_with_callback(WEB_EVENT_PASTE, on_paste.as_ref().unchecked_ref()));
852    on_paste.forget();
853    let on_copy: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |ev: Event| {
854        if web_is_copy_proxy_event(&ev) {
855            return;
856        }
857        if let Some(selected) = web_selected_text_snapshot()
858            && web_write_copy_event_text(&ev, &selected)
859        {
860            ev.prevent_default();
861        }
862    }) as Box<dyn FnMut(Event)>);
863    drop(doc.add_event_listener_with_callback(WEB_EVENT_COPY, on_copy.as_ref().unchecked_ref()));
864    on_copy.forget();
865    let win_resize: Window = win.clone();
866    let canvas_resize: HtmlCanvasElement = canvas.clone();
867    let on_resize: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
868        web_apply_viewport_resize_immediate(&win_resize, &canvas_resize);
869    }) as Box<dyn FnMut(Event)>);
870    drop(
871        win.add_event_listener_with_callback(WEB_EVENT_RESIZE, on_resize.as_ref().unchecked_ref()),
872    );
873    if let Ok(vv) = Reflect::get(win.as_ref(), &JsValue::from_str(WEB_PROP_VISUAL_VIEWPORT))
874        && let Ok(vv_target) = vv.dyn_into::<EventTarget>()
875    {
876        drop(vv_target.add_event_listener_with_callback(
877            WEB_EVENT_RESIZE,
878            on_resize.as_ref().unchecked_ref(),
879        ));
880    }
881    on_resize.forget();
882    let win_ro: Window = win.clone();
883    let canvas_ro: HtmlCanvasElement = canvas.clone();
884    let on_ro: Closure<dyn FnMut(f64, f64)> = Closure::wrap(Box::new(move |pw: f64, ph: f64| {
885        let valid_dims: bool = pw.is_finite() && ph.is_finite();
886        if valid_dims && pw >= 64.0 && ph >= 64.0 {
887            let obs_w: u32 = pw.round().clamp(1.0, WEB_CANVAS_MAX_PHYS_DIM) as u32;
888            let obs_h: u32 = ph.round().clamp(1.0, WEB_CANVAS_MAX_PHYS_DIM) as u32;
889            WEB_OBSERVED_PHYS_SIZE.with(|cell: &Cell<(u32, u32)>| cell.set((obs_w, obs_h)));
890        }
891        web_apply_viewport_resize_immediate(&win_ro, &canvas_ro);
892    }) as Box<dyn FnMut(f64, f64)>);
893    let attach_ro_fn: Function =
894        Function::new_with_args(WEB_JS_ATTACH_RESIZE_ARGS, WEB_JS_ATTACH_RESIZE_OBSERVER);
895    drop(attach_ro_fn.call2(
896        &JsValue::NULL,
897        canvas.as_ref(),
898        on_ro.as_ref().unchecked_ref(),
899    ));
900    on_ro.forget();
901    let win_dpr: Window = win.clone();
902    let canvas_dpr: HtmlCanvasElement = canvas.clone();
903    let on_dpr: Closure<dyn FnMut()> = Closure::wrap(Box::new(move || {
904        web_apply_viewport_resize_immediate(&win_dpr, &canvas_dpr);
905    }) as Box<dyn FnMut()>);
906    let attach_dpr_fn: Function =
907        Function::new_with_args(WEB_JS_WATCH_DPR_ARGS, WEB_JS_WATCH_DPR_BODY);
908    drop(attach_dpr_fn.call1(&JsValue::NULL, on_dpr.as_ref().unchecked_ref()));
909    on_dpr.forget();
910    let win_raf: Window = win.clone();
911    let canvas_raf: HtmlCanvasElement = canvas.clone();
912    WEB_RAF_CALLBACK.with(|slot: &RefCell<Option<Closure<dyn FnMut(f64)>>>| {
913        if let Ok(mut guard) = slot.try_borrow_mut() {
914            *guard = Some(Closure::wrap(Box::new(move |ts: f64| {
915                WEB_RAF_ID.with(|id_cell: &Cell<Option<i32>>| id_cell.set(None));
916                if !web_should_pump_frames() {
917                    WEB_RAF_LAST_TS.with(|ts_cell: &Cell<f64>| ts_cell.set(0.0));
918                    WEB_RAF_ACCUM_SECS.with(|s_cell: &Cell<f32>| s_cell.set(0.0));
919                    WEB_RAF_ACCUM_FRAMES.with(|f_cell: &Cell<u32>| f_cell.set(0));
920                    return;
921                }
922                let prev_ts: f64 = WEB_RAF_LAST_TS.with(|ts_cell: &Cell<f64>| ts_cell.replace(ts));
923                let mut dt: f32 = 1.0 / 60.0;
924                let mut valid_step: bool = false;
925                if prev_ts > 0.0 {
926                    let raw_dt: f32 = ((ts - prev_ts) / 1000.0) as f32;
927                    if (0.001..=0.1).contains(&raw_dt) {
928                        valid_step = true;
929                    }
930                    dt = raw_dt.clamp(0.001, 0.05);
931                }
932                if valid_step {
933                    let next_secs: f32 = WEB_RAF_ACCUM_SECS.with(Cell::get) + dt;
934                    let next_frames: u32 = WEB_RAF_ACCUM_FRAMES.with(Cell::get).saturating_add(1);
935                    if next_secs >= 0.35 && next_frames >= 8 {
936                        let measured_hz: f32 = (next_frames as f32) / next_secs;
937                        WEB_RAF_ACCUM_SECS.with(|s_cell: &Cell<f32>| s_cell.set(0.0));
938                        WEB_RAF_ACCUM_FRAMES.with(|f_cell: &Cell<u32>| f_cell.set(0));
939                        WEB_RAF_CALIBRATED.with(|c: &Cell<bool>| c.set(true));
940                        web_report_host_refresh_rate(measured_hz);
941                    } else {
942                        WEB_RAF_ACCUM_SECS.with(|s_cell: &Cell<f32>| s_cell.set(next_secs));
943                        WEB_RAF_ACCUM_FRAMES.with(|f_cell: &Cell<u32>| f_cell.set(next_frames));
944                    }
945                }
946                let live_dpr_raw: f64 = win_raf.device_pixel_ratio();
947                let live_dpr: f32 = if live_dpr_raw.is_finite() && live_dpr_raw > 0.0 {
948                    (live_dpr_raw as f32).clamp(WEB_DPR_MIN, WEB_DPR_MAX)
949                } else {
950                    1.0
951                };
952                let cached_dpr: f32 = WEB_CACHED_VIEWPORT.with(Cell::get).4;
953                if (live_dpr - cached_dpr).abs() > 0.005 {
954                    let _: bool = web_refresh_cached_viewport(&win_raf, &canvas_raf);
955                }
956                let resized_or_scaled: bool =
957                    if WEB_VIEWPORT_DIRTY.with(|flag: &Cell<bool>| flag.replace(false)) {
958                        web_apply_cached_viewport(&canvas_raf)
959                    } else {
960                        false
961                    };
962                let cur_route: String = euv_web_current_route();
963                let on_game: bool = cur_route == ROUTE_GAME
964                    || cur_route == ROUTE_GAME_3D
965                    || cur_route == ROUTE_WATER;
966                let animating: bool = web_has_active_animations();
967                let dirty: bool = WEB_NEEDS_FRAME.with(|flag: &Cell<bool>| flag.replace(false))
968                    || is_frame_needed();
969                let needs_continuous: bool = resized_or_scaled || on_game;
970                let needs_redraw: bool = animating || dirty;
971                if needs_continuous || needs_redraw {
972                    let _: u64 = web_flush_frame(dt);
973                    web_record_raf_submission_proxy_tick(&canvas_raf);
974                }
975                let calibrated: bool = WEB_RAF_CALIBRATED.with(Cell::get);
976                let still_active: bool = on_game
977                    || web_has_active_animations()
978                    || WEB_NEEDS_FRAME.with(Cell::get)
979                    || is_frame_needed()
980                    || !calibrated;
981                if still_active && web_should_pump_frames() {
982                    web_start_raf_pump(&win_raf);
983                } else {
984                    WEB_RAF_LAST_TS.with(|ts_cell: &Cell<f64>| ts_cell.set(0.0));
985                }
986            }) as Box<dyn FnMut(f64)>));
987        }
988    });
989    if doc.hidden() {
990        web_dispatch_system_event(SystemEvent::Background);
991    } else {
992        web_start_raf_pump(&win);
993    }
994}
995
996/// Records a browser `requestAnimationFrame` callback strictly as `ShowcaseWebTimingSource::SubmissionProxy` without claiming hardware compositor proof.
997///
998/// # Arguments
999///
1000/// - `&HtmlCanvasElement` - Active showcase canvas element providing current physical pixel dimensions.
1001#[cfg(target_arch = "wasm32")]
1002fn web_record_raf_submission_proxy_tick(canvas: &HtmlCanvasElement) {
1003    let pixel_bytes: u64 = u64::from(canvas.width())
1004        .saturating_mul(u64::from(canvas.height()))
1005        .saturating_mul(4);
1006    WEB_DUAL_CANVAS_COORDINATOR.with(|cell: &RefCell<ShowcaseWebDualCanvasCoordinator>| {
1007        if let Ok(mut coord) = cell.try_borrow_mut() {
1008            coord.record_raf_proxy_tick(pixel_bytes);
1009        }
1010    });
1011}
1012
1013/// Starts switching the Web showcase presentation path (`GpuDirect` / `GpuUpload` / `Canvas2d`) using an independent hidden `<canvas>` whenever switching context families.
1014///
1015/// # Arguments
1016///
1017/// - `ShowcaseWebPresentationPath` - Target Web presentation mode.
1018/// - `u32` - Physical canvas width in pixels.
1019/// - `u32` - Physical canvas height in pixels.
1020///
1021/// # Returns
1022///
1023/// - `bool` - `true` when an independent hidden standby `<canvas>` was allocated for pre-warming.
1024#[cfg(target_arch = "wasm32")]
1025#[must_use]
1026pub fn web_begin_independent_canvas_switch(
1027    target: ShowcaseWebPresentationPath,
1028    width: u32,
1029    height: u32,
1030) -> bool {
1031    WEB_DUAL_CANVAS_COORDINATOR.with(|cell: &RefCell<ShowcaseWebDualCanvasCoordinator>| {
1032        cell.try_borrow_mut()
1033            .map(|mut coord: RefMut<'_, ShowcaseWebDualCanvasCoordinator>| {
1034                coord.begin_switch(target, width, height)
1035            })
1036            .unwrap_or(false)
1037    })
1038}
1039
1040/// Commits a pre-warmed independent standby `<canvas>` at a frame boundary once dimensions and scene revision match, retiring the previous canvas only after commit.
1041///
1042/// # Arguments
1043///
1044/// - `u32` - Expected physical width in pixels.
1045/// - `u32` - Expected physical height in pixels.
1046/// - `u64` - Expected scene revision.
1047///
1048/// # Returns
1049///
1050/// - `bool` - `true` when the atomic visibility/z-index swap committed cleanly.
1051#[cfg(target_arch = "wasm32")]
1052#[must_use]
1053pub fn web_commit_independent_canvas_switch(
1054    expected_width: u32,
1055    expected_height: u32,
1056    expected_scene_version: u64,
1057) -> bool {
1058    WEB_DUAL_CANVAS_COORDINATOR.with(|cell: &RefCell<ShowcaseWebDualCanvasCoordinator>| {
1059        cell.try_borrow_mut()
1060            .map(|mut coord: RefMut<'_, ShowcaseWebDualCanvasCoordinator>| {
1061                coord.commit_at_frame_boundary(
1062                    expected_width,
1063                    expected_height,
1064                    expected_scene_version,
1065                )
1066            })
1067            .unwrap_or(false)
1068    })
1069}
1070
1071/// Returns a snapshot of the live Web showcase dual-canvas handoff coordinator and honest `SubmissionProxy` telemetry.
1072///
1073/// # Returns
1074///
1075/// - `ShowcaseWebDualCanvasCoordinator` - Current coordinator snapshot.
1076#[cfg(target_arch = "wasm32")]
1077#[must_use]
1078pub fn web_dual_canvas_snapshot() -> ShowcaseWebDualCanvasCoordinator {
1079    WEB_DUAL_CANVAS_COORDINATOR
1080        .with(|cell: &RefCell<ShowcaseWebDualCanvasCoordinator>| cell.borrow().clone())
1081}
1082
1083/// Returns `true` when the active WebAssembly `App` should pump `requestAnimationFrame` frames.
1084///
1085/// # Returns
1086///
1087/// - `bool` - `false` while background-frozen or shutting down.
1088#[cfg(target_arch = "wasm32")]
1089fn web_should_pump_frames() -> bool {
1090    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1091        match slot.try_borrow() {
1092            Ok(guard) => {
1093                let pump: bool = guard
1094                    .as_ref()
1095                    .map(|(app, _): &(App, ShowcaseState)| app.should_pump_frames())
1096                    .unwrap_or(false);
1097                WEB_SHOULD_PUMP.with(|flag: &Cell<bool>| flag.set(pump));
1098                pump
1099            }
1100            Err(_) => WEB_SHOULD_PUMP.with(Cell::get),
1101        }
1102    })
1103}
1104
1105/// Schedules the retained browser `requestAnimationFrame` callback if no frame is already pending.
1106///
1107/// # Arguments
1108///
1109/// - `&Window` - Active browser `Window`.
1110#[cfg(target_arch = "wasm32")]
1111fn web_start_raf_pump(win: &Window) {
1112    if !web_should_pump_frames() {
1113        return;
1114    }
1115    let already_scheduled: bool =
1116        WEB_RAF_ID.with(|id_cell: &Cell<Option<i32>>| id_cell.get().is_some());
1117    if already_scheduled {
1118        return;
1119    }
1120    WEB_RAF_CALLBACK.with(|slot: &RefCell<Option<Closure<dyn FnMut(f64)>>>| {
1121        if let Ok(cb_ref) = slot.try_borrow()
1122            && let Some(cb) = cb_ref.as_ref()
1123        {
1124            let func: &Function = cb.as_ref().unchecked_ref();
1125            if let Ok(req_id) = win.request_animation_frame(func) {
1126                WEB_RAF_ID.with(|id_cell: &Cell<Option<i32>>| id_cell.set(Some(req_id)));
1127            }
1128        }
1129    });
1130}
1131
1132/// Cancels any pending browser `requestAnimationFrame` callback and resets rAF timing accumulators for zero-CPU background sleep.
1133#[cfg(target_arch = "wasm32")]
1134fn web_stop_raf_pump() {
1135    let pending_id: Option<i32> = WEB_RAF_ID.with(|id_cell: &Cell<Option<i32>>| id_cell.take());
1136    if let Some(req_id) = pending_id
1137        && let Some(win) = window()
1138    {
1139        drop(win.cancel_animation_frame(req_id));
1140    }
1141    WEB_RAF_LAST_TS.with(|ts_cell: &Cell<f64>| ts_cell.set(0.0));
1142    WEB_RAF_ACCUM_SECS.with(|s_cell: &Cell<f32>| s_cell.set(0.0));
1143    WEB_RAF_ACCUM_FRAMES.with(|f_cell: &Cell<u32>| f_cell.set(0));
1144}
1145
1146/// Dispatches a browser-originated `SystemEvent` into the active WebAssembly `App` and pauses or restarts the rAF pump accordingly.
1147///
1148/// # Arguments
1149///
1150/// - `SystemEvent` - Cross-platform system or lifecycle event to normalize and dispatch.
1151#[cfg(target_arch = "wasm32")]
1152fn web_dispatch_system_event(event: SystemEvent) {
1153    let mut should_pump: bool = false;
1154    let mut handled: bool = false;
1155    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1156        if let Ok(mut borrow) = slot.try_borrow_mut()
1157            && let Some((app, _)) = borrow.as_mut()
1158        {
1159            app.dispatch_system_event(event);
1160            should_pump = app.should_pump_frames();
1161            handled = true;
1162        }
1163    });
1164    if !handled {
1165        return;
1166    }
1167    WEB_SHOULD_PUMP.with(|flag: &Cell<bool>| flag.set(should_pump));
1168    if !should_pump {
1169        web_stop_raf_pump();
1170    } else {
1171        WEB_RAF_LAST_TS.with(|ts_cell: &Cell<f64>| ts_cell.set(0.0));
1172        web_mark_needs_frame();
1173        if let Some(win) = window() {
1174            web_start_raf_pump(&win);
1175        }
1176    }
1177}
1178
1179/// Extracts plain UTF-8 text from a DOM `paste` event's `clipboardData.getData("text/plain")`.
1180///
1181/// # Arguments
1182///
1183/// - `&Event` - Browser DOM `paste` event.
1184///
1185/// # Returns
1186///
1187/// - `Option<String>` - Plain text payload when available and non-empty.
1188#[cfg(target_arch = "wasm32")]
1189fn web_extract_paste_text(ev: &Event) -> Option<String> {
1190    let data: JsValue =
1191        Reflect::get(ev.as_ref(), &JsValue::from_str(WEB_PROP_CLIPBOARD_DATA)).ok()?;
1192    if data.is_null() || data.is_undefined() {
1193        return None;
1194    }
1195    let get_fn_val: JsValue = Reflect::get(&data, &JsValue::from_str(WEB_PROP_GET_DATA)).ok()?;
1196    let get_fn: Function = get_fn_val.dyn_into::<Function>().ok()?;
1197    let result: JsValue = get_fn
1198        .call1(&data, &JsValue::from_str(WEB_MIME_TEXT_PLAIN))
1199        .ok()?;
1200    result.as_string().filter(|s: &String| !s.is_empty())
1201}
1202
1203/// Checks whether a DOM `copy` event originated from `euv-core`'s offscreen copy proxy `<textarea>`.
1204///
1205/// # Arguments
1206///
1207/// - `&Event` - Browser DOM `copy` event.
1208///
1209/// # Returns
1210///
1211/// - `bool` - `true` when the event target carries `data-euv-copy-proxy="1"`.
1212#[cfg(target_arch = "wasm32")]
1213fn web_is_copy_proxy_event(ev: &Event) -> bool {
1214    let Some(target) = ev.target() else {
1215        return false;
1216    };
1217    let Ok(el) = target.dyn_into::<Element>() else {
1218        return false;
1219    };
1220    el.get_attribute(WEB_ATTR_COPY_PROXY).as_deref() == Some(WEB_COPY_PROXY_FLAG)
1221}
1222
1223/// Reads the currently selected text from the active WebAssembly showcase scene, if any.
1224///
1225/// # Returns
1226///
1227/// - `Option<String>` - Non-empty selected text string, or `None` when nothing is selected.
1228#[cfg(target_arch = "wasm32")]
1229fn web_selected_text_snapshot() -> Option<String> {
1230    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1231        let Ok(guard) = slot.try_borrow() else {
1232            return None;
1233        };
1234        let (app, _): &(App, ShowcaseState) = guard.as_ref()?;
1235        app.get_scene()
1236            .get_selected_text()
1237            .filter(|s: &String| !s.is_empty())
1238    })
1239}
1240
1241/// Writes `text` into a DOM `copy` event's `clipboardData.setData("text/plain", text)`.
1242///
1243/// # Arguments
1244///
1245/// - `&Event` - Browser DOM `copy` event.
1246/// - `&str` - Plain UTF-8 text to place on the OS clipboard.
1247///
1248/// # Returns
1249///
1250/// - `bool` - `true` when `clipboardData.setData` succeeded.
1251#[cfg(target_arch = "wasm32")]
1252fn web_write_copy_event_text(ev: &Event, text: &str) -> bool {
1253    let Ok(data) = Reflect::get(ev.as_ref(), &JsValue::from_str(WEB_PROP_CLIPBOARD_DATA)) else {
1254        return false;
1255    };
1256    if data.is_null() || data.is_undefined() {
1257        return false;
1258    }
1259    let Ok(set_fn_val) = Reflect::get(&data, &JsValue::from_str(WEB_PROP_SET_DATA)) else {
1260        return false;
1261    };
1262    let Ok(set_fn) = set_fn_val.dyn_into::<Function>() else {
1263        return false;
1264    };
1265    set_fn
1266        .call2(
1267            &data,
1268            &JsValue::from_str(WEB_MIME_TEXT_PLAIN),
1269            &JsValue::from_str(text),
1270        )
1271        .is_ok()
1272}
1273
1274/// Synchronizes showcase route state from browser `popstate` or `hashchange` without mutating the browser forward stack.
1275///
1276/// # Arguments
1277///
1278/// - `&Window` - Active browser `Window`.
1279#[cfg(target_arch = "wasm32")]
1280fn web_sync_route_from_browser_history(win: &Window) {
1281    let raw_hash: String = win.location().hash().unwrap_or_default();
1282    let prev_guard: bool = WEB_SYNCING_FROM_HISTORY.with(|flag: &Cell<bool>| flag.replace(true));
1283    let mut updated: bool = false;
1284    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1285        if let Ok(mut borrow) = slot.try_borrow_mut()
1286            && let Some((app, state)) = borrow.as_mut()
1287        {
1288            let _: String = apply_showcase_history_route(app, state, &raw_hash);
1289            updated = true;
1290        }
1291    });
1292    WEB_SYNCING_FROM_HISTORY.with(|flag: &Cell<bool>| flag.set(prev_guard));
1293    if updated {
1294        let _: bool = web_sync_safe_area();
1295        web_mark_needs_frame();
1296        web_start_raf_pump(win);
1297    }
1298    if let Ok(href) = win.location().href() {
1299        web_dispatch_system_event(SystemEvent::DeepLink(href));
1300    }
1301}
1302
1303/// Returns `true` when the browser document currently has an active fullscreen element (standard or WebKit-prefixed).
1304///
1305/// # Arguments
1306///
1307/// - `&Document` - Active browser `Document`.
1308///
1309/// # Returns
1310///
1311/// - `bool` - `true` when browser fullscreen mode is currently active.
1312#[cfg(target_arch = "wasm32")]
1313fn web_doc_is_fullscreen(doc: &Document) -> bool {
1314    if doc.fullscreen_element().is_some() {
1315        return true;
1316    }
1317    Reflect::get(
1318        doc.as_ref(),
1319        &JsValue::from_str(WEB_PROP_WEBKIT_FULLSCREEN_ELEMENT),
1320    )
1321    .ok()
1322    .map(|v: JsValue| !v.is_null() && !v.is_undefined())
1323    .unwrap_or(false)
1324}
1325
1326/// Attaches a DOM event listener with `{ passive: false }` so `preventDefault()` succeeds reliably on wheel/touch listeners across modern browsers.
1327///
1328/// # Arguments
1329///
1330/// - `&EventTarget` - Target DOM event receiver.
1331/// - `&str` - Event name (for example `"wheel"`).
1332/// - `&Function` - JavaScript callback function reference.
1333#[cfg(target_arch = "wasm32")]
1334fn web_add_non_passive_listener(target: &EventTarget, event: &str, callback: &Function) {
1335    let opts: Object = Object::new();
1336    let _: Result<bool, JsValue> = Reflect::set(
1337        opts.as_ref(),
1338        &JsValue::from_str(WEB_OPT_PASSIVE),
1339        &JsValue::FALSE,
1340    );
1341    if let Ok(add_val) = Reflect::get(
1342        target.as_ref(),
1343        &JsValue::from_str(WEB_METHOD_ADD_EVENT_LISTENER),
1344    ) && let Ok(add_fn) = add_val.dyn_into::<Function>()
1345        && add_fn
1346            .call3(
1347                target.as_ref(),
1348                &JsValue::from_str(event),
1349                callback.as_ref(),
1350                opts.as_ref(),
1351            )
1352            .is_ok()
1353    {
1354        return;
1355    }
1356    drop(target.add_event_listener_with_callback(event, callback));
1357}
1358
1359/// Wakes the WebAssembly runtime back to `Foreground` when user input arrives on a visible tab whose rAF pump was parked.
1360#[cfg(target_arch = "wasm32")]
1361fn web_ensure_visible_foreground() {
1362    if WEB_SHOULD_PUMP.with(Cell::get) {
1363        return;
1364    }
1365    let is_hidden: bool = window()
1366        .and_then(|w: Window| w.document())
1367        .map(|d: Document| d.hidden())
1368        .unwrap_or(false);
1369    if !is_hidden {
1370        web_dispatch_system_event(SystemEvent::Foreground);
1371    }
1372}
1373
1374/// Immediately applies viewport/DPR/safe-area changes to the `<canvas>` and `App`, renders synchronously to prevent blank-buffer flicker, and schedules a follow-up rAF settle frame without waiting for user input.
1375///
1376/// # Arguments
1377///
1378/// - `&Window` - Active browser `Window`.
1379/// - `&HtmlCanvasElement` - Mounted showcase canvas element.
1380#[cfg(target_arch = "wasm32")]
1381fn web_apply_viewport_resize_immediate(win: &Window, canvas: &HtmlCanvasElement) {
1382    web_ensure_visible_foreground();
1383    let viewport_changed: bool = web_refresh_cached_viewport(win, canvas);
1384    let safe_changed: bool = web_sync_safe_area();
1385    let applied: bool = web_apply_cached_viewport(canvas);
1386    let changed_metrics: bool = viewport_changed || safe_changed;
1387    if changed_metrics || applied {
1388        WEB_VIEWPORT_DIRTY.with(|flag: &Cell<bool>| flag.set(false));
1389        let _: u64 = web_flush_frame(0.0);
1390        web_mark_needs_frame();
1391        web_start_raf_pump(win);
1392    }
1393}
1394
1395/// Reconciles `euv` immersive fullscreen state after a browser `fullscreenchange` event (including user `Escape` exit).
1396///
1397/// # Arguments
1398///
1399/// - `&Window` - Active browser `Window`.
1400/// - `&Document` - Active browser `Document`.
1401/// - `&HtmlCanvasElement` - Mounted showcase canvas element.
1402#[cfg(target_arch = "wasm32")]
1403fn web_sync_fullscreen_from_dom(win: &Window, doc: &Document, canvas: &HtmlCanvasElement) {
1404    web_ensure_visible_foreground();
1405    let dom_fs: bool = web_doc_is_fullscreen(doc);
1406    if !dom_fs {
1407        WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1408            if let Ok(mut borrow) = slot.try_borrow_mut()
1409                && let Some((app, _)) = borrow.as_mut()
1410                && (app.is_immersive_fullscreen()
1411                    || is_fullscreen_active()
1412                    || EuvOverlayStack::has_fullscreen())
1413            {
1414                let _: usize = sync_external_fullscreen_exit();
1415                app.set_immersive_fullscreen(false);
1416            }
1417        });
1418    }
1419    let _: bool = web_refresh_cached_viewport(win, canvas);
1420    let _: bool = web_sync_safe_area();
1421    let _: bool = web_apply_cached_viewport(canvas);
1422    WEB_VIEWPORT_DIRTY.with(|flag: &Cell<bool>| flag.set(false));
1423    let _: u64 = web_flush_frame(0.0);
1424    web_mark_needs_frame();
1425    web_start_raf_pump(win);
1426}
1427
1428/// Dispatches a `WindowEvent::ThemeChanged` immediately into the active WebAssembly runtime and schedules a repaint.
1429///
1430/// # Arguments
1431///
1432/// - `ThemeMode` - Newly active browser color-scheme preference.
1433#[cfg(target_arch = "wasm32")]
1434fn web_dispatch_theme_changed(mode: ThemeMode) {
1435    let mut dispatched: bool = false;
1436    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1437        if let Ok(mut borrow) = slot.try_borrow_mut()
1438            && let Some((app, _)) = borrow.as_mut()
1439        {
1440            let wid: WindowId = app.get_window_state().get_id();
1441            app.dispatch_window_event(WindowEvent::ThemeChanged(wid, mode));
1442            dispatched = true;
1443        }
1444    });
1445    if dispatched {
1446        web_mark_needs_frame();
1447    }
1448}
1449
1450/// Refreshes viewport, DPR, safe area, and screen orientation after a browser `orientationchange` event.
1451///
1452/// # Arguments
1453///
1454/// - `&Window` - Active browser `Window`.
1455/// - `&HtmlCanvasElement` - Mounted showcase canvas element.
1456#[cfg(target_arch = "wasm32")]
1457fn web_handle_orientation_change(win: &Window, canvas: &HtmlCanvasElement) {
1458    web_apply_viewport_resize_immediate(win, canvas);
1459    let (_, _, css_w, css_h, _): (f64, f64, f64, f64, f32) = WEB_CACHED_VIEWPORT.with(Cell::get);
1460    let orient: ScreenOrientation = if css_w > css_h {
1461        ScreenOrientation::Landscape
1462    } else {
1463        ScreenOrientation::Portrait
1464    };
1465    web_dispatch_system_event(SystemEvent::OrientationChanged(orient));
1466    let _: u64 = web_flush_frame(0.0);
1467    web_mark_needs_frame();
1468    web_start_raf_pump(win);
1469}
1470
1471/// Attaches browser DOM lifecycle, focus, connectivity, color-scheme, history, fullscreen, orientation, and soft-keyboard listeners onto `win`, `doc`, and `canvas`.
1472///
1473/// # Arguments
1474///
1475/// - `&Window` - Active browser `Window`.
1476/// - `&Document` - Active browser `Document`.
1477/// - `&HtmlCanvasElement` - Mounted showcase canvas element.
1478#[cfg(target_arch = "wasm32")]
1479fn web_attach_system_event_listeners(win: &Window, doc: &Document, canvas: &HtmlCanvasElement) {
1480    let doc_vis: Document = doc.clone();
1481    let win_vis: Window = win.clone();
1482    let canvas_vis: HtmlCanvasElement = canvas.clone();
1483    let on_vis: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1484        if doc_vis.hidden() {
1485            web_queue_pointer_cancel(0);
1486            web_dispatch_system_event(SystemEvent::Background);
1487        } else {
1488            let _: bool = web_refresh_cached_viewport(&win_vis, &canvas_vis);
1489            let _: bool = web_sync_safe_area();
1490            web_dispatch_system_event(SystemEvent::Foreground);
1491        }
1492    }) as Box<dyn FnMut(Event)>);
1493    drop(doc.add_event_listener_with_callback(
1494        WEB_EVENT_VISIBILITY_CHANGE,
1495        on_vis.as_ref().unchecked_ref(),
1496    ));
1497    on_vis.forget();
1498    let win_focus: Window = win.clone();
1499    let canvas_focus: HtmlCanvasElement = canvas.clone();
1500    let on_focus: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1501        let _: bool = web_refresh_cached_viewport(&win_focus, &canvas_focus);
1502        let _: bool = web_sync_safe_area();
1503        web_dispatch_system_event(SystemEvent::Foreground);
1504        web_dispatch_system_event(SystemEvent::FocusChanged(true));
1505    }) as Box<dyn FnMut(Event)>);
1506    drop(win.add_event_listener_with_callback(WEB_EVENT_FOCUS, on_focus.as_ref().unchecked_ref()));
1507    on_focus.forget();
1508    let win_ps: Window = win.clone();
1509    let canvas_ps: HtmlCanvasElement = canvas.clone();
1510    let on_pageshow: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1511        let _: bool = web_refresh_cached_viewport(&win_ps, &canvas_ps);
1512        let _: bool = web_sync_safe_area();
1513        web_sync_route_from_browser_history(&win_ps);
1514        web_dispatch_system_event(SystemEvent::Foreground);
1515    }) as Box<dyn FnMut(Event)>);
1516    drop(win.add_event_listener_with_callback(
1517        WEB_EVENT_PAGE_SHOW,
1518        on_pageshow.as_ref().unchecked_ref(),
1519    ));
1520    on_pageshow.forget();
1521    let on_pagehide: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1522        web_queue_pointer_cancel(0);
1523        web_dispatch_system_event(SystemEvent::Background);
1524    }) as Box<dyn FnMut(Event)>);
1525    drop(win.add_event_listener_with_callback(
1526        WEB_EVENT_PAGE_HIDE,
1527        on_pagehide.as_ref().unchecked_ref(),
1528    ));
1529    on_pagehide.forget();
1530    let on_unload: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1531        web_dispatch_system_event(SystemEvent::Terminate);
1532    }) as Box<dyn FnMut(Event)>);
1533    drop(win.add_event_listener_with_callback(
1534        WEB_EVENT_BEFORE_UNLOAD,
1535        on_unload.as_ref().unchecked_ref(),
1536    ));
1537    on_unload.forget();
1538    let on_online: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1539        web_dispatch_system_event(SystemEvent::NetworkStatusChanged(NetworkStatus::Online));
1540    }) as Box<dyn FnMut(Event)>);
1541    drop(
1542        win.add_event_listener_with_callback(WEB_EVENT_ONLINE, on_online.as_ref().unchecked_ref()),
1543    );
1544    on_online.forget();
1545    let on_offline: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1546        web_dispatch_system_event(SystemEvent::NetworkStatusChanged(NetworkStatus::Offline));
1547    }) as Box<dyn FnMut(Event)>);
1548    drop(
1549        win.add_event_listener_with_callback(
1550            WEB_EVENT_OFFLINE,
1551            on_offline.as_ref().unchecked_ref(),
1552        ),
1553    );
1554    on_offline.forget();
1555    if let Ok(Some(mql)) = win.match_media(WEB_MEDIA_PREFERS_DARK) {
1556        let mql_cb: MediaQueryList = mql.clone();
1557        let on_theme: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1558            let next_theme: ThemeMode = if mql_cb.matches() {
1559                ThemeMode::Dark
1560            } else {
1561                ThemeMode::Light
1562            };
1563            web_dispatch_theme_changed(next_theme);
1564        })
1565            as Box<dyn FnMut(Event)>);
1566        drop(
1567            mql.add_event_listener_with_callback(
1568                WEB_EVENT_CHANGE,
1569                on_theme.as_ref().unchecked_ref(),
1570            ),
1571        );
1572        on_theme.forget();
1573    }
1574    let win_hist: Window = win.clone();
1575    let on_history: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1576        web_sync_route_from_browser_history(&win_hist);
1577    }) as Box<dyn FnMut(Event)>);
1578    drop(win.add_event_listener_with_callback(
1579        WEB_EVENT_HASH_CHANGE,
1580        on_history.as_ref().unchecked_ref(),
1581    ));
1582    drop(win.add_event_listener_with_callback(
1583        WEB_EVENT_POP_STATE,
1584        on_history.as_ref().unchecked_ref(),
1585    ));
1586    on_history.forget();
1587    let win_fs: Window = win.clone();
1588    let doc_fs: Document = doc.clone();
1589    let canvas_fs: HtmlCanvasElement = canvas.clone();
1590    let on_fs_change: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1591        web_sync_fullscreen_from_dom(&win_fs, &doc_fs, &canvas_fs);
1592    }) as Box<dyn FnMut(Event)>);
1593    drop(doc.add_event_listener_with_callback(
1594        WEB_EVENT_FULLSCREEN_CHANGE,
1595        on_fs_change.as_ref().unchecked_ref(),
1596    ));
1597    drop(doc.add_event_listener_with_callback(
1598        WEB_EVENT_WEBKIT_FULLSCREEN_CHANGE,
1599        on_fs_change.as_ref().unchecked_ref(),
1600    ));
1601    on_fs_change.forget();
1602    let win_orient: Window = win.clone();
1603    let canvas_orient: HtmlCanvasElement = canvas.clone();
1604    let on_orient: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1605        web_handle_orientation_change(&win_orient, &canvas_orient);
1606    }) as Box<dyn FnMut(Event)>);
1607    drop(win.add_event_listener_with_callback(
1608        WEB_EVENT_ORIENTATION_CHANGE,
1609        on_orient.as_ref().unchecked_ref(),
1610    ));
1611    if let Ok(screen_val) = Reflect::get(win.as_ref(), &JsValue::from_str(WEB_PROP_SCREEN))
1612        && !screen_val.is_null()
1613        && !screen_val.is_undefined()
1614        && let Ok(orient_val) = Reflect::get(&screen_val, &JsValue::from_str(WEB_PROP_ORIENTATION))
1615        && let Ok(orient_target) = orient_val.dyn_into::<EventTarget>()
1616    {
1617        drop(orient_target.add_event_listener_with_callback(
1618            WEB_EVENT_CHANGE,
1619            on_orient.as_ref().unchecked_ref(),
1620        ));
1621    }
1622    on_orient.forget();
1623    let vv_key: JsValue = JsValue::from_str(WEB_PROP_VISUAL_VIEWPORT);
1624    if let Ok(vv_val) = Reflect::get(win.as_ref(), &vv_key)
1625        && let Ok(vv_target) = vv_val.clone().dyn_into::<EventTarget>()
1626    {
1627        let win_vv: Window = win.clone();
1628        let vv_obj: JsValue = vv_val;
1629        let on_vv_resize: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1630            let inner_h: f32 = win_vv
1631                .inner_height()
1632                .ok()
1633                .and_then(|v: JsValue| v.as_f64())
1634                .unwrap_or(0.0) as f32;
1635            let h_key: JsValue = JsValue::from_str(WEB_PROP_HEIGHT);
1636            let vv_h: f32 = Reflect::get(&vv_obj, &h_key)
1637                .ok()
1638                .and_then(|v: JsValue| v.as_f64())
1639                .unwrap_or(inner_h as f64) as f32;
1640            let kb_delta: f32 = (inner_h - vv_h).max(0.0);
1641            let visible: bool = kb_delta >= WEB_KEYBOARD_MIN_DELTA_PX;
1642            let height: f32 = if visible { kb_delta } else { 0.0 };
1643            web_dispatch_system_event(SystemEvent::KeyboardVisibilityChanged { visible, height });
1644            if web_sync_safe_area() {
1645                web_mark_needs_frame();
1646            }
1647        })
1648            as Box<dyn FnMut(Event)>);
1649        drop(vv_target.add_event_listener_with_callback(
1650            WEB_EVENT_RESIZE,
1651            on_vv_resize.as_ref().unchecked_ref(),
1652        ));
1653        on_vv_resize.forget();
1654    }
1655}
1656
1657/// Maps a browser `KeyboardEvent.key` and physical `KeyboardEvent.code` into a cross-platform `KeyCode`.
1658///
1659/// # Arguments
1660///
1661/// - `&str` - Browser DOM `KeyboardEvent.key` string.
1662/// - `&str` - Browser DOM physical `KeyboardEvent.code` string (IME-independent).
1663///
1664/// # Returns
1665///
1666/// - `KeyCode` - Normalized `euv` key code.
1667#[cfg(target_arch = "wasm32")]
1668fn web_map_key(key: &str, code_str: &str) -> KeyCode {
1669    match code_str {
1670        WEB_CODE_KEY_W => return KeyCode::Character('w'),
1671        WEB_CODE_KEY_A => return KeyCode::Character('a'),
1672        WEB_CODE_KEY_S => return KeyCode::Character('s'),
1673        WEB_CODE_KEY_D => return KeyCode::Character('d'),
1674        WEB_CODE_KEY_E => return KeyCode::Character('e'),
1675        WEB_CODE_KEY_R => return KeyCode::Character('r'),
1676        WEB_CODE_KEY_P => return KeyCode::Character('p'),
1677        WEB_CODE_KEY_J => return KeyCode::Character('j'),
1678        WEB_CODE_KEY_C => return KeyCode::Character('c'),
1679        WEB_CODE_KEY_V => return KeyCode::Character('v'),
1680        WEB_CODE_KEY_X => return KeyCode::Character('x'),
1681        WEB_CODE_KEY_Z => return KeyCode::Character('z'),
1682        WEB_CODE_KEY_K => return KeyCode::Character('k'),
1683        WEB_CODE_SPACE => return KeyCode::Space,
1684        WEB_KEY_ARROW_LEFT => return KeyCode::ArrowLeft,
1685        WEB_KEY_ARROW_RIGHT => return KeyCode::ArrowRight,
1686        WEB_KEY_ARROW_UP => return KeyCode::ArrowUp,
1687        WEB_KEY_ARROW_DOWN => return KeyCode::ArrowDown,
1688        WEB_KEY_HOME => return KeyCode::Home,
1689        WEB_KEY_END => return KeyCode::End,
1690        WEB_KEY_PAGE_UP => return KeyCode::PageUp,
1691        WEB_KEY_PAGE_DOWN => return KeyCode::PageDown,
1692        _ => {}
1693    }
1694    match key {
1695        WEB_KEY_ENTER => KeyCode::Enter,
1696        WEB_KEY_BACKSPACE => KeyCode::Backspace,
1697        WEB_KEY_DELETE => KeyCode::Delete,
1698        WEB_KEY_ESCAPE => KeyCode::Escape,
1699        WEB_KEY_TAB => KeyCode::Tab,
1700        WEB_KEY_SPACE => KeyCode::Space,
1701        WEB_KEY_ARROW_LEFT => KeyCode::ArrowLeft,
1702        WEB_KEY_ARROW_RIGHT => KeyCode::ArrowRight,
1703        WEB_KEY_ARROW_UP => KeyCode::ArrowUp,
1704        WEB_KEY_ARROW_DOWN => KeyCode::ArrowDown,
1705        WEB_KEY_HOME => KeyCode::Home,
1706        WEB_KEY_END => KeyCode::End,
1707        WEB_KEY_PAGE_UP => KeyCode::PageUp,
1708        WEB_KEY_PAGE_DOWN => KeyCode::PageDown,
1709        other => other
1710            .chars()
1711            .next()
1712            .map(KeyCode::Character)
1713            .unwrap_or(KeyCode::Unknown),
1714    }
1715}
1716
1717/// Returns `true` when the active WebAssembly app has running UI transition animations.
1718///
1719/// # Returns
1720///
1721/// - `bool` - Whether animation frames must continue ticking.
1722#[cfg(target_arch = "wasm32")]
1723fn web_has_active_animations() -> bool {
1724    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1725        match slot.try_borrow() {
1726            Ok(guard) => guard
1727                .as_ref()
1728                .map(|(app, _): &(App, ShowcaseState)| app.has_active_animations())
1729                .unwrap_or(false),
1730            Err(_) => false,
1731        }
1732    })
1733}
1734
1735/// Marks the coalesced Web animation-frame render flag and wakes the demand-driven `requestAnimationFrame` pump if parked.
1736#[cfg(target_arch = "wasm32")]
1737fn web_mark_needs_frame() {
1738    WEB_NEEDS_FRAME.with(|flag: &Cell<bool>| flag.set(true));
1739    let idle: bool = WEB_RAF_ID.with(|id_cell: &Cell<Option<i32>>| id_cell.get().is_none());
1740    if idle && let Some(win) = window() {
1741        web_start_raf_pump(&win);
1742    }
1743}
1744
1745/// Normalizes a browser `PointerEvent.pointerId` into a non-zero cross-platform pointer identifier.
1746///
1747/// # Arguments
1748///
1749/// - `&web_sys::PointerEvent` - Browser DOM pointer event.
1750///
1751/// # Returns
1752///
1753/// - `u64` - Stable non-zero pointer identifier.
1754#[cfg(target_arch = "wasm32")]
1755fn web_pointer_id_from_dom(ev: &web_sys::PointerEvent) -> u64 {
1756    (ev.pointer_id() as i64).unsigned_abs().saturating_add(1)
1757}
1758
1759/// Converts a browser DOM `PointerEvent` into an `euv::PointerEvent` using cached canvas coordinates without triggering DOM layout reflow.
1760///
1761/// # Arguments
1762///
1763/// - `&web_sys::PointerEvent` - Browser DOM pointer event.
1764/// - `Option<bool>` - Optional explicit pressed override (`Some(true)` on down, `Some(false)` on up, `None` to inspect `buttons()`).
1765///
1766/// # Returns
1767///
1768/// - `PointerEvent` - Cross-platform pointer event.
1769#[cfg(target_arch = "wasm32")]
1770fn web_pointer_from_dom(ev: &web_sys::PointerEvent, force_pressed: Option<bool>) -> PointerEvent {
1771    let (left, top, _, _, _): (f64, f64, f64, f64, f32) = WEB_CACHED_VIEWPORT.with(Cell::get);
1772    let x: f32 = (ev.client_x() as f64 - left) as f32;
1773    let y: f32 = (ev.client_y() as f64 - top) as f32;
1774    let pid: u64 = web_pointer_id_from_dom(ev);
1775    let ptype: String = ev.pointer_type();
1776    let device: PointerDevice = if ptype == WEB_PTR_TYPE_TOUCH {
1777        PointerDevice::Touch
1778    } else if ptype == WEB_PTR_TYPE_PEN {
1779        PointerDevice::Stylus
1780    } else {
1781        PointerDevice::Mouse
1782    };
1783    let is_pressed: bool =
1784        force_pressed.unwrap_or_else(|| ev.buttons() != 0 || device == PointerDevice::Touch);
1785    let pressure: f32 = if is_pressed { 1.0 } else { 0.0 };
1786    let mods: Modifiers =
1787        Modifiers::new(ev.shift_key(), ev.ctrl_key(), ev.alt_key(), ev.meta_key());
1788    PointerEvent::new(
1789        pid,
1790        device,
1791        Point::new(x, y),
1792        PointerButton::Primary,
1793        pressure,
1794        mods,
1795    )
1796}
1797
1798/// Enqueues a browser pointer move into the active WebAssembly runtime without forcing redundant repaints on no-op hover movement.
1799///
1800/// # Arguments
1801///
1802/// - `PointerEvent` - Normalized pointer move event.
1803#[cfg(target_arch = "wasm32")]
1804fn web_queue_pointer_move_event(ptr: PointerEvent) {
1805    let mut needs_redraw: bool = false;
1806    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1807        if let Ok(mut borrow) = slot.try_borrow_mut()
1808            && let Some((app, _)) = borrow.as_mut()
1809        {
1810            let rev_before: u64 = app.get_scene().with_read(SceneTree::get_revision, 0);
1811            let cursor_before: CursorIcon = app.get_last_cursor();
1812            let wid: WindowId = app.get_window_state().get_id();
1813            app.dispatch_window_event(WindowEvent::PointerMove(wid, ptr));
1814            let rev_after: u64 = app.get_scene().with_read(SceneTree::get_revision, 0);
1815            let cursor_after: CursorIcon = app.get_last_cursor();
1816            let active_drag: bool =
1817                ptr.get_pressure() > 0.0 || ptr.get_device() != PointerDevice::Mouse;
1818            let has_anim: bool = app
1819                .get_scene()
1820                .with_read(SceneTree::has_active_transitions, false);
1821            needs_redraw = rev_after != rev_before
1822                || cursor_after != cursor_before
1823                || active_drag
1824                || has_anim
1825                || is_frame_needed();
1826        }
1827    });
1828    if needs_redraw {
1829        web_mark_needs_frame();
1830    }
1831}
1832
1833/// Enqueues a browser pointer press into the active WebAssembly runtime for the next animation frame.
1834///
1835/// # Arguments
1836///
1837/// - `PointerEvent` - Normalized pointer press event.
1838#[cfg(target_arch = "wasm32")]
1839fn web_queue_pointer_down_event(ptr: PointerEvent) {
1840    web_ensure_visible_foreground();
1841    let mut queued: bool = false;
1842    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1843        if let Ok(mut borrow) = slot.try_borrow_mut()
1844            && let Some((app, _)) = borrow.as_mut()
1845        {
1846            let wid: WindowId = app.get_window_state().get_id();
1847            app.dispatch_window_event(WindowEvent::PointerDown(wid, ptr));
1848            queued = true;
1849        }
1850    });
1851    if queued {
1852        web_mark_needs_frame();
1853    }
1854}
1855
1856/// Enqueues a browser pointer release into the active WebAssembly runtime for the next animation frame.
1857///
1858/// # Arguments
1859///
1860/// - `PointerEvent` - Normalized pointer release event.
1861#[cfg(target_arch = "wasm32")]
1862fn web_queue_pointer_up_event(ptr: PointerEvent) {
1863    let mut queued: bool = false;
1864    let mut fs_exited: bool = false;
1865    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1866        if let Ok(mut borrow) = slot.try_borrow_mut()
1867            && let Some((app, _)) = borrow.as_mut()
1868        {
1869            let was_fs: bool = app.is_immersive_fullscreen() || is_fullscreen_active();
1870            let wid: WindowId = app.get_window_state().get_id();
1871            app.dispatch_window_event(WindowEvent::PointerUp(wid, ptr));
1872            let now_fs: bool = app.is_immersive_fullscreen() || is_fullscreen_active();
1873            fs_exited = was_fs && !now_fs;
1874            queued = true;
1875        }
1876    });
1877    if fs_exited {
1878        let _: u64 = web_flush_frame(0.0);
1879    }
1880    if queued {
1881        web_mark_needs_frame();
1882    }
1883}
1884
1885/// Enqueues a browser pointer cancel (`0` cancels all active contacts) into the active WebAssembly runtime.
1886///
1887/// # Arguments
1888///
1889/// - `u64` - Cancelled pointer identifier (`0` cancels all active pointers).
1890#[cfg(target_arch = "wasm32")]
1891fn web_queue_pointer_cancel(pointer_id: u64) {
1892    let mut queued: bool = false;
1893    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1894        if let Ok(mut borrow) = slot.try_borrow_mut()
1895            && let Some((app, _)) = borrow.as_mut()
1896        {
1897            let wid: WindowId = app.get_window_state().get_id();
1898            app.dispatch_window_event(WindowEvent::PointerCancel(wid, pointer_id));
1899            queued = true;
1900        }
1901    });
1902    if queued {
1903        web_mark_needs_frame();
1904    }
1905}
1906
1907/// Enqueues a normalized browser wheel scroll delta at `(x, y)` for coalesced VSync rendering.
1908///
1909/// # Arguments
1910///
1911/// - `f32` - Pointer X coordinate inside the canvas.
1912/// - `f32` - Pointer Y coordinate inside the canvas.
1913/// - `f32` - Horizontal scroll delta.
1914/// - `f32` - Vertical scroll delta.
1915#[cfg(target_arch = "wasm32")]
1916fn web_queue_scroll_at(x: f32, y: f32, dx: f32, dy: f32) {
1917    web_ensure_visible_foreground();
1918    let mut queued: bool = false;
1919    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1920        if let Ok(mut borrow) = slot.try_borrow_mut()
1921            && let Some((app, _)) = borrow.as_mut()
1922        {
1923            let wid: WindowId = app.get_window_state().get_id();
1924            app.dispatch_window_event(WindowEvent::PointerMove(wid, PointerEvent::mouse(x, y)));
1925            app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(dx, dy)));
1926            queued = true;
1927        }
1928    });
1929    if queued {
1930        web_mark_needs_frame();
1931    }
1932}
1933
1934/// Enqueues a browser key-down and optional printable text event for the next animation frame.
1935///
1936/// # Arguments
1937///
1938/// - `&str` - DOM `KeyboardEvent.key` string.
1939/// - `&str` - DOM physical `KeyboardEvent.code` string.
1940/// - `Modifiers` - Active Shift/Ctrl/Alt/Meta modifier flags from the DOM `KeyboardEvent`.
1941/// - `bool` - Whether the DOM `KeyboardEvent` is a key auto-repeat.
1942#[cfg(target_arch = "wasm32")]
1943fn web_queue_key_down(key: &str, code_str: &str, mods: Modifiers, repeat: bool) {
1944    if WEB_IME_COMPOSING.with(Cell::get) {
1945        return;
1946    }
1947    web_ensure_visible_foreground();
1948    let ime_active: bool = WEB_IME_ACTIVE.with(Cell::get);
1949    let mut queued: bool = false;
1950    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1951        if let Ok(mut borrow) = slot.try_borrow_mut()
1952            && let Some((app, _)) = borrow.as_mut()
1953        {
1954            let wid: WindowId = app.get_window_state().get_id();
1955            let code: KeyCode = web_map_key(key, code_str);
1956            let key_ev: WindowEvent = WindowEvent::KeyDown(wid, KeyEvent::new(code, mods, repeat));
1957            app.dispatch_window_event(key_ev);
1958            if web_should_dispatch_text_input(ime_active, mods, key) {
1959                app.dispatch_window_event(WindowEvent::TextInput(wid, key.to_string()));
1960            }
1961            queued = true;
1962        }
1963    });
1964    if queued {
1965        web_mark_needs_frame();
1966    }
1967}
1968
1969/// Dispatches committed browser IME or virtual keyboard text into the active WebAssembly runtime.
1970///
1971/// # Arguments
1972///
1973/// - `String` - Committed UTF-8 text from the hidden IME proxy input.
1974#[cfg(target_arch = "wasm32")]
1975fn web_queue_text_input(text: String) {
1976    if text.is_empty() {
1977        return;
1978    }
1979    let mut queued: bool = false;
1980    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1981        if let Ok(mut borrow) = slot.try_borrow_mut()
1982            && let Some((app, _)) = borrow.as_mut()
1983        {
1984            let wid: WindowId = app.get_window_state().get_id();
1985            app.dispatch_window_event(WindowEvent::TextInput(wid, text));
1986            queued = true;
1987        }
1988    });
1989    if queued {
1990        web_mark_needs_frame();
1991    }
1992}
1993
1994/// Reads and clears the hidden browser IME proxy `<input>` value, falling back to `fallback` when empty, and dispatches any committed text into `euv`.
1995///
1996/// # Arguments
1997///
1998/// - `&HtmlElement` - Hidden browser IME proxy element.
1999/// - `Option<String>` - Optional `CompositionEvent.data` fallback when the DOM element value was already cleared.
2000#[cfg(target_arch = "wasm32")]
2001fn web_flush_ime_element(el: &HtmlElement, fallback: Option<String>) {
2002    let key: JsValue = JsValue::from_str(WEB_PROP_VALUE);
2003    let el_text: Option<String> = Reflect::get(el.as_ref(), &key)
2004        .ok()
2005        .and_then(|val: JsValue| val.as_string())
2006        .filter(|s: &String| !s.is_empty());
2007    let _: Result<bool, JsValue> = Reflect::set(el.as_ref(), &key, &JsValue::from_str(""));
2008    let committed: Option<String> = el_text.or_else(|| fallback.filter(|s: &String| !s.is_empty()));
2009    if let Some(text) = committed {
2010        web_queue_text_input(text);
2011    }
2012}
2013
2014/// Returns `true` when a DOM `InputEvent` reports `isComposing === true`.
2015///
2016/// # Arguments
2017///
2018/// - `&Event` - Browser DOM `input` event.
2019///
2020/// # Returns
2021///
2022/// - `bool` - `true` while an OS/browser IME composition is still in progress.
2023#[cfg(target_arch = "wasm32")]
2024fn web_event_is_composing(ev: &Event) -> bool {
2025    Reflect::get(ev.as_ref(), &JsValue::from_str(WEB_PROP_IS_COMPOSING))
2026        .ok()
2027        .and_then(|val: JsValue| val.as_bool())
2028        .unwrap_or(false)
2029}
2030
2031/// Extracts `CompositionEvent.data` as an optional non-empty UTF-8 string.
2032///
2033/// # Arguments
2034///
2035/// - `&Event` - Browser DOM `compositionend` event.
2036///
2037/// # Returns
2038///
2039/// - `Option<String>` - Committed composition string if present and non-empty.
2040#[cfg(target_arch = "wasm32")]
2041fn web_event_data_string(ev: &Event) -> Option<String> {
2042    Reflect::get(ev.as_ref(), &JsValue::from_str(WEB_PROP_DATA))
2043        .ok()
2044        .and_then(|val: JsValue| val.as_string())
2045        .filter(|s: &String| !s.is_empty())
2046}
2047
2048/// Attaches a visually hidden DOM `<input>` element so mobile browsers and CJK IMEs open native keyboards on input focus.
2049///
2050/// # Arguments
2051///
2052/// - `&Document` - Active browser DOM document.
2053#[cfg(target_arch = "wasm32")]
2054fn web_attach_ime_proxy(doc: &Document) {
2055    let Ok(raw_el) = doc.create_element(WEB_IME_INPUT_TAG) else {
2056        return;
2057    };
2058    let el: Element = raw_el;
2059    drop(el.set_attribute(WEB_IME_ATTR_ID, WEB_IME_INPUT_ID));
2060    drop(el.set_attribute(WEB_IME_ATTR_TYPE, WEB_IME_ATTR_TEXT));
2061    drop(el.set_attribute(WEB_IME_ATTR_AUTOCOMPLETE, WEB_IME_ATTR_OFF));
2062    drop(el.set_attribute(WEB_IME_ATTR_AUTOCORRECT, WEB_IME_ATTR_OFF));
2063    drop(el.set_attribute(WEB_IME_ATTR_AUTOCAPITALIZE, WEB_IME_ATTR_OFF));
2064    drop(el.set_attribute(WEB_IME_ATTR_SPELLCHECK, WEB_IME_ATTR_FALSE));
2065    drop(el.set_attribute(WEB_IME_ATTR_ARIA_LABEL, WEB_IME_ARIA_LABEL));
2066    drop(el.set_attribute(WEB_IME_ATTR_STYLE, WEB_IME_STYLE));
2067    let Ok(html_el) = el.dyn_into::<HtmlElement>() else {
2068        return;
2069    };
2070    if let Some(body) = doc.body() {
2071        drop(body.append_child(&html_el));
2072    }
2073    let on_ime_focus: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
2074        WEB_IME_ACTIVE.with(|a: &Cell<bool>| a.set(true));
2075    }) as Box<dyn FnMut(Event)>);
2076    drop(
2077        html_el.add_event_listener_with_callback(
2078            WEB_EVENT_FOCUS,
2079            on_ime_focus.as_ref().unchecked_ref(),
2080        ),
2081    );
2082    on_ime_focus.forget();
2083    let comp_start: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
2084        WEB_IME_COMPOSING.with(|c: &Cell<bool>| c.set(true));
2085    }) as Box<dyn FnMut(Event)>);
2086    drop(html_el.add_event_listener_with_callback(
2087        WEB_EVENT_COMPOSITION_START,
2088        comp_start.as_ref().unchecked_ref(),
2089    ));
2090    comp_start.forget();
2091    let comp_update: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
2092        WEB_IME_COMPOSING.with(|c: &Cell<bool>| c.set(true));
2093    }) as Box<dyn FnMut(Event)>);
2094    drop(html_el.add_event_listener_with_callback(
2095        WEB_EVENT_COMPOSITION_UPDATE,
2096        comp_update.as_ref().unchecked_ref(),
2097    ));
2098    comp_update.forget();
2099    let comp_el: HtmlElement = html_el.clone();
2100    let comp_end: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |ev: Event| {
2101        WEB_IME_COMPOSING.with(|c: &Cell<bool>| c.set(false));
2102        let fallback: Option<String> = web_event_data_string(&ev);
2103        web_flush_ime_element(&comp_el, fallback);
2104    }) as Box<dyn FnMut(Event)>);
2105    drop(html_el.add_event_listener_with_callback(
2106        WEB_EVENT_COMPOSITION_END,
2107        comp_end.as_ref().unchecked_ref(),
2108    ));
2109    comp_end.forget();
2110    let inp_el: HtmlElement = html_el.clone();
2111    let on_input: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |ev: Event| {
2112        if !WEB_IME_COMPOSING.with(Cell::get) && !web_event_is_composing(&ev) {
2113            web_flush_ime_element(&inp_el, None);
2114        }
2115    }) as Box<dyn FnMut(Event)>);
2116    drop(
2117        html_el
2118            .add_event_listener_with_callback(WEB_EVENT_INPUT, on_input.as_ref().unchecked_ref()),
2119    );
2120    on_input.forget();
2121    let on_ime_blur: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
2122        WEB_IME_ACTIVE.with(|a: &Cell<bool>| a.set(false));
2123        WEB_IME_COMPOSING.with(|c: &Cell<bool>| c.set(false));
2124        WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2125            if let Ok(mut borrow) = slot.try_borrow_mut()
2126                && let Some((app, _)) = borrow.as_mut()
2127            {
2128                let wid: WindowId = app.get_window_state().get_id();
2129                app.dispatch_window_event(WindowEvent::Ime(wid, ImeEvent::Disabled));
2130            }
2131        });
2132    }) as Box<dyn FnMut(Event)>);
2133    drop(
2134        html_el
2135            .add_event_listener_with_callback(WEB_EVENT_BLUR, on_ime_blur.as_ref().unchecked_ref()),
2136    );
2137    on_ime_blur.forget();
2138    WEB_IME_ELEMENT.with(|slot: &RefCell<Option<HtmlElement>>| {
2139        if let Ok(mut guard) = slot.try_borrow_mut() {
2140            *guard = Some(html_el);
2141        }
2142    });
2143}
2144
2145/// Handles `euv` native action requests in the browser (fullscreen, external URL open, and hidden IME proxy focus).
2146///
2147/// # Arguments
2148///
2149/// - `&str` - Action category (e.g. `NATIVE_ACTION_FULLSCREEN`, `NATIVE_ACTION_OPEN_URL`, `NATIVE_ACTION_IME`).
2150/// - `&str` - Action subcommand (`"show"` / `"hide"` / `"on"` / `"off"` or external URL).
2151/// - `&str` - Secondary payload argument.
2152///
2153/// # Returns
2154///
2155/// - `bool` - `true` when handled by the browser bridge.
2156#[cfg(target_arch = "wasm32")]
2157fn web_native_action_bridge(kind: &str, arg1: &str, _arg2: &str) -> bool {
2158    if kind == NATIVE_ACTION_FULLSCREEN {
2159        if arg1 == WEB_FS_ACTION_ON {
2160            web_set_fullscreen(true);
2161            return true;
2162        }
2163        if arg1 == WEB_FS_ACTION_OFF {
2164            web_set_fullscreen(false);
2165            return true;
2166        }
2167        return false;
2168    }
2169    if kind == NATIVE_ACTION_OPEN_URL {
2170        if !is_valid_external_url(arg1) {
2171            return false;
2172        }
2173        let Some(win) = window() else {
2174            return false;
2175        };
2176        return win
2177            .open_with_url_and_target_and_features(
2178                arg1.trim(),
2179                WEB_OPEN_TARGET_BLANK,
2180                WEB_OPEN_FEATURES_SAFE,
2181            )
2182            .is_ok();
2183    }
2184    if kind != NATIVE_ACTION_IME {
2185        return false;
2186    }
2187    WEB_IME_ELEMENT.with(|slot: &RefCell<Option<HtmlElement>>| {
2188        let Ok(guard) = slot.try_borrow() else {
2189            return false;
2190        };
2191        let Some(el) = guard.as_ref() else {
2192            return false;
2193        };
2194        if arg1 == WEB_IME_ACTION_SHOW {
2195            WEB_IME_ACTIVE.with(|a: &Cell<bool>| a.set(true));
2196            let already_focused: bool = window()
2197                .and_then(|win: Window| win.document())
2198                .and_then(|doc: Document| doc.active_element())
2199                .map(|active_el: Element| active_el.id() == WEB_IME_INPUT_ID)
2200                .unwrap_or(false);
2201            if !already_focused {
2202                drop(el.focus());
2203            }
2204            true
2205        } else if arg1 == WEB_IME_ACTION_HIDE {
2206            WEB_IME_ACTIVE.with(|a: &Cell<bool>| a.set(false));
2207            WEB_IME_COMPOSING.with(|c: &Cell<bool>| c.set(false));
2208            let key: JsValue = JsValue::from_str(WEB_PROP_VALUE);
2209            let _: Result<bool, JsValue> = Reflect::set(el.as_ref(), &key, &JsValue::from_str(""));
2210            drop(el.blur());
2211            true
2212        } else {
2213            false
2214        }
2215    })
2216}
2217
2218/// Enqueues a browser key-up event into the active WebAssembly runtime and game host.
2219///
2220/// # Arguments
2221///
2222/// - `&str` - DOM `KeyboardEvent.key` string.
2223/// - `&str` - DOM physical `KeyboardEvent.code` string.
2224/// - `Modifiers` - Active Shift/Ctrl/Alt/Meta modifier flags from the DOM `KeyboardEvent`.
2225#[cfg(target_arch = "wasm32")]
2226fn web_queue_key_up(key: &str, code_str: &str, mods: Modifiers) {
2227    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2228        if let Ok(mut borrow) = slot.try_borrow_mut()
2229            && let Some((app, _)) = borrow.as_mut()
2230        {
2231            let wid: WindowId = app.get_window_state().get_id();
2232            let code: KeyCode = web_map_key(key, code_str);
2233            app.dispatch_window_event(WindowEvent::KeyUp(wid, KeyEvent::new(code, mods, false)));
2234        }
2235    });
2236}
2237
2238/// Reads the browser's live CSS viewport `(width, height)` preferring `visualViewport` (when not pinch-zoomed) and `documentElement.clientWidth/Height` before `innerWidth/Height`.
2239///
2240/// # Arguments
2241///
2242/// - `&Window` - Active browser window.
2243///
2244/// # Returns
2245///
2246/// - `(f64, f64)` - Measured CSS viewport `(width, height)`.
2247#[cfg(target_arch = "wasm32")]
2248fn web_read_window_css_viewport(win: &Window) -> (f64, f64) {
2249    if let Ok(vv) = Reflect::get(win.as_ref(), &JsValue::from_str(WEB_PROP_VISUAL_VIEWPORT))
2250        && !vv.is_null()
2251        && !vv.is_undefined()
2252    {
2253        let vv_scale: f64 = Reflect::get(&vv, &JsValue::from_str(WEB_PROP_SCALE))
2254            .ok()
2255            .and_then(|v: JsValue| v.as_f64())
2256            .filter(|v: &f64| v.is_finite() && *v > 0.0)
2257            .unwrap_or(1.0);
2258        if vv_scale <= WEB_PINCH_ZOOM_THRESHOLD {
2259            let vw: Option<f64> = Reflect::get(&vv, &JsValue::from_str(WEB_PROP_WIDTH))
2260                .ok()
2261                .and_then(|v: JsValue| v.as_f64())
2262                .filter(|v: &f64| v.is_finite() && *v >= 64.0);
2263            let vh: Option<f64> = Reflect::get(&vv, &JsValue::from_str(WEB_PROP_HEIGHT))
2264                .ok()
2265                .and_then(|v: JsValue| v.as_f64())
2266                .filter(|v: &f64| v.is_finite() && *v >= 64.0);
2267            if let (Some(w), Some(h)) = (vw, vh) {
2268                return (w, h);
2269            }
2270        }
2271    }
2272    if let Some(root) = win
2273        .document()
2274        .and_then(|doc: Document| doc.document_element())
2275    {
2276        let cw: f64 = f64::from(root.client_width());
2277        let ch: f64 = f64::from(root.client_height());
2278        if cw >= 64.0 && ch >= 64.0 {
2279            return (cw, ch);
2280        }
2281    }
2282    let w: f64 = win
2283        .inner_width()
2284        .ok()
2285        .and_then(|v: JsValue| v.as_f64())
2286        .filter(|w: &f64| w.is_finite() && *w >= 64.0)
2287        .unwrap_or(SHOWCASE_WINDOW_WIDTH as f64);
2288    let h: f64 = win
2289        .inner_height()
2290        .ok()
2291        .and_then(|v: JsValue| v.as_f64())
2292        .filter(|h: &f64| h.is_finite() && *h >= 64.0)
2293        .unwrap_or(SHOWCASE_WINDOW_HEIGHT as f64);
2294    (w, h)
2295}
2296
2297/// Queries browser `<canvas>` geometry and `devicePixelRatio` once before constructing `App` so Frame 1 renders directly at exact physical pixels.
2298///
2299/// # Returns
2300///
2301/// - `(f64, f64, f64, f64, f32)` - Measured `(left, top, css_width, css_height, dpr)`.
2302#[cfg(target_arch = "wasm32")]
2303fn web_query_initial_viewport() -> (f64, f64, f64, f64, f32) {
2304    let Some(win) = window() else {
2305        return (
2306            0.0,
2307            0.0,
2308            SHOWCASE_WINDOW_WIDTH as f64,
2309            SHOWCASE_WINDOW_HEIGHT as f64,
2310            1.0,
2311        );
2312    };
2313    let dpr_raw: f64 = win.device_pixel_ratio();
2314    let dpr: f32 = if dpr_raw.is_finite() && dpr_raw > 0.0 {
2315        (dpr_raw as f32).clamp(WEB_DPR_MIN, WEB_DPR_MAX)
2316    } else {
2317        1.0
2318    };
2319    let mut left: f64 = 0.0;
2320    let mut top: f64 = 0.0;
2321    let mut css_w: f64 = 0.0;
2322    let mut css_h: f64 = 0.0;
2323    if let Some(doc) = win.document()
2324        && let Ok(Some(el)) = doc.query_selector(WEB_SELECTOR_CANVAS)
2325        && let Ok(canvas) = el.dyn_into::<HtmlCanvasElement>()
2326    {
2327        let rect: DomRect = canvas.get_bounding_client_rect();
2328        left = rect.left();
2329        top = rect.top();
2330        css_w = rect.width();
2331        css_h = rect.height();
2332    }
2333    let (win_w, win_h): (f64, f64) = web_read_window_css_viewport(&win);
2334    if !css_w.is_finite() || css_w < 64.0 {
2335        css_w = win_w;
2336    }
2337    if !css_h.is_finite() || css_h < 64.0 {
2338        css_h = win_h;
2339    }
2340    (left, top, css_w, css_h, dpr)
2341}
2342
2343/// Refreshes `WEB_CACHED_VIEWPORT` from DOM resize or DPR change events and marks the viewport dirty when metrics change.
2344///
2345/// # Arguments
2346///
2347/// - `&Window` - Browser window object.
2348/// - `&HtmlCanvasElement` - Target full-viewport canvas element.
2349///
2350/// # Returns
2351///
2352/// - `bool` - `true` when cached position, logical CSS dimensions, or DPR changed.
2353#[cfg(target_arch = "wasm32")]
2354fn web_refresh_cached_viewport(win: &Window, canvas: &HtmlCanvasElement) -> bool {
2355    let rect: DomRect = canvas.get_bounding_client_rect();
2356    let left: f64 = rect.left();
2357    let top: f64 = rect.top();
2358    let (win_w, win_h): (f64, f64) = web_read_window_css_viewport(win);
2359    let css_w: f64 = if rect.width().is_finite() && rect.width() >= 64.0 {
2360        rect.width()
2361    } else {
2362        win_w
2363    };
2364    let css_h: f64 = if rect.height().is_finite() && rect.height() >= 64.0 {
2365        rect.height()
2366    } else {
2367        win_h
2368    };
2369    let dpr_raw: f64 = win.device_pixel_ratio();
2370    let dpr: f32 = if dpr_raw.is_finite() && dpr_raw > 0.0 {
2371        (dpr_raw as f32).clamp(WEB_DPR_MIN, WEB_DPR_MAX)
2372    } else {
2373        1.0
2374    };
2375    let prev: (f64, f64, f64, f64, f32) = WEB_CACHED_VIEWPORT.with(Cell::get);
2376    let changed: bool = (prev.0 - left).abs() > 0.25
2377        || (prev.1 - top).abs() > 0.25
2378        || (prev.2 - css_w).abs() > 0.25
2379        || (prev.3 - css_h).abs() > 0.25
2380        || (prev.4 - dpr).abs() > 0.005;
2381    if changed {
2382        WEB_CACHED_VIEWPORT.with(|cell: &Cell<(f64, f64, f64, f64, f32)>| {
2383            cell.set((left, top, css_w, css_h, dpr));
2384        });
2385        WEB_VIEWPORT_DIRTY.with(|flag: &Cell<bool>| flag.set(true));
2386    }
2387    changed
2388}
2389
2390/// Applies the cached `(css_w, css_h, dpr)` metrics in `WEB_CACHED_VIEWPORT` to the `<canvas>` backing store and `App`.
2391///
2392/// # Arguments
2393///
2394/// - `&HtmlCanvasElement` - Target full-viewport canvas element.
2395///
2396/// # Returns
2397///
2398/// - `bool` - `true` when physical dimensions or DPI scale changed and the viewport was updated.
2399#[cfg(target_arch = "wasm32")]
2400fn web_apply_cached_viewport(canvas: &HtmlCanvasElement) -> bool {
2401    let (_, _, css_w, css_h, dpr): (f64, f64, f64, f64, f32) = WEB_CACHED_VIEWPORT.with(Cell::get);
2402    let dpr_f64: f64 = f64::from(dpr);
2403    let est_w: u32 = (css_w * dpr_f64)
2404        .round()
2405        .clamp(1.0, WEB_CANVAS_MAX_PHYS_DIM) as u32;
2406    let est_h: u32 = (css_h * dpr_f64)
2407        .round()
2408        .clamp(1.0, WEB_CANVAS_MAX_PHYS_DIM) as u32;
2409    let (obs_w, obs_h): (u32, u32) = WEB_OBSERVED_PHYS_SIZE.with(Cell::get);
2410    let has_obs: bool = obs_w >= 64 && obs_h >= 64;
2411    let matches_obs: bool = has_obs && obs_w.abs_diff(est_w) <= 2 && obs_h.abs_diff(est_h) <= 2;
2412    let (phys_w, phys_h): (u32, u32) = if matches_obs {
2413        (obs_w, obs_h)
2414    } else {
2415        (est_w, est_h)
2416    };
2417    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2418        let Ok(mut borrow) = slot.try_borrow_mut() else {
2419            return false;
2420        };
2421        let Some((app, _)) = borrow.as_mut() else {
2422            return false;
2423        };
2424        let ws: WindowState = app.get_window_state();
2425        let size_diff: bool = ws.get_physical_width() != phys_w
2426            || ws.get_physical_height() != phys_h
2427            || (ws.get_scale_factor() - dpr).abs() > 0.005
2428            || canvas.width() != phys_w
2429            || canvas.height() != phys_h;
2430        if !size_diff {
2431            return false;
2432        }
2433        if canvas.width() != phys_w {
2434            canvas.set_width(phys_w);
2435        }
2436        if canvas.height() != phys_h {
2437            canvas.set_height(phys_h);
2438        }
2439        app.set_exact_physical_viewport(phys_w, phys_h, dpr);
2440        true
2441    })
2442}
2443
2444/// Re-queries browser CSS `env(safe-area-inset-*)` values and dispatches `WindowEvent::SafeAreaChanged` when changed.
2445///
2446/// # Returns
2447///
2448/// - `bool` - `true` when effective safe-area insets changed and require a relayout frame.
2449#[cfg(target_arch = "wasm32")]
2450fn web_sync_safe_area() -> bool {
2451    let measured: SafeAreaInsets = web_query_safe_area_insets();
2452    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2453        let Ok(mut borrow) = slot.try_borrow_mut() else {
2454            return false;
2455        };
2456        let Some((app, _)) = borrow.as_mut() else {
2457            return false;
2458        };
2459        let effective: SafeAreaInsets = if app.is_immersive_fullscreen() {
2460            SafeAreaInsets::default()
2461        } else {
2462            measured
2463        };
2464        let current: SafeAreaInsets = app.get_context().get_safe_area().get_untracked();
2465        if current == effective {
2466            return false;
2467        }
2468        let wid: WindowId = app.get_window_state().get_id();
2469        app.dispatch_window_event(WindowEvent::SafeAreaChanged(wid, effective));
2470        true
2471    })
2472}
2473
2474/// Reports measured browser `requestAnimationFrame` refresh cadence into the active `App` runtime.
2475///
2476/// # Arguments
2477///
2478/// - `f32` - Measured browser presentation cadence in Hertz.
2479#[cfg(target_arch = "wasm32")]
2480fn web_report_host_refresh_rate(measured_hz: f32) {
2481    let mut needs_redraw: bool = false;
2482    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2483        if let Ok(mut borrow) = slot.try_borrow_mut()
2484            && let Some((app, _)) = borrow.as_mut()
2485        {
2486            let prev_fps: f32 = app.get_context().get_live_fps().get_untracked();
2487            app.report_host_refresh_rate(measured_hz);
2488            let next_fps: f32 = app.get_context().get_live_fps().get_untracked();
2489            if (next_fps - prev_fps).abs() >= 1.0 {
2490                needs_redraw = true;
2491            }
2492        }
2493    });
2494    if needs_redraw {
2495        web_mark_needs_frame();
2496    }
2497}
2498
2499/// Steps one coalesced WebAssembly frame during `requestAnimationFrame` with accurate real-time `dt_secs`.
2500///
2501/// # Arguments
2502///
2503/// - `f32` - Elapsed seconds since the previous animation frame.
2504///
2505/// # Returns
2506///
2507/// - `u64` - Rendered frame hash.
2508#[cfg(target_arch = "wasm32")]
2509fn web_flush_frame(dt_secs: f32) -> u64 {
2510    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2511        let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2512            Ok(guard) => guard,
2513            Err(_) => return 0,
2514        };
2515        let Some((app, state)) = borrow.as_mut() else {
2516            return 0;
2517        };
2518        let coord: ShowcaseWebDualCanvasCoordinator = web_dual_canvas_snapshot();
2519        state.sync_adaptive_from_web_coordinator(app, &coord);
2520        let hash: u64 = app
2521            .step_game_frame(dt_secs)
2522            .map(|stats: FrameStats| stats.get_frame_hash())
2523            .unwrap_or(0);
2524        state.sync_adaptive_from_web_coordinator(app, &coord);
2525        let pump: bool = app.should_pump_frames();
2526        WEB_SHOULD_PUMP.with(|flag: &Cell<bool>| flag.set(pump));
2527        hash
2528    })
2529}
2530
2531/// Initializes the persistent WebAssembly showcase on the browser `<canvas>` and renders the first frame.
2532///
2533/// # Returns
2534///
2535/// - `u64` - Deterministic frame hash produced by the initial render, or `0` on startup failure.
2536#[cfg(target_arch = "wasm32")]
2537#[wasm_bindgen]
2538pub fn euv_example_web_start() -> u64 {
2539    reset_reactive_runtime();
2540    register_frame_wakeup(web_mark_needs_frame);
2541    let (left, top, css_w, css_h, dpr): (f64, f64, f64, f64, f32) = web_query_initial_viewport();
2542    WEB_CACHED_VIEWPORT.with(|cell: &Cell<(f64, f64, f64, f64, f32)>| {
2543        cell.set((left, top, css_w, css_h, dpr));
2544    });
2545    WEB_VIEWPORT_DIRTY.with(|flag: &Cell<bool>| flag.set(false));
2546    let logical_w: u32 = css_w.round().max(64.0) as u32;
2547    let logical_h: u32 = css_h.round().max(64.0) as u32;
2548    let phys_w: u32 = (css_w * f64::from(dpr))
2549        .round()
2550        .clamp(1.0, WEB_CANVAS_MAX_PHYS_DIM) as u32;
2551    let phys_h: u32 = (css_h * f64::from(dpr))
2552        .round()
2553        .clamp(1.0, WEB_CANVAS_MAX_PHYS_DIM) as u32;
2554    if let Some(win) = window()
2555        && let Some(doc) = win.document()
2556        && let Ok(Some(el)) = doc.query_selector(WEB_SELECTOR_CANVAS)
2557        && let Ok(canvas) = el.dyn_into::<HtmlCanvasElement>()
2558    {
2559        if canvas.width() != phys_w {
2560            canvas.set_width(phys_w);
2561        }
2562        if canvas.height() != phys_h {
2563            canvas.set_height(phys_h);
2564        }
2565    }
2566    match create_showcase_app_with_viewport(false, RenderMode::Auto, logical_w, logical_h, dpr) {
2567        Ok((mut app, state)) => {
2568            app.set_exact_physical_viewport(phys_w, phys_h, dpr);
2569            if let Some(win) = window()
2570                && let Ok(hash_str) = win.location().hash()
2571            {
2572                let initial: String =
2573                    resolve_web_hash_route(&hash_str, Some(state.get_dynamic_hub()));
2574                state.get_router().replace(&initial);
2575                let _: bool = state.get_route().set_if_changed(initial);
2576            }
2577            let route_watch: Signal<String> = state.get_route();
2578            let hub_watch: DynamicUpdateHub = state.get_dynamic_hub().clone();
2579            let (hash_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
2580                Effect::new(move || {
2581                    let r: String = route_watch.get();
2582                    if WEB_SYNCING_FROM_HISTORY.with(Cell::get) {
2583                        return;
2584                    }
2585                    if let Some(win) = window() {
2586                        let cur_raw: String = win.location().hash().unwrap_or_default();
2587                        let cur_norm: String = resolve_web_hash_route(&cur_raw, Some(&hub_watch));
2588                        if cur_norm != r {
2589                            let target_hash: String = format!("#{r}");
2590                            let _: Result<(), JsValue> = win.location().set_hash(&target_hash);
2591                        }
2592                    }
2593                })
2594            });
2595            let root_id: NodeId = app
2596                .get_scene()
2597                .with_read(SceneTree::get_root, NodeId::default());
2598            app.get_scene().with_write(
2599                |tree: &mut SceneTree| {
2600                    tree.attach_scope(root_id, hash_scope);
2601                },
2602                (),
2603            );
2604            let hash: u64 = app
2605                .step_frame()
2606                .map(|stats: FrameStats| stats.get_frame_hash())
2607                .unwrap_or(0);
2608            let coord: ShowcaseWebDualCanvasCoordinator = web_dual_canvas_snapshot();
2609            state.sync_adaptive_from_web_coordinator(&mut app, &coord);
2610            let pump: bool = app.should_pump_frames();
2611            WEB_SHOULD_PUMP.with(|flag: &Cell<bool>| flag.set(pump));
2612            WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2613                if let Ok(mut borrow) = slot.try_borrow_mut() {
2614                    *borrow = Some((app, state));
2615                }
2616            });
2617            hash
2618        }
2619        Err(_) => 0,
2620    }
2621}
2622
2623/// Switches the active route in the persistent WebAssembly showcase and renders immediately.
2624///
2625/// # Arguments
2626///
2627/// - `&str` - Route path to navigate to.
2628///
2629/// # Returns
2630///
2631/// - `u64` - Deterministic frame hash after route navigation.
2632#[cfg(target_arch = "wasm32")]
2633#[wasm_bindgen]
2634pub fn euv_example_render_route(route: &str) -> u64 {
2635    let has_runtime: bool = WEB_SHOWCASE_RUNTIME.with(
2636        |slot: &RefCell<Option<(App, ShowcaseState)>>| matches!(slot.try_borrow(), Ok(guard) if guard.is_some()),
2637    );
2638    if !has_runtime {
2639        let _: u64 = euv_example_web_start();
2640    }
2641    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2642        let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2643            Ok(guard) => guard,
2644            Err(_) => return 0,
2645        };
2646        let Some((app, state)) = borrow.as_mut() else {
2647            return 0;
2648        };
2649        let _: bool = state.get_route().set_if_changed(route.to_string());
2650        app.step_frame()
2651            .map(|stats: FrameStats| stats.get_frame_hash())
2652            .unwrap_or(0)
2653    })
2654}
2655
2656/// Dispatches a browser pointer move event into the persistent WebAssembly showcase and re-renders.
2657///
2658/// # Arguments
2659///
2660/// - `f32` - Logical X coordinate inside the canvas.
2661/// - `f32` - Logical Y coordinate inside the canvas.
2662///
2663/// # Returns
2664///
2665/// - `u64` - Rendered frame hash.
2666#[cfg(target_arch = "wasm32")]
2667#[wasm_bindgen]
2668pub fn euv_web_pointer_move(x: f32, y: f32) -> u64 {
2669    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2670        let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2671            Ok(guard) => guard,
2672            Err(_) => return 0,
2673        };
2674        let Some((app, _)) = borrow.as_mut() else {
2675            return 0;
2676        };
2677        let wid: WindowId = app.get_window_state().get_id();
2678        app.dispatch_window_event(WindowEvent::PointerMove(wid, PointerEvent::mouse(x, y)));
2679        app.step_frame()
2680            .map(|stats: FrameStats| stats.get_frame_hash())
2681            .unwrap_or(0)
2682    })
2683}
2684
2685/// Dispatches a browser pointer press event into the persistent WebAssembly showcase and re-renders.
2686///
2687/// # Arguments
2688///
2689/// - `f32` - Logical X coordinate inside the canvas.
2690/// - `f32` - Logical Y coordinate inside the canvas.
2691///
2692/// # Returns
2693///
2694/// - `u64` - Rendered frame hash.
2695#[cfg(target_arch = "wasm32")]
2696#[wasm_bindgen]
2697pub fn euv_web_pointer_down(x: f32, y: f32) -> u64 {
2698    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2699        let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2700            Ok(guard) => guard,
2701            Err(_) => return 0,
2702        };
2703        let Some((app, _)) = borrow.as_mut() else {
2704            return 0;
2705        };
2706        let wid: WindowId = app.get_window_state().get_id();
2707        app.dispatch_window_event(WindowEvent::PointerDown(wid, PointerEvent::mouse(x, y)));
2708        app.step_frame()
2709            .map(|stats: FrameStats| stats.get_frame_hash())
2710            .unwrap_or(0)
2711    })
2712}
2713
2714/// Dispatches a browser pointer release (and click) event into the persistent WebAssembly showcase and re-renders.
2715///
2716/// # Arguments
2717///
2718/// - `f32` - Logical X coordinate inside the canvas.
2719/// - `f32` - Logical Y coordinate inside the canvas.
2720///
2721/// # Returns
2722///
2723/// - `u64` - Rendered frame hash.
2724#[cfg(target_arch = "wasm32")]
2725#[wasm_bindgen]
2726pub fn euv_web_pointer_up(x: f32, y: f32) -> u64 {
2727    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2728        let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2729            Ok(guard) => guard,
2730            Err(_) => return 0,
2731        };
2732        let Some((app, _)) = borrow.as_mut() else {
2733            return 0;
2734        };
2735        let wid: WindowId = app.get_window_state().get_id();
2736        app.dispatch_window_event(WindowEvent::PointerUp(wid, PointerEvent::mouse(x, y)));
2737        app.step_frame()
2738            .map(|stats: FrameStats| stats.get_frame_hash())
2739            .unwrap_or(0)
2740    })
2741}
2742
2743/// Dispatches a browser wheel scroll delta into the persistent WebAssembly showcase and re-renders.
2744///
2745/// # Arguments
2746///
2747/// - `f32` - Horizontal scroll delta.
2748/// - `f32` - Vertical scroll delta.
2749///
2750/// # Returns
2751///
2752/// - `u64` - Rendered frame hash.
2753#[cfg(target_arch = "wasm32")]
2754#[wasm_bindgen]
2755pub fn euv_web_scroll(dx: f32, dy: f32) -> u64 {
2756    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2757        let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2758            Ok(guard) => guard,
2759            Err(_) => return 0,
2760        };
2761        let Some((app, _)) = borrow.as_mut() else {
2762            return 0;
2763        };
2764        let wid: WindowId = app.get_window_state().get_id();
2765        app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(dx, dy)));
2766        app.step_frame()
2767            .map(|stats: FrameStats| stats.get_frame_hash())
2768            .unwrap_or(0)
2769    })
2770}
2771
2772/// Dispatches a browser keyboard press and optional text input into the persistent WebAssembly showcase.
2773///
2774/// # Arguments
2775///
2776/// - `&str` - DOM `KeyboardEvent.key` string (e.g. `"Backspace"`, `"ArrowRight"`, `"a"`).
2777///
2778/// # Returns
2779///
2780/// - `u64` - Rendered frame hash.
2781#[cfg(target_arch = "wasm32")]
2782#[wasm_bindgen]
2783pub fn euv_web_key_down(key: &str) -> u64 {
2784    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2785        let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2786            Ok(guard) => guard,
2787            Err(_) => return 0,
2788        };
2789        let Some((app, state)) = borrow.as_mut() else {
2790            return 0;
2791        };
2792        let wid: WindowId = app.get_window_state().get_id();
2793        let code: KeyCode = match key {
2794            WEB_KEY_ENTER => KeyCode::Enter,
2795            WEB_KEY_BACKSPACE => KeyCode::Backspace,
2796            WEB_KEY_DELETE => KeyCode::Delete,
2797            WEB_KEY_ESCAPE => KeyCode::Escape,
2798            WEB_KEY_TAB => KeyCode::Tab,
2799            WEB_KEY_SPACE => KeyCode::Space,
2800            WEB_KEY_ARROW_LEFT => KeyCode::ArrowLeft,
2801            WEB_KEY_ARROW_RIGHT => KeyCode::ArrowRight,
2802            WEB_KEY_ARROW_UP => KeyCode::ArrowUp,
2803            WEB_KEY_ARROW_DOWN => KeyCode::ArrowDown,
2804            other => other
2805                .chars()
2806                .next()
2807                .map(KeyCode::Character)
2808                .unwrap_or(KeyCode::Unknown),
2809        };
2810        let key_ev: WindowEvent =
2811            WindowEvent::KeyDown(wid, KeyEvent::new(code, Modifiers::default(), false));
2812        state.get_game_host().ingest_event(&key_ev);
2813        app.dispatch_window_event(key_ev);
2814        if key.chars().count() == 1 {
2815            app.dispatch_window_event(WindowEvent::TextInput(wid, key.to_string()));
2816        }
2817        app.step_frame()
2818            .map(|stats: FrameStats| stats.get_frame_hash())
2819            .unwrap_or(0)
2820    })
2821}
2822
2823/// Advances the game physics clock by `dt_secs` when viewing the Game Engine route and renders a frame.
2824///
2825/// # Arguments
2826///
2827/// - `f32` - Elapsed seconds since the previous animation frame.
2828///
2829/// # Returns
2830///
2831/// - `u64` - Rendered frame hash.
2832#[cfg(target_arch = "wasm32")]
2833#[wasm_bindgen]
2834pub fn euv_web_tick(dt_secs: f32) -> u64 {
2835    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2836        let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2837            Ok(guard) => guard,
2838            Err(_) => return 0,
2839        };
2840        let Some((app, state)) = borrow.as_mut() else {
2841            return 0;
2842        };
2843        if !app.should_pump_frames() {
2844            return app.get_renderer().get_last_stats().get_frame_hash();
2845        }
2846        let cur_route: String = state.get_route().get_untracked();
2847        let on_game: bool =
2848            cur_route == ROUTE_GAME || cur_route == ROUTE_GAME_3D || cur_route == ROUTE_WATER;
2849        if on_game || app.has_active_animations() {
2850            return app
2851                .step_game_frame(dt_secs)
2852                .map(|stats: FrameStats| stats.get_frame_hash())
2853                .unwrap_or(0);
2854        }
2855        app.get_renderer().get_last_stats().get_frame_hash()
2856    })
2857}
2858
2859/// Resizes the persistent WebAssembly showcase canvas and viewport immediately and re-renders.
2860///
2861/// # Arguments
2862///
2863/// - `u32` - New logical viewport width in CSS pixels.
2864/// - `u32` - New logical viewport height in CSS pixels.
2865/// - `f32` - Active browser `window.devicePixelRatio`.
2866///
2867/// # Returns
2868///
2869/// - `u64` - Deterministic frame hash produced by the resized render.
2870#[cfg(target_arch = "wasm32")]
2871#[wasm_bindgen]
2872pub fn euv_web_resize(width: u32, height: u32, dpr: f32) -> u64 {
2873    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2874        let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2875            Ok(guard) => guard,
2876            Err(_) => return 0,
2877        };
2878        let Some((app, _)) = borrow.as_mut() else {
2879            return 0;
2880        };
2881        let w: u32 = width.max(64);
2882        let h: u32 = height.max(64);
2883        let scale: f32 = if dpr.is_finite() && dpr > 0.0 {
2884            dpr.clamp(WEB_DPR_MIN, WEB_DPR_MAX)
2885        } else {
2886            1.0
2887        };
2888        let phys_w: u32 = ((w as f64) * (scale as f64))
2889            .round()
2890            .clamp(1.0, WEB_CANVAS_MAX_PHYS_DIM) as u32;
2891        let phys_h: u32 = ((h as f64) * (scale as f64))
2892            .round()
2893            .clamp(1.0, WEB_CANVAS_MAX_PHYS_DIM) as u32;
2894        WEB_OBSERVED_PHYS_SIZE.with(|cell: &Cell<(u32, u32)>| cell.set((0, 0)));
2895        let (prev_l, prev_t, _, _, _): (f64, f64, f64, f64, f32) =
2896            WEB_CACHED_VIEWPORT.with(Cell::get);
2897        WEB_CACHED_VIEWPORT.with(|cell: &Cell<(f64, f64, f64, f64, f32)>| {
2898            cell.set((prev_l, prev_t, f64::from(w), f64::from(h), scale));
2899        });
2900        WEB_VIEWPORT_DIRTY.with(|flag: &Cell<bool>| flag.set(false));
2901        if let Some(win) = window()
2902            && let Some(doc) = win.document()
2903            && let Ok(Some(el)) = doc.query_selector(WEB_SELECTOR_CANVAS)
2904            && let Ok(canvas) = el.dyn_into::<HtmlCanvasElement>()
2905        {
2906            if canvas.width() != phys_w {
2907                canvas.set_width(phys_w);
2908            }
2909            if canvas.height() != phys_h {
2910                canvas.set_height(phys_h);
2911            }
2912        }
2913        app.set_exact_physical_viewport(phys_w, phys_h, scale);
2914        app.step_frame()
2915            .map(|stats: FrameStats| stats.get_frame_hash())
2916            .unwrap_or(0)
2917    })
2918}
2919
2920/// Dispatches a cross-platform `euv://automation/...` protocol URI against `app` and `state` in dev/test builds.
2921///
2922/// # Arguments
2923///
2924/// - `&mut App` - Live showcase application instance.
2925/// - `&ShowcaseState` - Shared reactive showcase state.
2926/// - `&str` - Raw `euv://automation/...` protocol URI.
2927///
2928/// # Returns
2929///
2930/// - `Option<String>` - Serialized `AiSchemaResponse` JSON if `uri` is a valid automation URI.
2931#[cfg(any(debug_assertions, test))]
2932#[must_use]
2933pub fn dispatch_automation_uri(app: &mut App, state: &ShowcaseState, uri: &str) -> Option<String> {
2934    let hooks: AiAppHooks = state.build_ai_hooks();
2935    AiSchemaProtocol::handle_uri_with_hooks(app, uri, Some(&hooks))
2936}
2937
2938/// Attaches `window.__euv_automation(json)` and `window.__euv_automation_uri(uri)` in dev Web/WebView builds (compiled out in release).
2939///
2940/// # Arguments
2941///
2942/// - `&Window` - Active browser or WebView window object.
2943#[cfg(all(debug_assertions, target_arch = "wasm32"))]
2944fn web_attach_dev_automation_bridge(win: &Window) {
2945    let on_json: Closure<dyn FnMut(String) -> String> =
2946        Closure::wrap(Box::new(|req_json: String| euv_dev_ai_schema(&req_json))
2947            as Box<dyn FnMut(String) -> String>);
2948    let _: Result<bool, JsValue> = Reflect::set(
2949        win.as_ref(),
2950        &JsValue::from_str(WEB_PROP_EUV_AUTOMATION),
2951        on_json.as_ref(),
2952    );
2953    on_json.forget();
2954    let on_uri: Closure<dyn FnMut(String) -> String> =
2955        Closure::wrap(
2956            Box::new(|uri: String| euv_dev_ai_uri(&uri)) as Box<dyn FnMut(String) -> String>
2957        );
2958    let _: Result<bool, JsValue> = Reflect::set(
2959        win.as_ref(),
2960        &JsValue::from_str(WEB_PROP_EUV_AUTOMATION_URI),
2961        on_uri.as_ref(),
2962    );
2963    on_uri.forget();
2964}
2965
2966/// Executes an AI Schema v1/v2 JSON request against the live WebAssembly showcase in dev builds only (stripped in release).
2967///
2968/// # Arguments
2969///
2970/// - `&str` - Serialized `AiSchemaRequest` JSON string.
2971///
2972/// # Returns
2973///
2974/// - `String` - Serialized `AiSchemaResponse` JSON string.
2975#[cfg(all(debug_assertions, target_arch = "wasm32"))]
2976#[wasm_bindgen]
2977pub fn euv_dev_ai_schema(request_json: &str) -> String {
2978    let out: String = WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
2979        let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
2980            Ok(guard) => guard,
2981            Err(_) => return String::new(),
2982        };
2983        let Some((app, state)) = borrow.as_mut() else {
2984            return String::new();
2985        };
2986        let hooks: AiAppHooks = state.build_ai_hooks();
2987        AiSchemaProtocol::handle_json_with_hooks(app, request_json, Some(&hooks))
2988    });
2989    web_mark_needs_frame();
2990    out
2991}
2992
2993/// Executes a cross-platform `euv://automation/...` protocol URI against the live WebAssembly showcase in dev builds only (stripped in release).
2994///
2995/// # Arguments
2996///
2997/// - `&str` - Raw `euv://automation/...` URI string.
2998///
2999/// # Returns
3000///
3001/// - `String` - Serialized `AiSchemaResponse` JSON string (or empty string if unrecognized).
3002#[cfg(all(debug_assertions, target_arch = "wasm32"))]
3003#[wasm_bindgen]
3004pub fn euv_dev_ai_uri(uri: &str) -> String {
3005    let out: String = WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
3006        let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
3007            Ok(guard) => guard,
3008            Err(_) => return String::new(),
3009        };
3010        let Some((app, state)) = borrow.as_mut() else {
3011            return String::new();
3012        };
3013        let hooks: AiAppHooks = state.build_ai_hooks();
3014        AiSchemaProtocol::handle_uri_with_hooks(app, uri, Some(&hooks)).unwrap_or_default()
3015    });
3016    web_mark_needs_frame();
3017    out
3018}
3019
3020/// Returns the active route string of the persistent WebAssembly showcase for telemetry.
3021///
3022/// # Returns
3023///
3024/// - `String` - Current active route path.
3025#[cfg(target_arch = "wasm32")]
3026#[wasm_bindgen]
3027pub fn euv_web_current_route() -> String {
3028    WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
3029        match slot.try_borrow() {
3030            Ok(guard) => guard
3031                .as_ref()
3032                .map(|(_, state): &(App, ShowcaseState)| state.get_route().get_untracked())
3033                .unwrap_or_default(),
3034            Err(_) => String::new(),
3035        }
3036    })
3037}
3038
3039/// Escapes `raw` for safe inclusion inside a JSON string literal.
3040///
3041/// # Arguments
3042///
3043/// - `&str` - Arbitrary UTF-8 string to escape.
3044///
3045/// # Returns
3046///
3047/// - `String` - JSON-escaped content without surrounding quotes.
3048#[cfg(target_arch = "wasm32")]
3049fn host_json_escape(raw: &str) -> String {
3050    let mut out: String = String::with_capacity(raw.len() + 8);
3051    for ch in raw.chars() {
3052        match ch {
3053            '"' => out.push_str("\\\""),
3054            '\\' => out.push_str("\\\\"),
3055            '\n' => out.push_str("\\n"),
3056            '\r' => out.push_str("\\r"),
3057            '\t' => out.push_str("\\t"),
3058            c if (c as u32) < 0x20 => out.push(' '),
3059            c => out.push(c),
3060        }
3061    }
3062    out
3063}
3064
3065/// Enqueues a raw JSON command object for the external MiniApp/QuickApp/Wearable JS host bridge.
3066///
3067/// # Arguments
3068///
3069/// - `String` - Serialized JSON object string.
3070#[cfg(target_arch = "wasm32")]
3071fn host_push_command_json(cmd_json: String) {
3072    HOST_OUTBOUND_COMMANDS.with(|queue: &RefCell<Vec<String>>| {
3073        if let Ok(mut borrow) = queue.try_borrow_mut() {
3074            borrow.push(cmd_json);
3075        }
3076    });
3077}
3078
3079/// Captures core `NATIVE_ACTION_*` bridge requests into the JSON host command queue for non-DOM JS runtimes.
3080///
3081/// # Arguments
3082///
3083/// - `&str` - Canonical `NATIVE_ACTION_*` kind.
3084/// - `&str` - Primary action argument.
3085/// - `&str` - Secondary action argument.
3086///
3087/// # Returns
3088///
3089/// - `bool` - `true` when queued for the external host bridge.
3090#[cfg(target_arch = "wasm32")]
3091fn host_native_action_bridge(kind: &str, arg1: &str, arg2: &str) -> bool {
3092    if kind == NATIVE_ACTION_CLIPBOARD {
3093        let escaped: String = host_json_escape(arg2);
3094        host_push_command_json(format!(
3095            "{{\"kind\":\"{HOST_CMD_SET_CLIPBOARD}\",\"value\":\"{escaped}\"}}"
3096        ));
3097        return true;
3098    }
3099    if kind == NATIVE_ACTION_IME {
3100        let enabled: bool = arg1 == WEB_IME_ACTION_SHOW;
3101        let rect_escaped: String = host_json_escape(arg2);
3102        host_push_command_json(format!(
3103            "{{\"kind\":\"{HOST_CMD_SHOW_KEYBOARD}\",\"enabled\":{enabled},\"rect\":\"{rect_escaped}\"}}"
3104        ));
3105        return true;
3106    }
3107    if kind == NATIVE_ACTION_HAPTIC {
3108        host_push_command_json(format!("{{\"kind\":\"{HOST_CMD_VIBRATE_SHORT}\"}}"));
3109        return true;
3110    }
3111    if kind == NATIVE_ACTION_OPEN_URL {
3112        if !is_valid_external_url(arg1) {
3113            return false;
3114        }
3115        let escaped: String = host_json_escape(arg1.trim());
3116        host_push_command_json(format!(
3117            "{{\"kind\":\"{HOST_CMD_OPEN_URL}\",\"url\":\"{escaped}\"}}"
3118        ));
3119        return true;
3120    }
3121    if kind == NATIVE_ACTION_TOAST || kind == NATIVE_ACTION_NOTIFY {
3122        let msg: &str = if !arg2.is_empty() { arg2 } else { arg1 };
3123        let escaped: String = host_json_escape(msg);
3124        host_push_command_json(format!(
3125            "{{\"kind\":\"{HOST_CMD_SHOW_TOAST}\",\"message\":\"{escaped}\"}}"
3126        ));
3127        return true;
3128    }
3129    if kind == NATIVE_ACTION_FULLSCREEN {
3130        let enabled: bool = arg1 == WEB_FS_ACTION_ON;
3131        host_push_command_json(format!(
3132            "{{\"kind\":\"{HOST_CMD_SET_FULLSCREEN}\",\"enabled\":{enabled}}}"
3133        ));
3134        return true;
3135    }
3136    if kind == NATIVE_ACTION_EXIT {
3137        host_push_command_json(format!(
3138            "{{\"kind\":\"{HOST_CMD_NAVIGATE_BACK}\",\"delta\":1}}"
3139        ));
3140        return true;
3141    }
3142    let k_esc: String = host_json_escape(kind);
3143    let a1_esc: String = host_json_escape(arg1);
3144    let a2_esc: String = host_json_escape(arg2);
3145    host_push_command_json(format!(
3146        "{{\"kind\":\"{k_esc}\",\"arg1\":\"{a1_esc}\",\"arg2\":\"{a2_esc}\"}}"
3147    ));
3148    true
3149}
3150
3151/// Marks the active zero-DOM canvas host runtime dirty so the next `euv_host_step` rasterizes an updated frame.
3152#[cfg(target_arch = "wasm32")]
3153fn host_mark_dirty() {
3154    HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
3155        if let Ok(mut borrow) = slot.try_borrow_mut()
3156            && let Some(rt) = borrow.as_mut()
3157        {
3158            rt.set_dirty(true);
3159        }
3160    });
3161}
3162
3163/// Computes and stores the tightest physical pixel bounding box from `app.last_frame_damage()` onto `rt`.
3164///
3165/// # Arguments
3166///
3167/// - `&mut HostCanvasRuntime` - Active zero-DOM host runtime.
3168/// - `bool` - When `true`, forces full framebuffer damage bounds.
3169#[cfg(target_arch = "wasm32")]
3170fn host_sync_dirty_rect(rt: &mut HostCanvasRuntime, force_full: bool) {
3171    let (phys_w, phys_h): (u32, u32) = rt
3172        .get_app()
3173        .get_renderer()
3174        .framebuffer()
3175        .map(|fb: &Framebuffer| (fb.get_width(), fb.get_height()))
3176        .unwrap_or((0, 0));
3177    if phys_w == 0 || phys_h == 0 {
3178        rt.set_dirty_x(0)
3179            .set_dirty_y(0)
3180            .set_dirty_w(0)
3181            .set_dirty_h(0);
3182        return;
3183    }
3184    let damage: DamageRegion = rt.get_app().last_frame_damage();
3185    if force_full || rt.get_force_full_dirty() || damage.get_full_damage() {
3186        rt.set_force_full_dirty(false)
3187            .set_dirty_x(0)
3188            .set_dirty_y(0)
3189            .set_dirty_w(phys_w)
3190            .set_dirty_h(phys_h);
3191        return;
3192    }
3193    let rects: Vec<PixelDirtyRect> = damage_region_to_pixel_dirty_rects(damage, phys_w, phys_h);
3194    if rects.is_empty() {
3195        rt.set_dirty_x(0)
3196            .set_dirty_y(0)
3197            .set_dirty_w(phys_w)
3198            .set_dirty_h(phys_h);
3199        return;
3200    }
3201    let mut min_x: u32 = phys_w;
3202    let mut min_y: u32 = phys_h;
3203    let mut max_x: u32 = 0;
3204    let mut max_y: u32 = 0;
3205    for rect in rects.iter() {
3206        let rx: u32 = rect.get_x();
3207        let ry: u32 = rect.get_y();
3208        let rx2: u32 = rx.saturating_add(rect.get_width()).min(phys_w);
3209        let ry2: u32 = ry.saturating_add(rect.get_height()).min(phys_h);
3210        if rx < min_x {
3211            min_x = rx;
3212        }
3213        if ry < min_y {
3214            min_y = ry;
3215        }
3216        if rx2 > max_x {
3217            max_x = rx2;
3218        }
3219        if ry2 > max_y {
3220            max_y = ry2;
3221        }
3222    }
3223    if max_x <= min_x || max_y <= min_y {
3224        rt.set_dirty_x(0)
3225            .set_dirty_y(0)
3226            .set_dirty_w(phys_w)
3227            .set_dirty_h(phys_h);
3228    } else {
3229        rt.set_dirty_x(min_x)
3230            .set_dirty_y(min_y)
3231            .set_dirty_w(max_x - min_x)
3232            .set_dirty_h(max_y - min_y);
3233    }
3234}
3235
3236/// Initializes the zero-DOM WebAssembly canvas host runtime for Mini-Programs, QuickApps, and WASM Wearables.
3237///
3238/// # Arguments
3239///
3240/// - `u32` - Host platform category (`1` = `MiniApp`, `2` = `QuickApp`, `3` = `Wearable`).
3241/// - `&str` - Canonical vendor identifier (e.g. `"wechat"`, `"alliance"`, `"vivo-watch"`).
3242/// - `u32` - Initial logical viewport width in dp.
3243/// - `u32` - Initial logical viewport height in dp.
3244/// - `f32` - Active display pixel ratio (`>= 0.5`).
3245/// - `f32` - Top safe-area / capsule inset in logical dp.
3246/// - `f32` - Bottom safe-area inset in logical dp.
3247///
3248/// # Returns
3249///
3250/// - `u64` - Initial deterministic rendered frame hash (`0` on failure).
3251#[cfg(target_arch = "wasm32")]
3252#[wasm_bindgen]
3253pub fn euv_host_init(
3254    host_kind: u32,
3255    vendor: &str,
3256    logical_w: u32,
3257    logical_h: u32,
3258    dpr: f32,
3259    safe_top: f32,
3260    safe_bottom: f32,
3261) -> u64 {
3262    let platform_kind: PlatformKind = match host_kind {
3263        2 => PlatformKind::QuickApp,
3264        3 => PlatformKind::Wearable,
3265        _ => PlatformKind::MiniApp,
3266    };
3267    let clean_w: u32 = logical_w.max(HOST_MIN_VIEWPORT_DIM);
3268    let clean_h: u32 = logical_h.max(HOST_MIN_VIEWPORT_DIM);
3269    let clean_dpr: f32 = if dpr.is_finite() && dpr > 0.0 {
3270        dpr.clamp(0.5, 4.5)
3271    } else {
3272        2.0
3273    };
3274    let safe_area: SafeAreaInsets = SafeAreaInsets::new(
3275        if safe_top.is_finite() {
3276            safe_top.max(0.0)
3277        } else {
3278            0.0
3279        },
3280        0.0,
3281        if safe_bottom.is_finite() {
3282            safe_bottom.max(0.0)
3283        } else {
3284            0.0
3285        },
3286        0.0,
3287    );
3288    HOST_OUTBOUND_COMMANDS.with(|queue: &RefCell<Vec<String>>| {
3289        if let Ok(mut borrow) = queue.try_borrow_mut() {
3290            borrow.clear();
3291        }
3292    });
3293    register_native_action_bridge(host_native_action_bridge);
3294    register_frame_wakeup(host_mark_dirty);
3295    match create_showcase_app_for_platform_with_viewport(
3296        platform_kind,
3297        RenderMode::Software,
3298        clean_w,
3299        clean_h,
3300        clean_dpr,
3301        safe_area,
3302    ) {
3303        Ok((mut app, state)) => {
3304            app.get_mut_renderer()
3305                .get_mut_software()
3306                .set_font_provider(NativeSystemFont::system());
3307            let hash: u64 = app
3308                .step_frame()
3309                .map(|stats: FrameStats| stats.get_frame_hash())
3310                .unwrap_or(0);
3311            let vendor_name: String = if vendor.trim().is_empty() {
3312                HOST_DEFAULT_VENDOR.to_string()
3313            } else {
3314                vendor.trim().to_string()
3315            };
3316            let mut runtime: HostCanvasRuntime = HostCanvasRuntime {
3317                app,
3318                state,
3319                touch_tracker: TouchPointerTracker::default(),
3320                vendor: vendor_name,
3321                platform_kind,
3322                logical_width: clean_w,
3323                logical_height: clean_h,
3324                dpr: clean_dpr,
3325                paused: false,
3326                ambient: false,
3327                dirty: false,
3328                force_full_dirty: true,
3329                dirty_x: 0,
3330                dirty_y: 0,
3331                dirty_w: 0,
3332                dirty_h: 0,
3333                frame_count: 1,
3334                last_frame_hash: hash,
3335                crown_remainder: 0.0,
3336            };
3337            host_sync_dirty_rect(&mut runtime, true);
3338            HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
3339                if let Ok(mut borrow) = slot.try_borrow_mut() {
3340                    *borrow = Some(runtime);
3341                }
3342            });
3343            hash
3344        }
3345        Err(_) => 0,
3346    }
3347}
3348
3349/// Advances animations and rasterizes a new software RGBA8 frame only when dirty, animating, or forced.
3350///
3351/// # Arguments
3352///
3353/// - `f32` - Elapsed seconds since the previous frame tick.
3354/// - `bool` - When `true`, forces a full-viewport rasterization even if idle.
3355///
3356/// # Returns
3357///
3358/// - `u32` - `1` when new pixels were rasterized into linear memory; `0` when skipped for 0% idle CPU.
3359#[cfg(target_arch = "wasm32")]
3360#[wasm_bindgen]
3361pub fn euv_host_step(dt_secs: f32, force_render: bool) -> u32 {
3362    HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
3363        let mut borrow: RefMut<'_, Option<HostCanvasRuntime>> = match slot.try_borrow_mut() {
3364            Ok(guard) => guard,
3365            Err(_) => return 0,
3366        };
3367        let Some(rt) = borrow.as_mut() else {
3368            return 0;
3369        };
3370        if rt.get_paused() && !force_render {
3371            return 0;
3372        }
3373        let dt: f32 = if dt_secs.is_finite() && dt_secs > 0.0 {
3374            dt_secs.clamp(0.001, 0.1)
3375        } else {
3376            1.0 / 60.0
3377        };
3378        let cur_route: String = rt.get_state().get_route().get_untracked();
3379        let on_game: bool =
3380            cur_route == ROUTE_GAME || cur_route == ROUTE_GAME_3D || cur_route == ROUTE_WATER;
3381        let animating: bool = rt.get_app().has_active_animations();
3382        let active_motion: bool = on_game || animating;
3383        let forced_or_dirty: bool = force_render || rt.get_dirty();
3384        let needs_frame: bool = forced_or_dirty || active_motion;
3385        if !needs_frame {
3386            return 0;
3387        }
3388        let res: Result<FrameStats, PlatformError> = if on_game || animating {
3389            rt.get_mut_app().step_game_frame(dt)
3390        } else {
3391            rt.get_mut_app().step_frame()
3392        };
3393        match res {
3394            Ok(stats) => {
3395                rt.set_dirty(false);
3396                rt.set_frame_count(rt.get_frame_count().saturating_add(1));
3397                rt.set_last_frame_hash(stats.get_frame_hash());
3398                host_sync_dirty_rect(rt, force_render);
3399                1
3400            }
3401            Err(_) => 0,
3402        }
3403    })
3404}
3405
3406/// Returns the byte pointer to the current RGBA8 framebuffer inside WASM linear memory for zero-copy JS upload.
3407///
3408/// # Returns
3409///
3410/// - `u32` - Byte offset into `wasmMemory.buffer` (`0` when uninitialized).
3411#[cfg(target_arch = "wasm32")]
3412#[wasm_bindgen]
3413pub fn euv_host_framebuffer_ptr() -> u32 {
3414    HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
3415        slot.try_borrow()
3416            .ok()
3417            .and_then(|guard: Ref<'_, Option<HostCanvasRuntime>>| {
3418                guard.as_ref().and_then(|rt: &HostCanvasRuntime| {
3419                    rt.get_app()
3420                        .get_renderer()
3421                        .framebuffer()
3422                        .map(|fb: &Framebuffer| fb.get_pixels().as_ptr() as usize as u32)
3423                })
3424            })
3425            .unwrap_or(0)
3426    })
3427}
3428
3429/// Returns the byte length of the current RGBA8 framebuffer (`width * height * 4`).
3430///
3431/// # Returns
3432///
3433/// - `u32` - Buffer size in bytes.
3434#[cfg(target_arch = "wasm32")]
3435#[wasm_bindgen]
3436pub fn euv_host_framebuffer_len() -> u32 {
3437    HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
3438        slot.try_borrow()
3439            .ok()
3440            .and_then(|guard: Ref<'_, Option<HostCanvasRuntime>>| {
3441                guard.as_ref().and_then(|rt: &HostCanvasRuntime| {
3442                    rt.get_app()
3443                        .get_renderer()
3444                        .framebuffer()
3445                        .map(|fb: &Framebuffer| fb.get_pixels().len() as u32)
3446                })
3447            })
3448            .unwrap_or(0)
3449    })
3450}
3451
3452/// Returns the physical pixel width of the current RGBA8 framebuffer.
3453///
3454/// # Returns
3455///
3456/// - `u32` - Physical width in pixels.
3457#[cfg(target_arch = "wasm32")]
3458#[wasm_bindgen]
3459pub fn euv_host_framebuffer_width() -> u32 {
3460    HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
3461        slot.try_borrow()
3462            .ok()
3463            .and_then(|guard: Ref<'_, Option<HostCanvasRuntime>>| {
3464                guard.as_ref().and_then(|rt: &HostCanvasRuntime| {
3465                    rt.get_app()
3466                        .get_renderer()
3467                        .framebuffer()
3468                        .map(Framebuffer::get_width)
3469                })
3470            })
3471            .unwrap_or(0)
3472    })
3473}
3474
3475/// Returns the physical pixel height of the current RGBA8 framebuffer.
3476///
3477/// # Returns
3478///
3479/// - `u32` - Physical height in pixels.
3480#[cfg(target_arch = "wasm32")]
3481#[wasm_bindgen]
3482pub fn euv_host_framebuffer_height() -> u32 {
3483    HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
3484        slot.try_borrow()
3485            .ok()
3486            .and_then(|guard: Ref<'_, Option<HostCanvasRuntime>>| {
3487                guard.as_ref().and_then(|rt: &HostCanvasRuntime| {
3488                    rt.get_app()
3489                        .get_renderer()
3490                        .framebuffer()
3491                        .map(Framebuffer::get_height)
3492                })
3493            })
3494            .unwrap_or(0)
3495    })
3496}
3497
3498/// Returns the physical pixel X origin of the latest rendered dirty rectangle.
3499///
3500/// # Returns
3501///
3502/// - `u32` - Dirty rectangle X coordinate in physical pixels.
3503#[cfg(target_arch = "wasm32")]
3504#[wasm_bindgen]
3505pub fn euv_host_dirty_x() -> u32 {
3506    HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
3507        slot.try_borrow()
3508            .ok()
3509            .and_then(|guard: Ref<'_, Option<HostCanvasRuntime>>| {
3510                guard.as_ref().map(HostCanvasRuntime::get_dirty_x)
3511            })
3512            .unwrap_or(0)
3513    })
3514}
3515
3516/// Returns the physical pixel Y origin of the latest rendered dirty rectangle.
3517///
3518/// # Returns
3519///
3520/// - `u32` - Dirty rectangle Y coordinate in physical pixels.
3521#[cfg(target_arch = "wasm32")]
3522#[wasm_bindgen]
3523pub fn euv_host_dirty_y() -> u32 {
3524    HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
3525        slot.try_borrow()
3526            .ok()
3527            .and_then(|guard: Ref<'_, Option<HostCanvasRuntime>>| {
3528                guard.as_ref().map(HostCanvasRuntime::get_dirty_y)
3529            })
3530            .unwrap_or(0)
3531    })
3532}
3533
3534/// Returns the physical pixel width of the latest rendered dirty rectangle.
3535///
3536/// # Returns
3537///
3538/// - `u32` - Dirty rectangle width in physical pixels.
3539#[cfg(target_arch = "wasm32")]
3540#[wasm_bindgen]
3541pub fn euv_host_dirty_w() -> u32 {
3542    HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
3543        slot.try_borrow()
3544            .ok()
3545            .and_then(|guard: Ref<'_, Option<HostCanvasRuntime>>| {
3546                guard.as_ref().map(HostCanvasRuntime::get_dirty_w)
3547            })
3548            .unwrap_or(0)
3549    })
3550}
3551
3552/// Returns the physical pixel height of the latest rendered dirty rectangle.
3553///
3554/// # Returns
3555///
3556/// - `u32` - Dirty rectangle height in physical pixels.
3557#[cfg(target_arch = "wasm32")]
3558#[wasm_bindgen]
3559pub fn euv_host_dirty_h() -> u32 {
3560    HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
3561        slot.try_borrow()
3562            .ok()
3563            .and_then(|guard: Ref<'_, Option<HostCanvasRuntime>>| {
3564                guard.as_ref().map(HostCanvasRuntime::get_dirty_h)
3565            })
3566            .unwrap_or(0)
3567    })
3568}
3569
3570/// Dispatches a touch event from MiniApp, QuickApp, or Wearable JS into EUV via `TouchPointerTracker`.
3571///
3572/// # Arguments
3573///
3574/// - `i32` - Touch phase (`0` = down, `1` = move, `2` = up, `3` = cancel).
3575/// - `i32` - Touch contact identifier.
3576/// - `f32` - Logical X coordinate in dp.
3577/// - `f32` - Logical Y coordinate in dp.
3578///
3579/// # Returns
3580///
3581/// - `bool` - `true` when dispatched to an active runtime.
3582#[cfg(target_arch = "wasm32")]
3583#[wasm_bindgen]
3584pub fn euv_host_touch(phase: i32, pointer_id: i32, logical_x: f32, logical_y: f32) -> bool {
3585    HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
3586        let mut borrow: RefMut<'_, Option<HostCanvasRuntime>> = match slot.try_borrow_mut() {
3587            Ok(guard) => guard,
3588            Err(_) => return false,
3589        };
3590        let Some(rt) = borrow.as_mut() else {
3591            return false;
3592        };
3593        let wid: WindowId = rt.get_app().get_window_state().get_id();
3594        let android_action: i32 = match phase {
3595            0 => ANDROID_ACTION_DOWN,
3596            1 => ANDROID_ACTION_MOVE,
3597            2 => ANDROID_ACTION_UP,
3598            _ => ANDROID_ACTION_CANCEL,
3599        };
3600        let x: f32 = if logical_x.is_finite() {
3601            logical_x
3602        } else {
3603            0.0
3604        };
3605        let y: f32 = if logical_y.is_finite() {
3606            logical_y
3607        } else {
3608            0.0
3609        };
3610        let events: Vec<WindowEvent> = rt.get_mut_touch_tracker().handle_android_motion(
3611            wid,
3612            android_action,
3613            0,
3614            &[(pointer_id, x, y)],
3615        );
3616        for ev in events {
3617            rt.get_mut_app().dispatch_window_event(ev);
3618        }
3619        rt.set_dirty(true);
3620        true
3621    })
3622}
3623
3624/// Dispatches a pointer-positioned scroll delta (wheel or gesture scroll) into the active host runtime.
3625///
3626/// # Arguments
3627///
3628/// - `f32` - Logical X coordinate in dp.
3629/// - `f32` - Logical Y coordinate in dp.
3630/// - `f32` - Horizontal scroll delta in logical dp.
3631/// - `f32` - Vertical scroll delta in logical dp.
3632///
3633/// # Returns
3634///
3635/// - `bool` - `true` when dispatched.
3636#[cfg(target_arch = "wasm32")]
3637#[wasm_bindgen]
3638pub fn euv_host_scroll(logical_x: f32, logical_y: f32, dx: f32, dy: f32) -> bool {
3639    HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
3640        let mut borrow: RefMut<'_, Option<HostCanvasRuntime>> = match slot.try_borrow_mut() {
3641            Ok(guard) => guard,
3642            Err(_) => return false,
3643        };
3644        let Some(rt) = borrow.as_mut() else {
3645            return false;
3646        };
3647        let wid: WindowId = rt.get_app().get_window_state().get_id();
3648        rt.get_mut_app()
3649            .dispatch_window_event(WindowEvent::PointerMove(
3650                wid,
3651                PointerEvent::mouse(logical_x, logical_y),
3652            ));
3653        rt.get_mut_app()
3654            .dispatch_window_event(WindowEvent::Scroll(wid, Point::new(dx, dy)));
3655        rt.set_dirty(true);
3656        true
3657    })
3658}
3659
3660/// Resizes the zero-DOM canvas host viewport and triggers a full redraw on the next step.
3661///
3662/// # Arguments
3663///
3664/// - `u32` - Updated logical viewport width in dp.
3665/// - `u32` - Updated logical viewport height in dp.
3666/// - `f32` - Updated display pixel ratio.
3667///
3668/// # Returns
3669///
3670/// - `bool` - `true` when applied.
3671#[cfg(target_arch = "wasm32")]
3672#[wasm_bindgen]
3673pub fn euv_host_resize(logical_w: u32, logical_h: u32, dpr: f32) -> bool {
3674    HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
3675        let mut borrow: RefMut<'_, Option<HostCanvasRuntime>> = match slot.try_borrow_mut() {
3676            Ok(guard) => guard,
3677            Err(_) => return false,
3678        };
3679        let Some(rt) = borrow.as_mut() else {
3680            return false;
3681        };
3682        let w: u32 = logical_w.max(HOST_MIN_VIEWPORT_DIM);
3683        let h: u32 = logical_h.max(HOST_MIN_VIEWPORT_DIM);
3684        let scale: f32 = if dpr.is_finite() && dpr > 0.0 {
3685            dpr.clamp(0.5, 4.5)
3686        } else {
3687            rt.get_dpr()
3688        };
3689        let phys_w: u32 = ((w as f64) * (scale as f64)).round().max(1.0) as u32;
3690        let phys_h: u32 = ((h as f64) * (scale as f64)).round().max(1.0) as u32;
3691        rt.set_logical_width(w)
3692            .set_logical_height(h)
3693            .set_dpr(scale)
3694            .set_dirty(true)
3695            .set_force_full_dirty(true);
3696        rt.get_mut_app()
3697            .set_exact_physical_viewport(phys_w, phys_h, scale);
3698        true
3699    })
3700}
3701
3702/// Updates safe-area / capsule / circular watch insets on the active zero-DOM canvas host.
3703///
3704/// # Arguments
3705///
3706/// - `f32` - Top safe inset in logical dp.
3707/// - `f32` - Right safe inset in logical dp.
3708/// - `f32` - Bottom safe inset in logical dp.
3709/// - `f32` - Left safe inset in logical dp.
3710///
3711/// # Returns
3712///
3713/// - `bool` - `true` when applied.
3714#[cfg(target_arch = "wasm32")]
3715#[wasm_bindgen]
3716pub fn euv_host_safe_area(top: f32, right: f32, bottom: f32, left: f32) -> bool {
3717    HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
3718        let mut borrow: RefMut<'_, Option<HostCanvasRuntime>> = match slot.try_borrow_mut() {
3719            Ok(guard) => guard,
3720            Err(_) => return false,
3721        };
3722        let Some(rt) = borrow.as_mut() else {
3723            return false;
3724        };
3725        let wid: WindowId = rt.get_app().get_window_state().get_id();
3726        let safe: SafeAreaInsets =
3727            SafeAreaInsets::new(top.max(0.0), right.max(0.0), bottom.max(0.0), left.max(0.0));
3728        rt.get_mut_app()
3729            .dispatch_window_event(WindowEvent::SafeAreaChanged(wid, safe));
3730        rt.get_mut_app()
3731            .dispatch_window_event(WindowEvent::System(SystemEvent::SafeAreaChanged(safe)));
3732        rt.set_dirty(true).set_force_full_dirty(true);
3733        true
3734    })
3735}
3736
3737/// Translates host lifecycle transitions (`onLaunch`, `onShow`, `onHide`, `onUnload`, `onBackPress`) into EUV events.
3738///
3739/// # Arguments
3740///
3741/// - `i32` - Lifecycle tag (`1` = launch, `2` = show, `3` = hide/freeze, `4` = unload/destroy, `5` = back press).
3742/// - `&str` - Optional deep-link URI or query payload.
3743///
3744/// # Returns
3745///
3746/// - `bool` - For `5` (`onBackPress`), `true` when EUV consumed back navigation; otherwise `true` when applied.
3747#[cfg(target_arch = "wasm32")]
3748#[wasm_bindgen]
3749pub fn euv_host_lifecycle(tag: i32, payload: &str) -> bool {
3750    HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
3751        let mut borrow: RefMut<'_, Option<HostCanvasRuntime>> = match slot.try_borrow_mut() {
3752            Ok(guard) => guard,
3753            Err(_) => return false,
3754        };
3755        let Some(rt) = borrow.as_mut() else {
3756            return false;
3757        };
3758        let wid: WindowId = rt.get_app().get_window_state().get_id();
3759        match tag {
3760            1 => {
3761                rt.set_paused(false).set_dirty(true);
3762                if !payload.trim().is_empty() {
3763                    rt.get_mut_app().dispatch_window_event(WindowEvent::System(
3764                        SystemEvent::DeepLink(payload.trim().to_string()),
3765                    ));
3766                }
3767                true
3768            }
3769            2 => {
3770                rt.set_paused(false)
3771                    .set_dirty(true)
3772                    .set_force_full_dirty(true);
3773                rt.get_mut_app()
3774                    .dispatch_window_event(WindowEvent::System(SystemEvent::Appear));
3775                rt.get_mut_app()
3776                    .dispatch_window_event(WindowEvent::System(SystemEvent::Foreground));
3777                if !payload.trim().is_empty() {
3778                    rt.get_mut_app().dispatch_window_event(WindowEvent::System(
3779                        SystemEvent::DeepLink(payload.trim().to_string()),
3780                    ));
3781                }
3782                true
3783            }
3784            3 => {
3785                rt.set_paused(true);
3786                let cancels: Vec<WindowEvent> =
3787                    rt.get_mut_touch_tracker().cancel_all_on_focus_loss(wid);
3788                for ev in cancels {
3789                    rt.get_mut_app().dispatch_window_event(ev);
3790                }
3791                rt.get_mut_app()
3792                    .dispatch_window_event(WindowEvent::System(SystemEvent::Disappear));
3793                rt.get_mut_app()
3794                    .dispatch_window_event(WindowEvent::System(SystemEvent::Background));
3795                true
3796            }
3797            4 => {
3798                rt.set_paused(true);
3799                let cancels: Vec<WindowEvent> =
3800                    rt.get_mut_touch_tracker().cancel_all_on_focus_loss(wid);
3801                for ev in cancels {
3802                    rt.get_mut_app().dispatch_window_event(ev);
3803                }
3804                rt.get_mut_app()
3805                    .dispatch_window_event(WindowEvent::System(SystemEvent::Terminate));
3806                true
3807            }
3808            5 => {
3809                let dismissed_overlay: bool = EuvOverlayStack::dismiss_all() > 0;
3810                let exited_fs: bool = if rt.get_app().is_immersive_fullscreen()
3811                    || is_fullscreen_active()
3812                    || EuvOverlayStack::has_fullscreen()
3813                {
3814                    let _: usize = sync_external_fullscreen_exit();
3815                    rt.get_mut_app().set_immersive_fullscreen(false);
3816                    true
3817                } else {
3818                    false
3819                };
3820                let cur_route: String = rt.get_state().get_route().get_untracked();
3821                let popped_route: bool =
3822                    if !dismissed_overlay && !exited_fs && cur_route != ROUTE_OVERVIEW {
3823                        let _: bool = rt
3824                            .get_state()
3825                            .get_route()
3826                            .set_if_changed(ROUTE_OVERVIEW.to_string());
3827                        true
3828                    } else {
3829                        false
3830                    };
3831                rt.get_mut_app().dispatch_window_event(WindowEvent::KeyDown(
3832                    wid,
3833                    KeyEvent::new(KeyCode::Back, Modifiers::default(), false),
3834                ));
3835                rt.get_mut_app()
3836                    .dispatch_window_event(WindowEvent::System(SystemEvent::BackPressed));
3837                rt.set_dirty(true);
3838                let handled_modal: bool = dismissed_overlay || exited_fs;
3839                handled_modal || popped_route
3840            }
3841            _ => false,
3842        }
3843    })
3844}
3845
3846/// Dispatches UTF-8 IME text input (and optional Enter confirm) from a host `<input>` proxy.
3847///
3848/// # Arguments
3849///
3850/// - `&str` - Committed UTF-8 text chunk.
3851/// - `bool` - When `true`, also dispatches `KeyCode::Enter`.
3852///
3853/// # Returns
3854///
3855/// - `bool` - `true` when dispatched.
3856#[cfg(target_arch = "wasm32")]
3857#[wasm_bindgen]
3858pub fn euv_host_ime(text: &str, confirmed: bool) -> bool {
3859    HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
3860        let mut borrow: RefMut<'_, Option<HostCanvasRuntime>> = match slot.try_borrow_mut() {
3861            Ok(guard) => guard,
3862            Err(_) => return false,
3863        };
3864        let Some(rt) = borrow.as_mut() else {
3865            return false;
3866        };
3867        let wid: WindowId = rt.get_app().get_window_state().get_id();
3868        if !text.is_empty() {
3869            rt.get_mut_app()
3870                .dispatch_window_event(WindowEvent::Ime(wid, ImeEvent::Commit(text.to_string())));
3871            rt.get_mut_app()
3872                .dispatch_window_event(WindowEvent::TextInput(wid, text.to_string()));
3873        }
3874        if confirmed {
3875            rt.get_mut_app().dispatch_window_event(WindowEvent::KeyDown(
3876                wid,
3877                KeyEvent::new(KeyCode::Enter, Modifiers::default(), false),
3878            ));
3879        }
3880        rt.set_dirty(true);
3881        true
3882    })
3883}
3884
3885/// Dispatches a logical key press (e.g. `"Enter"`, `"Backspace"`, `"Escape"`, `"Tab"`, `"ArrowDown"`) into the host runtime.
3886///
3887/// # Arguments
3888///
3889/// - `&str` - Key identifier string.
3890///
3891/// # Returns
3892///
3893/// - `bool` - `true` when dispatched.
3894#[cfg(target_arch = "wasm32")]
3895#[wasm_bindgen]
3896pub fn euv_host_key(key: &str) -> bool {
3897    HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
3898        let mut borrow: RefMut<'_, Option<HostCanvasRuntime>> = match slot.try_borrow_mut() {
3899            Ok(guard) => guard,
3900            Err(_) => return false,
3901        };
3902        let Some(rt) = borrow.as_mut() else {
3903            return false;
3904        };
3905        let wid: WindowId = rt.get_app().get_window_state().get_id();
3906        let code: KeyCode = match key {
3907            WEB_KEY_ENTER => KeyCode::Enter,
3908            WEB_KEY_BACKSPACE => KeyCode::Backspace,
3909            WEB_KEY_DELETE => KeyCode::Delete,
3910            WEB_KEY_ESCAPE => KeyCode::Escape,
3911            WEB_KEY_TAB => KeyCode::Tab,
3912            WEB_KEY_SPACE => KeyCode::Space,
3913            WEB_KEY_ARROW_LEFT => KeyCode::ArrowLeft,
3914            WEB_KEY_ARROW_RIGHT => KeyCode::ArrowRight,
3915            WEB_KEY_ARROW_UP => KeyCode::ArrowUp,
3916            WEB_KEY_ARROW_DOWN => KeyCode::ArrowDown,
3917            other => other
3918                .chars()
3919                .next()
3920                .map(KeyCode::Character)
3921                .unwrap_or(KeyCode::Unknown),
3922        };
3923        let ev: WindowEvent =
3924            WindowEvent::KeyDown(wid, KeyEvent::new(code, Modifiers::default(), false));
3925        rt.get_state().get_game_host().ingest_event(&ev);
3926        rt.get_mut_app().dispatch_window_event(ev);
3927        rt.set_dirty(true);
3928        true
3929    })
3930}
3931
3932/// Switches the active host runtime Light/Dark theme mode.
3933///
3934/// # Arguments
3935///
3936/// - `bool` - `true` for Dark mode, `false` for Light mode.
3937///
3938/// # Returns
3939///
3940/// - `bool` - `true` when applied.
3941#[cfg(target_arch = "wasm32")]
3942#[wasm_bindgen]
3943pub fn euv_host_theme(is_dark: bool) -> bool {
3944    HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
3945        let mut borrow: RefMut<'_, Option<HostCanvasRuntime>> = match slot.try_borrow_mut() {
3946            Ok(guard) => guard,
3947            Err(_) => return false,
3948        };
3949        let Some(rt) = borrow.as_mut() else {
3950            return false;
3951        };
3952        let wid: WindowId = rt.get_app().get_window_state().get_id();
3953        let theme: ThemeMode = if is_dark {
3954            ThemeMode::Dark
3955        } else {
3956            ThemeMode::Light
3957        };
3958        let _: bool = rt.get_state().get_theme().get_mode().set_if_changed(theme);
3959        rt.get_mut_app()
3960            .dispatch_window_event(WindowEvent::ThemeChanged(wid, theme));
3961        rt.get_mut_app()
3962            .dispatch_window_event(WindowEvent::System(SystemEvent::ThemeChanged(theme)));
3963        rt.set_dirty(true).set_force_full_dirty(true);
3964        true
3965    })
3966}
3967
3968/// Forwards a host memory pressure level (`>= 10` critical, `> 0` warning, `0` normal) into EUV.
3969///
3970/// # Arguments
3971///
3972/// - `i32` - Vendor memory pressure level.
3973///
3974/// # Returns
3975///
3976/// - `bool` - `true` when dispatched.
3977#[cfg(target_arch = "wasm32")]
3978#[wasm_bindgen]
3979pub fn euv_host_memory_warning(level: i32) -> bool {
3980    HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
3981        let mut borrow: RefMut<'_, Option<HostCanvasRuntime>> = match slot.try_borrow_mut() {
3982            Ok(guard) => guard,
3983            Err(_) => return false,
3984        };
3985        let Some(rt) = borrow.as_mut() else {
3986            return false;
3987        };
3988        let pressure: MemoryPressure = miniapp_memory_level_to_pressure(level);
3989        rt.get_mut_app()
3990            .dispatch_window_event(WindowEvent::System(SystemEvent::MemoryWarning(pressure)));
3991        rt.set_dirty(true);
3992        true
3993    })
3994}
3995
3996/// Forwards host soft-keyboard height changes in logical dp into EUV.
3997///
3998/// # Arguments
3999///
4000/// - `f32` - Keyboard height in logical dp (`0.0` when hidden).
4001///
4002/// # Returns
4003///
4004/// - `bool` - `true` when dispatched.
4005#[cfg(target_arch = "wasm32")]
4006#[wasm_bindgen]
4007pub fn euv_host_keyboard_height(height_dp: f32) -> bool {
4008    HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
4009        let mut borrow: RefMut<'_, Option<HostCanvasRuntime>> = match slot.try_borrow_mut() {
4010            Ok(guard) => guard,
4011            Err(_) => return false,
4012        };
4013        let Some(rt) = borrow.as_mut() else {
4014            return false;
4015        };
4016        let h: f32 = if height_dp.is_finite() {
4017            height_dp.max(0.0)
4018        } else {
4019            0.0
4020        };
4021        rt.get_mut_app().dispatch_window_event(WindowEvent::System(
4022            SystemEvent::KeyboardVisibilityChanged {
4023                visible: h > 0.0,
4024                height: h,
4025            },
4026        ));
4027        rt.set_dirty(true);
4028        true
4029    })
4030}
4031
4032/// Forwards host network reachability updates (`"wifi"`, `"cellular"`, `"offline"`, `"none"`, etc.) into EUV.
4033///
4034/// # Arguments
4035///
4036/// - `&str` - Network status label from host runtime.
4037///
4038/// # Returns
4039///
4040/// - `bool` - `true` when dispatched.
4041#[cfg(target_arch = "wasm32")]
4042#[wasm_bindgen]
4043pub fn euv_host_network(status: &str) -> bool {
4044    HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
4045        let mut borrow: RefMut<'_, Option<HostCanvasRuntime>> = match slot.try_borrow_mut() {
4046            Ok(guard) => guard,
4047            Err(_) => return false,
4048        };
4049        let Some(rt) = borrow.as_mut() else {
4050            return false;
4051        };
4052        let lower: String = status.trim().to_ascii_lowercase();
4053        let net: NetworkStatus = if lower == HOST_NET_NONE || lower == HOST_NET_OFFLINE {
4054            NetworkStatus::Offline
4055        } else if lower == HOST_NET_WIFI {
4056            NetworkStatus::Wifi
4057        } else if lower == HOST_NET_CELLULAR || lower.ends_with('g') {
4058            NetworkStatus::Cellular
4059        } else {
4060            NetworkStatus::Unknown
4061        };
4062        rt.get_mut_app()
4063            .dispatch_window_event(WindowEvent::System(SystemEvent::NetworkStatusChanged(net)));
4064        rt.set_dirty(true);
4065        true
4066    })
4067}
4068
4069/// Dispatches rotary crown / rotating bezel detents from smartwatch hosts (BlueOS, Vela, Zepp OS).
4070///
4071/// # Arguments
4072///
4073/// - `f32` - Signed detent delta (positive scrolls down / forward).
4074/// - `i32` - Crown mode (`0` = scroll, `1` = focus step, `2` = directional step).
4075///
4076/// # Returns
4077///
4078/// - `bool` - `true` when dispatched.
4079#[cfg(target_arch = "wasm32")]
4080#[wasm_bindgen]
4081pub fn euv_host_crown(detents: f32, mode: i32) -> bool {
4082    HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
4083        let mut borrow: RefMut<'_, Option<HostCanvasRuntime>> = match slot.try_borrow_mut() {
4084            Ok(guard) => guard,
4085            Err(_) => return false,
4086        };
4087        let Some(rt) = borrow.as_mut() else {
4088            return false;
4089        };
4090        if !detents.is_finite() || detents.abs() < 1e-4 {
4091            return false;
4092        }
4093        let wid: WindowId = rt.get_app().get_window_state().get_id();
4094        let cx: f32 = (rt.get_logical_width() as f32) * 0.5;
4095        let cy: f32 = (rt.get_logical_height() as f32) * 0.5;
4096        match mode {
4097            1 | 2 => {
4098                let total: f32 = rt.get_crown_remainder() + detents;
4099                let steps: i32 = total.trunc() as i32;
4100                rt.set_crown_remainder(total - (steps as f32));
4101                for _ in 0..steps.unsigned_abs() {
4102                    let (code, shift): (KeyCode, bool) = if mode == 1 {
4103                        (KeyCode::Tab, steps < 0)
4104                    } else if steps > 0 {
4105                        (KeyCode::ArrowDown, false)
4106                    } else {
4107                        (KeyCode::ArrowUp, false)
4108                    };
4109                    let mods: Modifiers = Modifiers::new(shift, false, false, false);
4110                    rt.get_mut_app().dispatch_window_event(WindowEvent::KeyDown(
4111                        wid,
4112                        KeyEvent::new(code, mods, false),
4113                    ));
4114                }
4115            }
4116            _ => {
4117                rt.get_mut_app()
4118                    .dispatch_window_event(WindowEvent::PointerMove(
4119                        wid,
4120                        PointerEvent::mouse(cx, cy),
4121                    ));
4122                let dy: f32 = detents * WEARABLE_CROWN_PIXELS_PER_DETENT;
4123                rt.get_mut_app()
4124                    .dispatch_window_event(WindowEvent::Scroll(wid, Point::new(0.0, dy)));
4125            }
4126        }
4127        rt.set_dirty(true);
4128        true
4129    })
4130}
4131
4132/// Switches wearable Always-On Display (1Hz ambient) mode on or off.
4133///
4134/// # Arguments
4135///
4136/// - `bool` - `true` when entering burn-in-safe 1Hz AOD ambient mode.
4137///
4138/// # Returns
4139///
4140/// - `bool` - `true` when applied.
4141#[cfg(target_arch = "wasm32")]
4142#[wasm_bindgen]
4143pub fn euv_host_ambient(is_ambient: bool) -> bool {
4144    HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
4145        let mut borrow: RefMut<'_, Option<HostCanvasRuntime>> = match slot.try_borrow_mut() {
4146            Ok(guard) => guard,
4147            Err(_) => return false,
4148        };
4149        let Some(rt) = borrow.as_mut() else {
4150            return false;
4151        };
4152        rt.set_ambient(is_ambient).set_dirty(true);
4153        rt.get_mut_app().dispatch_window_event(WindowEvent::System(
4154            SystemEvent::LowPowerModeChanged(is_ambient),
4155        ));
4156        true
4157    })
4158}
4159
4160/// Dispatches normalized wearable wrist/button hardware gestures into EUV.
4161///
4162/// # Arguments
4163///
4164/// - `i32` - Gesture tag (`0`=WristRaise, `1`=WristLower, `2`=PalmCover, `3`=DoublePinch, `4`=SideButtonPress).
4165///
4166/// # Returns
4167///
4168/// - `bool` - `true` when dispatched.
4169#[cfg(target_arch = "wasm32")]
4170#[wasm_bindgen]
4171pub fn euv_host_hardware_gesture(gesture_tag: i32) -> bool {
4172    HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
4173        let mut borrow: RefMut<'_, Option<HostCanvasRuntime>> = match slot.try_borrow_mut() {
4174            Ok(guard) => guard,
4175            Err(_) => return false,
4176        };
4177        let Some(rt) = borrow.as_mut() else {
4178            return false;
4179        };
4180        let wid: WindowId = rt.get_app().get_window_state().get_id();
4181        match gesture_tag {
4182            0 => {
4183                rt.set_paused(false).set_ambient(false).set_dirty(true);
4184                rt.get_mut_app()
4185                    .dispatch_window_event(WindowEvent::System(SystemEvent::Foreground));
4186                true
4187            }
4188            1 => {
4189                rt.set_ambient(true).set_dirty(true);
4190                rt.get_mut_app().dispatch_window_event(WindowEvent::System(
4191                    SystemEvent::LowPowerModeChanged(true),
4192                ));
4193                true
4194            }
4195            2 => {
4196                rt.set_paused(true).set_ambient(false);
4197                rt.get_mut_app()
4198                    .dispatch_window_event(WindowEvent::System(SystemEvent::Background));
4199                true
4200            }
4201            3 => {
4202                rt.get_mut_app().dispatch_window_event(WindowEvent::KeyDown(
4203                    wid,
4204                    KeyEvent::new(KeyCode::Enter, Modifiers::default(), false),
4205                ));
4206                rt.set_dirty(true);
4207                true
4208            }
4209            4 => {
4210                rt.get_mut_app().dispatch_window_event(WindowEvent::KeyDown(
4211                    wid,
4212                    KeyEvent::new(KeyCode::Back, Modifiers::default(), false),
4213                ));
4214                rt.get_mut_app()
4215                    .dispatch_window_event(WindowEvent::System(SystemEvent::BackPressed));
4216                rt.set_dirty(true);
4217                true
4218            }
4219            _ => false,
4220        }
4221    })
4222}
4223
4224/// Forwards 6-DOF accelerometer/gyroscope samples from MiniApp, QuickApp, or Wearable sensor bridges into EUV.
4225///
4226/// # Arguments
4227///
4228/// - `f32` - Acceleration X (`m/s^2`).
4229/// - `f32` - Acceleration Y (`m/s^2`).
4230/// - `f32` - Acceleration Z (`m/s^2`).
4231/// - `f32` - Gyroscope angular rate X (`rad/s`).
4232/// - `f32` - Gyroscope angular rate Y (`rad/s`).
4233/// - `f32` - Gyroscope angular rate Z (`rad/s`).
4234///
4235/// # Returns
4236///
4237/// - `bool` - `true` when dispatched.
4238#[cfg(target_arch = "wasm32")]
4239#[wasm_bindgen]
4240pub fn euv_host_device_motion(ax: f32, ay: f32, az: f32, gx: f32, gy: f32, gz: f32) -> bool {
4241    HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
4242        let mut borrow: RefMut<'_, Option<HostCanvasRuntime>> = match slot.try_borrow_mut() {
4243            Ok(guard) => guard,
4244            Err(_) => return false,
4245        };
4246        let Some(rt) = borrow.as_mut() else {
4247            return false;
4248        };
4249        let sample: DeviceMotionSample = DeviceMotionSample::from_vectors(
4250            [ax, ay, az],
4251            [0.0, 0.0, 0.0],
4252            [gx, gy, gz],
4253            [0.0, 0.0, 0.0],
4254            0,
4255            true,
4256        );
4257        rt.get_mut_app()
4258            .dispatch_window_event(WindowEvent::System(SystemEvent::DeviceMotion(sample)));
4259        rt.set_dirty(true);
4260        true
4261    })
4262}
4263
4264/// Navigates the zero-DOM canvas host showcase to `route` and immediately renders an updated frame.
4265///
4266/// # Arguments
4267///
4268/// - `&str` - Target showcase route path (e.g. `"/"`, `"/forms"`, `"/charts"`, `"/water"`).
4269///
4270/// # Returns
4271///
4272/// - `u64` - Deterministic rendered frame hash.
4273#[cfg(target_arch = "wasm32")]
4274#[wasm_bindgen]
4275pub fn euv_host_navigate(route: &str) -> u64 {
4276    HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
4277        let mut borrow: RefMut<'_, Option<HostCanvasRuntime>> = match slot.try_borrow_mut() {
4278            Ok(guard) => guard,
4279            Err(_) => return 0,
4280        };
4281        let Some(rt) = borrow.as_mut() else {
4282            return 0;
4283        };
4284        let normalized: String =
4285            resolve_web_hash_route(route, Some(rt.get_state().get_dynamic_hub()));
4286        let _: bool = rt.get_state().get_route().set_if_changed(normalized);
4287        rt.set_force_full_dirty(true);
4288        match rt.get_mut_app().step_frame() {
4289            Ok(stats) => {
4290                rt.set_dirty(false);
4291                rt.set_frame_count(rt.get_frame_count().saturating_add(1));
4292                rt.set_last_frame_hash(stats.get_frame_hash());
4293                host_sync_dirty_rect(rt, true);
4294                stats.get_frame_hash()
4295            }
4296            Err(_) => 0,
4297        }
4298    })
4299}
4300
4301/// Returns the active route path of the zero-DOM canvas host runtime.
4302///
4303/// # Returns
4304///
4305/// - `String` - Active route string.
4306#[cfg(target_arch = "wasm32")]
4307#[wasm_bindgen]
4308pub fn euv_host_current_route() -> String {
4309    HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
4310        slot.try_borrow()
4311            .ok()
4312            .and_then(|guard: Ref<'_, Option<HostCanvasRuntime>>| {
4313                guard
4314                    .as_ref()
4315                    .map(|rt: &HostCanvasRuntime| rt.get_state().get_route().get_untracked())
4316            })
4317            .unwrap_or_default()
4318    })
4319}
4320
4321/// Drains all queued outbound host bridge commands as a JSON array string.
4322///
4323/// # Returns
4324///
4325/// - `String` - JSON array of pending host commands (e.g. `"[]"` when empty).
4326#[cfg(target_arch = "wasm32")]
4327#[wasm_bindgen]
4328pub fn euv_host_drain_commands_json() -> String {
4329    HOST_OUTBOUND_COMMANDS.with(|queue: &RefCell<Vec<String>>| {
4330        let Ok(mut borrow) = queue.try_borrow_mut() else {
4331            return "[]".to_string();
4332        };
4333        let drained: Vec<String> = take(&mut *borrow);
4334        format!("[{}]", drained.join(","))
4335    })
4336}
4337
4338/// Returns structured JSON runtime telemetry for MiniApp/QuickApp/Wearable diagnostics and QA.
4339///
4340/// # Returns
4341///
4342/// - `String` - JSON object describing vendor, platform, route, dimensions, frame count, and dirty rect.
4343#[cfg(target_arch = "wasm32")]
4344#[wasm_bindgen]
4345pub fn euv_host_stats_json() -> String {
4346    HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
4347        let Ok(guard) = slot.try_borrow() else {
4348            return "{}".to_string();
4349        };
4350        let Some(rt) = guard.as_ref() else {
4351            return "{}".to_string();
4352        };
4353        let vendor: String = host_json_escape(rt.get_vendor());
4354        let route: String = host_json_escape(&rt.get_state().get_route().get_untracked());
4355        let (pw, ph): (u32, u32) = rt
4356            .get_app()
4357            .get_renderer()
4358            .framebuffer()
4359            .map(|fb: &Framebuffer| (fb.get_width(), fb.get_height()))
4360            .unwrap_or((0, 0));
4361        format!(
4362            "{{\"vendor\":\"{vendor}\",\"platform\":\"{:?}\",\"route\":\"{route}\",\"logicalWidth\":{},\"logicalHeight\":{},\"physicalWidth\":{pw},\"physicalHeight\":{ph},\"dpr\":{:.2},\"frames\":{},\"paused\":{},\"ambient\":{},\"dark\":{},\"dirty\":[{},{},{},{}],\"hash\":{}}}",
4363            rt.get_platform_kind(),
4364            rt.get_logical_width(),
4365            rt.get_logical_height(),
4366            rt.get_dpr(),
4367            rt.get_frame_count(),
4368            rt.get_paused(),
4369            rt.get_ambient(),
4370            rt.get_state().get_theme().get_mode().get_untracked() == ThemeMode::Dark,
4371            rt.get_dirty_x(),
4372            rt.get_dirty_y(),
4373            rt.get_dirty_w(),
4374            rt.get_dirty_h(),
4375            rt.get_last_frame_hash(),
4376        )
4377    })
4378}
4379
4380/// Returns whether the zero-DOM canvas host runtime is currently paused (background freeze / screen off).
4381///
4382/// # Returns
4383///
4384/// - `bool` - `true` when paused.
4385#[cfg(target_arch = "wasm32")]
4386#[wasm_bindgen]
4387pub fn euv_host_is_paused() -> bool {
4388    HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
4389        slot.try_borrow()
4390            .ok()
4391            .and_then(|guard: Ref<'_, Option<HostCanvasRuntime>>| {
4392                guard.as_ref().map(HostCanvasRuntime::get_paused)
4393            })
4394            .unwrap_or(true)
4395    })
4396}
4397
4398/// Destroys the active zero-DOM canvas host runtime and releases its framebuffer and command queue.
4399#[cfg(target_arch = "wasm32")]
4400#[wasm_bindgen]
4401pub fn euv_host_destroy() {
4402    HOST_CANVAS_RUNTIME.with(|slot: &RefCell<Option<HostCanvasRuntime>>| {
4403        if let Ok(mut borrow) = slot.try_borrow_mut() {
4404            *borrow = None;
4405        }
4406    });
4407    HOST_OUTBOUND_COMMANDS.with(|queue: &RefCell<Vec<String>>| {
4408        if let Ok(mut borrow) = queue.try_borrow_mut() {
4409            borrow.clear();
4410        }
4411    });
4412}