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