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