1use super::*;
2
3pub fn create_showcase_app(
14 headless: bool,
15 mode: RenderMode,
16) -> Result<(App, ShowcaseState), PlatformError> {
17 EuvOverlayStack::clear();
18 reset_fullscreen_state();
19 clear_provided_theme();
20 let render_cfg: RenderConfig = match mode {
21 RenderMode::Software => RenderConfig::software(),
22 RenderMode::Hardware => RenderConfig::hardware(),
23 RenderMode::Hybrid => RenderConfig::hybrid(),
24 RenderMode::Auto => RenderConfig::default(),
25 };
26 let mut window_cfg: WindowConfig = WindowConfig::default();
27 window_cfg
28 .set_title(SHOWCASE_WINDOW_TITLE.to_string())
29 .set_size(SHOWCASE_WINDOW_WIDTH, SHOWCASE_WINDOW_HEIGHT)
30 .set_render(render_cfg)
31 .set_icon(Some(euv_brand_logo_image()));
32 let mut app_cfg: AppConfig = AppConfig::default();
33 app_cfg.set_window(window_cfg);
34 let mut app: App = if headless {
35 App::headless(app_cfg)?
36 } else {
37 App::new(app_cfg)?
38 };
39 let mut state: ShowcaseState = ShowcaseState::new();
40 let host_plat_idx: usize = match app.platform_kind() {
41 PlatformKind::Ios => 0,
42 PlatformKind::IpadOs => 1,
43 PlatformKind::Android | PlatformKind::HarmonyOs | PlatformKind::Wearable => 2,
44 PlatformKind::MacOs => 3,
45 PlatformKind::Windows => 4,
46 PlatformKind::Linux | PlatformKind::Terminal | PlatformKind::TerminalCli => 5,
47 PlatformKind::Web
48 | PlatformKind::MiniApp
49 | PlatformKind::QuickApp
50 | PlatformKind::Headless => 6,
51 };
52 let _: bool = state
53 .get_os_target_platform_idx()
54 .set_if_changed(host_plat_idx);
55 state.attach_dynamic_hub(app.get_dynamic_hub().clone());
56 app.attach_game_host(state.get_game_host().clone());
57 app.attach_game_host(state.get_game3d_host().clone());
58 let mount_state: ShowcaseState = state.clone();
59 let _: NodeId = app.mount(move || mount_showcase_root(&mount_state));
60 Ok((app, state))
61}
62
63pub fn create_showcase_app_for_platform(
74 platform: PlatformKind,
75 mode: RenderMode,
76) -> Result<(App, ShowcaseState), PlatformError> {
77 EuvOverlayStack::clear();
78 reset_fullscreen_state();
79 clear_provided_theme();
80 let render_cfg: RenderConfig = match mode {
81 RenderMode::Software => RenderConfig::software(),
82 RenderMode::Hardware => RenderConfig::hardware(),
83 RenderMode::Hybrid => RenderConfig::hybrid(),
84 RenderMode::Auto => RenderConfig::default(),
85 };
86 let mut window_cfg: WindowConfig = WindowConfig::default();
87 window_cfg
88 .set_title(SHOWCASE_WINDOW_TITLE.to_string())
89 .set_size(SHOWCASE_WINDOW_WIDTH, SHOWCASE_WINDOW_HEIGHT)
90 .set_render(render_cfg)
91 .set_icon(Some(euv_brand_logo_image()));
92 let mut app_cfg: AppConfig = AppConfig::default();
93 app_cfg.set_window(window_cfg);
94 let backend: Box<dyn PlatformBackend> = Box::new(HeadlessPlatform::emulating(
95 platform,
96 1.0,
97 SafeAreaInsets::default(),
98 ));
99 let mut app: App = App::with_platform(app_cfg, backend)?;
100 let mut state: ShowcaseState = ShowcaseState::new();
101 let host_plat_idx: usize = match app.platform_kind() {
102 PlatformKind::Ios => 0,
103 PlatformKind::IpadOs => 1,
104 PlatformKind::Android | PlatformKind::HarmonyOs | PlatformKind::Wearable => 2,
105 PlatformKind::MacOs => 3,
106 PlatformKind::Windows => 4,
107 PlatformKind::Linux | PlatformKind::Terminal | PlatformKind::TerminalCli => 5,
108 PlatformKind::Web
109 | PlatformKind::MiniApp
110 | PlatformKind::QuickApp
111 | PlatformKind::Headless => 6,
112 };
113 let _: bool = state
114 .get_os_target_platform_idx()
115 .set_if_changed(host_plat_idx);
116 state.attach_dynamic_hub(app.get_dynamic_hub().clone());
117 app.attach_game_host(state.get_game_host().clone());
118 app.attach_game_host(state.get_game3d_host().clone());
119 let mount_state: ShowcaseState = state.clone();
120 let _: NodeId = app.mount(move || mount_showcase_root(&mount_state));
121 Ok((app, state))
122}
123
124pub fn run_headless_smoke(mode: RenderMode) -> Result<FrameStats, PlatformError> {
134 let (mut app, _): (App, ShowcaseState) = create_showcase_app(true, mode)?;
135 app.step_frame()
136}
137
138#[cfg(not(target_arch = "wasm32"))]
152fn dump_rgba_frame(
153 app: &mut App,
154 out_dir: &Path,
155 name: &str,
156 manifest: &mut String,
157 count: &mut usize,
158) -> Result<(), PlatformError> {
159 let _: FrameStats = app.step_frame()?;
160 for _ in 0..20 {
161 if !app.has_active_animations() {
162 break;
163 }
164 let _: FrameStats = app.step_game_frame(1.0 / 60.0)?;
165 }
166 if let Some(fb) = app.get_renderer().framebuffer() {
167 let file_name: String = format!("{name}.rgba");
168 let file_path: PathBuf = out_dir.join(&file_name);
169 fs::write(&file_path, fb.get_pixels().as_slice())
170 .map_err(|err: Error| PlatformError::SurfaceError(err.to_string()))?;
171 manifest.push_str(&format!("{name} {} {}\n", fb.get_width(), fb.get_height()));
172 *count += 1;
173 }
174 Ok(())
175}
176
177#[cfg(not(target_arch = "wasm32"))]
187pub fn capture_showcase_screenshots(out_dir: &Path) -> Result<usize, PlatformError> {
188 reset_reactive_runtime();
189 EuvOverlayStack::clear();
190 reset_fullscreen_state();
191 clear_provided_theme();
192 fs::create_dir_all(out_dir)
193 .map_err(|err: Error| PlatformError::InitializationFailed(err.to_string()))?;
194 let mut window_cfg: WindowConfig = WindowConfig::default();
195 window_cfg
196 .set_title(SHOWCASE_WINDOW_TITLE.to_string())
197 .set_size(1200, 800)
198 .set_render(RenderConfig::software())
199 .set_icon(Some(euv_brand_logo_image()));
200 let mut app_cfg: AppConfig = AppConfig::default();
201 app_cfg.set_window(window_cfg);
202 let backend: Box<dyn PlatformBackend> = Box::new(HeadlessPlatform::emulating(
203 PlatformKind::Headless,
204 2.0,
205 SafeAreaInsets::default(),
206 ));
207 let mut app: App = App::with_platform(app_cfg, backend)?;
208 let mut state: ShowcaseState = ShowcaseState::new();
209 state.attach_dynamic_hub(app.get_dynamic_hub().clone());
210 app.attach_game_host(state.get_game_host().clone());
211 app.attach_game_host(state.get_game3d_host().clone());
212 let mount_state: ShowcaseState = state.clone();
213 let _: NodeId = app.mount(move || mount_showcase_root(&mount_state));
214 app.get_mut_renderer()
215 .get_mut_software()
216 .set_font_provider(NativeSystemFont::system());
217 let wid: WindowId = app.get_window_state().get_id();
218 let mut manifest: String = String::new();
219 let mut count: usize = 0;
220 app.dispatch_window_event(WindowEvent::Resized(wid, 1200, 800, 2.0));
221 let desktop_routes: [(&str, &str); 12] = [
222 (ROUTE_OVERVIEW, "01_overview_desktop"),
223 (ROUTE_REACTIVE, "02_reactive_desktop"),
224 (ROUTE_RENDER, "03_render_desktop"),
225 (ROUTE_WINDOW, "04_window_desktop"),
226 (ROUTE_FORMS, "05_forms_desktop"),
227 (ROUTE_THEMES, "06_themes_desktop"),
228 (ROUTE_DATA, "07_data_desktop"),
229 (ROUTE_GAME, "08_game_desktop"),
230 (ROUTE_GAME_3D, "08b_game3d_desktop"),
231 (ROUTE_MEDIA, "08c_media_desktop"),
232 (ROUTE_OVERLAYS, "09_overlays_desktop"),
233 (ROUTE_DYNAMIC, "10_dynamic_desktop"),
234 ];
235 for (route, label) in desktop_routes.iter() {
236 let _: bool = state.get_route().set_if_changed((*route).to_string());
237 if *route == ROUTE_OVERVIEW {
238 app.dispatch_window_event(WindowEvent::PointerMove(
239 wid,
240 PointerEvent::mouse(100.0, 108.0),
241 ));
242 }
243 dump_rgba_frame(&mut app, out_dir, label, &mut manifest, &mut count)?;
244 }
245 let _: bool = state.get_route().set_if_changed(ROUTE_FORMS.to_string());
246 let _: FrameStats = app.step_frame()?;
247 app.dispatch_window_event(WindowEvent::PointerMove(
248 wid,
249 PointerEvent::mouse(600.0, 400.0),
250 ));
251 app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(0.0, 420.0)));
252 dump_rgba_frame(
253 &mut app,
254 out_dir,
255 "05b_forms_scrolled",
256 &mut manifest,
257 &mut count,
258 )?;
259 let _: bool = state.get_route().set_if_changed(ROUTE_DATA.to_string());
260 let _: FrameStats = app.step_frame()?;
261 app.dispatch_window_event(WindowEvent::PointerMove(
262 wid,
263 PointerEvent::mouse(600.0, 400.0),
264 ));
265 app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(0.0, 460.0)));
266 dump_rgba_frame(
267 &mut app,
268 out_dir,
269 "07b_data_vlist_scrolled",
270 &mut manifest,
271 &mut count,
272 )?;
273 app.dispatch_window_event(WindowEvent::PointerMove(
274 wid,
275 PointerEvent::mouse(320.0, 120.0),
276 ));
277 app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(0.0, 720.0)));
278 dump_rgba_frame(
279 &mut app,
280 out_dir,
281 "07c_data_bottom",
282 &mut manifest,
283 &mut count,
284 )?;
285 let _: bool = state.get_route().set_if_changed(ROUTE_OVERVIEW.to_string());
286 let _: FrameStats = app.step_frame()?;
287 app.dispatch_window_event(WindowEvent::PointerMove(
288 wid,
289 PointerEvent::mouse(100.0, 108.0),
290 ));
291 dump_rgba_frame(
292 &mut app,
293 out_dir,
294 "01b_overview_hovered",
295 &mut manifest,
296 &mut count,
297 )?;
298 let _: bool = state.get_route().set_if_changed(ROUTE_OVERLAYS.to_string());
299 let _: bool = state.get_modal_open().set_if_changed(true);
300 dump_rgba_frame(
301 &mut app,
302 out_dir,
303 "09b_overlays_modal",
304 &mut manifest,
305 &mut count,
306 )?;
307 let _: bool = state.get_modal_open().set_if_changed(false);
308 let _: bool = state.get_alert_dialog_open().set_if_changed(true);
309 dump_rgba_frame(
310 &mut app,
311 out_dir,
312 "09c_overlays_alert",
313 &mut manifest,
314 &mut count,
315 )?;
316 let _: bool = state.get_alert_dialog_open().set_if_changed(false);
317 let _: bool = state.get_hover_card_open().set_if_changed(true);
318 dump_rgba_frame(
319 &mut app,
320 out_dir,
321 "09d_overlays_hovercard",
322 &mut manifest,
323 &mut count,
324 )?;
325 let _: bool = state.get_hover_card_open().set_if_changed(false);
326 let _: bool = state.get_route().set_if_changed(ROUTE_THEMES.to_string());
327 state.toggle_theme_mode();
328 dump_rgba_frame(
329 &mut app,
330 out_dir,
331 "06b_themes_dark",
332 &mut manifest,
333 &mut count,
334 )?;
335 state.toggle_theme_mode();
336 let _: bool = state.get_route().set_if_changed(ROUTE_OVERVIEW.to_string());
337 app.dispatch_window_event(WindowEvent::Resized(wid, 768, 1024, 2.0));
338 dump_rgba_frame(
339 &mut app,
340 out_dir,
341 "11_overview_tablet",
342 &mut manifest,
343 &mut count,
344 )?;
345 app.dispatch_window_event(WindowEvent::Resized(wid, 390, 844, 2.0));
346 dump_rgba_frame(
347 &mut app,
348 out_dir,
349 "12_overview_mobile",
350 &mut manifest,
351 &mut count,
352 )?;
353 app.dispatch_window_event(WindowEvent::PointerDown(
354 wid,
355 PointerEvent::mouse(350.0, 26.0),
356 ));
357 app.dispatch_window_event(WindowEvent::PointerUp(
358 wid,
359 PointerEvent::mouse(350.0, 26.0),
360 ));
361 dump_rgba_frame(
362 &mut app,
363 out_dir,
364 "12b_mobile_menu_open",
365 &mut manifest,
366 &mut count,
367 )?;
368 app.dispatch_window_event(WindowEvent::PointerDown(
369 wid,
370 PointerEvent::mouse(240.0, 26.0),
371 ));
372 app.dispatch_window_event(WindowEvent::PointerUp(
373 wid,
374 PointerEvent::mouse(240.0, 26.0),
375 ));
376 let _: bool = state.get_route().set_if_changed(ROUTE_FORMS.to_string());
377 dump_rgba_frame(
378 &mut app,
379 out_dir,
380 "13_forms_mobile",
381 &mut manifest,
382 &mut count,
383 )?;
384 fs::write(out_dir.join("manifest.txt"), manifest)
385 .map_err(|err: Error| PlatformError::SurfaceError(err.to_string()))?;
386 Ok(count)
387}
388
389#[cfg(target_arch = "wasm32")]
391#[wasm_bindgen(start)]
392pub fn euv_web_boot() {
393 let _: u64 = euv_example_web_start();
394 let Some(win): Option<Window> = window() else {
395 return;
396 };
397 let Some(doc): Option<Document> = win.document() else {
398 return;
399 };
400 let Ok(Some(el)) = doc.query_selector(WEB_SELECTOR_CANVAS) else {
401 return;
402 };
403 let Ok(canvas) = el.dyn_into::<HtmlCanvasElement>() else {
404 return;
405 };
406 web_attach_ime_proxy(&doc);
407 register_native_action_bridge(web_native_action_bridge);
408 let _: bool = web_sync_exact_viewport(&win, &canvas);
409 let canvas_move: HtmlCanvasElement = canvas.clone();
410 let on_move: Closure<dyn FnMut(web_sys::PointerEvent)> =
411 Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
412 let ptr: PointerEvent = web_pointer_from_dom(&ev, &canvas_move, None);
413 web_queue_pointer_move_event(ptr);
414 }) as Box<dyn FnMut(web_sys::PointerEvent)>);
415 drop(canvas.add_event_listener_with_callback(
416 WEB_EVENT_POINTER_MOVE,
417 on_move.as_ref().unchecked_ref(),
418 ));
419 on_move.forget();
420 let canvas_down: HtmlCanvasElement = canvas.clone();
421 let on_down: Closure<dyn FnMut(web_sys::PointerEvent)> =
422 Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
423 drop(canvas_down.set_pointer_capture(ev.pointer_id()));
424 let ptr: PointerEvent = web_pointer_from_dom(&ev, &canvas_down, Some(true));
425 web_queue_pointer_down_event(ptr);
426 if !WEB_IME_ACTIVE.with(Cell::get) {
427 drop(canvas_down.focus());
428 }
429 }) as Box<dyn FnMut(web_sys::PointerEvent)>);
430 drop(canvas.add_event_listener_with_callback(
431 WEB_EVENT_POINTER_DOWN,
432 on_down.as_ref().unchecked_ref(),
433 ));
434 on_down.forget();
435 let canvas_up: HtmlCanvasElement = canvas.clone();
436 let on_up: Closure<dyn FnMut(web_sys::PointerEvent)> =
437 Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
438 ev.stop_propagation();
439 let ptr: PointerEvent = web_pointer_from_dom(&ev, &canvas_up, Some(false));
440 web_queue_pointer_up_event(ptr);
441 drop(canvas_up.release_pointer_capture(ev.pointer_id()));
442 }) as Box<dyn FnMut(web_sys::PointerEvent)>);
443 drop(
444 canvas
445 .add_event_listener_with_callback(WEB_EVENT_POINTER_UP, on_up.as_ref().unchecked_ref()),
446 );
447 on_up.forget();
448 let on_cancel: Closure<dyn FnMut(web_sys::PointerEvent)> =
449 Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
450 ev.stop_propagation();
451 web_queue_pointer_cancel(web_pointer_id_from_dom(&ev));
452 }) as Box<dyn FnMut(web_sys::PointerEvent)>);
453 drop(canvas.add_event_listener_with_callback(
454 WEB_EVENT_POINTER_CANCEL,
455 on_cancel.as_ref().unchecked_ref(),
456 ));
457 drop(canvas.add_event_listener_with_callback(
458 WEB_EVENT_LOST_POINTER_CAPTURE,
459 on_cancel.as_ref().unchecked_ref(),
460 ));
461 on_cancel.forget();
462 let canvas_win_up: HtmlCanvasElement = canvas.clone();
463 let on_win_up: Closure<dyn FnMut(web_sys::PointerEvent)> =
464 Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
465 let ptr: PointerEvent = web_pointer_from_dom(&ev, &canvas_win_up, Some(false));
466 web_queue_pointer_up_event(ptr);
467 }) as Box<dyn FnMut(web_sys::PointerEvent)>);
468 drop(win.add_event_listener_with_callback(
469 WEB_EVENT_POINTER_UP,
470 on_win_up.as_ref().unchecked_ref(),
471 ));
472 on_win_up.forget();
473 let on_win_cancel: Closure<dyn FnMut(web_sys::PointerEvent)> =
474 Closure::wrap(Box::new(move |ev: web_sys::PointerEvent| {
475 web_queue_pointer_cancel(web_pointer_id_from_dom(&ev));
476 }) as Box<dyn FnMut(web_sys::PointerEvent)>);
477 drop(win.add_event_listener_with_callback(
478 WEB_EVENT_POINTER_CANCEL,
479 on_win_cancel.as_ref().unchecked_ref(),
480 ));
481 on_win_cancel.forget();
482 let on_blur: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
483 web_queue_pointer_cancel(0);
484 web_dispatch_system_event(SystemEvent::FocusChanged(false));
485 }) as Box<dyn FnMut(Event)>);
486 drop(win.add_event_listener_with_callback(WEB_EVENT_BLUR, on_blur.as_ref().unchecked_ref()));
487 on_blur.forget();
488 web_attach_system_event_listeners(&win, &doc);
489 let canvas_wheel: HtmlCanvasElement = canvas.clone();
490 let on_wheel: Closure<dyn FnMut(WheelEvent)> = Closure::wrap(Box::new(move |ev: WheelEvent| {
491 ev.prevent_default();
492 let rect: DomRect = canvas_wheel.get_bounding_client_rect();
493 let x: f32 = (ev.client_x() as f64 - rect.left()) as f32;
494 let y: f32 = (ev.client_y() as f64 - rect.top()) as f32;
495 let mult: f32 = match ev.delta_mode() {
496 1 => 20.0,
497 2 => 320.0,
498 _ => 1.0,
499 };
500 web_queue_scroll_at(
501 x,
502 y,
503 (ev.delta_x() as f32) * mult,
504 (ev.delta_y() as f32) * mult,
505 );
506 })
507 as Box<dyn FnMut(WheelEvent)>);
508 drop(
509 canvas.add_event_listener_with_callback(WEB_EVENT_WHEEL, on_wheel.as_ref().unchecked_ref()),
510 );
511 on_wheel.forget();
512 let on_key: Closure<dyn FnMut(KeyboardEvent)> =
513 Closure::wrap(Box::new(move |ev: KeyboardEvent| {
514 let key: String = ev.key();
515 let code_str: String = ev.code();
516 let ime_active: bool = WEB_IME_ACTIVE.with(Cell::get);
517 let should_prevent: bool = if ime_active {
518 matches!(
519 key.as_str(),
520 WEB_KEY_ARROW_UP
521 | WEB_KEY_ARROW_DOWN
522 | WEB_KEY_ARROW_LEFT
523 | WEB_KEY_ARROW_RIGHT
524 | WEB_KEY_BACKSPACE
525 )
526 } else {
527 matches!(
528 key.as_str(),
529 WEB_KEY_ARROW_UP
530 | WEB_KEY_ARROW_DOWN
531 | WEB_KEY_ARROW_LEFT
532 | WEB_KEY_ARROW_RIGHT
533 | WEB_KEY_BACKSPACE
534 | WEB_KEY_SPACE
535 )
536 };
537 if should_prevent {
538 ev.prevent_default();
539 }
540 web_queue_key_down(&key, &code_str);
541 }) as Box<dyn FnMut(KeyboardEvent)>);
542 drop(win.add_event_listener_with_callback(WEB_EVENT_KEY_DOWN, on_key.as_ref().unchecked_ref()));
543 on_key.forget();
544 let on_key_up: Closure<dyn FnMut(KeyboardEvent)> =
545 Closure::wrap(Box::new(move |ev: KeyboardEvent| {
546 let key: String = ev.key();
547 let code_str: String = ev.code();
548 web_queue_key_up(&key, &code_str);
549 }) as Box<dyn FnMut(KeyboardEvent)>);
550 drop(
551 win.add_event_listener_with_callback(WEB_EVENT_KEY_UP, on_key_up.as_ref().unchecked_ref()),
552 );
553 on_key_up.forget();
554 let win_resize: Window = win.clone();
555 let canvas_resize: HtmlCanvasElement = canvas.clone();
556 let on_resize: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
557 let viewport_changed: bool = web_sync_exact_viewport(&win_resize, &canvas_resize);
558 let safe_changed: bool = web_sync_safe_area();
559 if viewport_changed || safe_changed {
560 web_mark_needs_frame();
561 }
562 }) as Box<dyn FnMut(Event)>);
563 drop(
564 win.add_event_listener_with_callback(WEB_EVENT_RESIZE, on_resize.as_ref().unchecked_ref()),
565 );
566 on_resize.forget();
567 let win_raf: Window = win.clone();
568 let canvas_raf: HtmlCanvasElement = canvas.clone();
569 WEB_RAF_CALLBACK.with(|slot: &RefCell<Option<WebRafCallback>>| {
570 if let Ok(mut guard) = slot.try_borrow_mut() {
571 *guard = Some(Closure::wrap(Box::new(move |ts: f64| {
572 WEB_RAF_ID.with(|id_cell: &Cell<Option<i32>>| id_cell.set(None));
573 if !web_should_pump_frames() {
574 WEB_RAF_LAST_TS.with(|ts_cell: &Cell<f64>| ts_cell.set(0.0));
575 WEB_RAF_ACCUM_SECS.with(|s_cell: &Cell<f32>| s_cell.set(0.0));
576 WEB_RAF_ACCUM_FRAMES.with(|f_cell: &Cell<u32>| f_cell.set(0));
577 return;
578 }
579 let prev_ts: f64 = WEB_RAF_LAST_TS.with(|ts_cell: &Cell<f64>| ts_cell.replace(ts));
580 let mut dt: f32 = 1.0 / 60.0;
581 let mut valid_step: bool = false;
582 if prev_ts > 0.0 {
583 let raw_dt: f32 = ((ts - prev_ts) / 1000.0) as f32;
584 if (0.001..=0.1).contains(&raw_dt) {
585 valid_step = true;
586 }
587 dt = raw_dt.clamp(0.001, 0.05);
588 }
589 if valid_step {
590 let next_secs: f32 = WEB_RAF_ACCUM_SECS.with(Cell::get) + dt;
591 let next_frames: u32 = WEB_RAF_ACCUM_FRAMES.with(Cell::get).saturating_add(1);
592 if next_secs >= 0.35 && next_frames >= 8 {
593 let measured_hz: f32 = (next_frames as f32) / next_secs;
594 WEB_RAF_ACCUM_SECS.with(|s_cell: &Cell<f32>| s_cell.set(0.0));
595 WEB_RAF_ACCUM_FRAMES.with(|f_cell: &Cell<u32>| f_cell.set(0));
596 web_report_host_refresh_rate(measured_hz);
597 } else {
598 WEB_RAF_ACCUM_SECS.with(|s_cell: &Cell<f32>| s_cell.set(next_secs));
599 WEB_RAF_ACCUM_FRAMES.with(|f_cell: &Cell<u32>| f_cell.set(next_frames));
600 }
601 }
602 let resized_or_scaled: bool = web_sync_exact_viewport(&win_raf, &canvas_raf);
603 let cur_route: String = euv_web_current_route();
604 let on_game: bool = cur_route == ROUTE_GAME || cur_route == ROUTE_GAME_3D;
605 let animating: bool = web_has_active_animations();
606 let dirty: bool = WEB_NEEDS_FRAME.with(|flag: &Cell<bool>| flag.replace(false));
607 let needs_continuous: bool = resized_or_scaled || on_game;
608 let needs_redraw: bool = animating || dirty;
609 if needs_continuous || needs_redraw {
610 let _: u64 = web_flush_frame(dt);
611 }
612 if web_should_pump_frames() {
613 web_start_raf_pump(&win_raf);
614 }
615 }) as Box<dyn FnMut(f64)>));
616 }
617 });
618 if doc.hidden() {
619 web_dispatch_system_event(SystemEvent::Background);
620 } else {
621 web_start_raf_pump(&win);
622 }
623}
624
625#[cfg(target_arch = "wasm32")]
631fn web_should_pump_frames() -> bool {
632 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
633 match slot.try_borrow() {
634 Ok(guard) => guard
635 .as_ref()
636 .map(|(app, _): &(App, ShowcaseState)| app.should_pump_frames())
637 .unwrap_or(false),
638 Err(_) => false,
639 }
640 })
641}
642
643#[cfg(target_arch = "wasm32")]
649fn web_start_raf_pump(win: &Window) {
650 if !web_should_pump_frames() {
651 return;
652 }
653 let already_scheduled: bool =
654 WEB_RAF_ID.with(|id_cell: &Cell<Option<i32>>| id_cell.get().is_some());
655 if already_scheduled {
656 return;
657 }
658 WEB_RAF_CALLBACK.with(|slot: &RefCell<Option<WebRafCallback>>| {
659 if let Ok(cb_ref) = slot.try_borrow()
660 && let Some(cb) = cb_ref.as_ref()
661 {
662 let func: &Function = cb.as_ref().unchecked_ref();
663 if let Ok(req_id) = win.request_animation_frame(func) {
664 WEB_RAF_ID.with(|id_cell: &Cell<Option<i32>>| id_cell.set(Some(req_id)));
665 }
666 }
667 });
668}
669
670#[cfg(target_arch = "wasm32")]
672fn web_stop_raf_pump() {
673 let pending_id: Option<i32> = WEB_RAF_ID.with(|id_cell: &Cell<Option<i32>>| id_cell.take());
674 if let Some(req_id) = pending_id
675 && let Some(win) = window()
676 {
677 drop(win.cancel_animation_frame(req_id));
678 }
679 WEB_RAF_LAST_TS.with(|ts_cell: &Cell<f64>| ts_cell.set(0.0));
680 WEB_RAF_ACCUM_SECS.with(|s_cell: &Cell<f32>| s_cell.set(0.0));
681 WEB_RAF_ACCUM_FRAMES.with(|f_cell: &Cell<u32>| f_cell.set(0));
682}
683
684#[cfg(target_arch = "wasm32")]
690fn web_dispatch_system_event(event: SystemEvent) {
691 let mut should_pump: bool = false;
692 let mut handled: bool = false;
693 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
694 if let Ok(mut borrow) = slot.try_borrow_mut()
695 && let Some((app, _)) = borrow.as_mut()
696 {
697 app.dispatch_system_event(event);
698 should_pump = app.should_pump_frames();
699 handled = true;
700 }
701 });
702 if !handled {
703 return;
704 }
705 if !should_pump {
706 web_stop_raf_pump();
707 } else {
708 WEB_RAF_LAST_TS.with(|ts_cell: &Cell<f64>| ts_cell.set(0.0));
709 web_mark_needs_frame();
710 if let Some(win) = window() {
711 web_start_raf_pump(&win);
712 }
713 }
714}
715
716#[cfg(target_arch = "wasm32")]
723fn web_attach_system_event_listeners(win: &Window, doc: &Document) {
724 let doc_vis: Document = doc.clone();
725 let on_vis: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
726 if doc_vis.hidden() {
727 web_dispatch_system_event(SystemEvent::Background);
728 } else {
729 web_dispatch_system_event(SystemEvent::Foreground);
730 }
731 }) as Box<dyn FnMut(Event)>);
732 drop(doc.add_event_listener_with_callback(
733 WEB_EVENT_VISIBILITY_CHANGE,
734 on_vis.as_ref().unchecked_ref(),
735 ));
736 on_vis.forget();
737 let on_focus: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
738 web_dispatch_system_event(SystemEvent::FocusChanged(true));
739 }) as Box<dyn FnMut(Event)>);
740 drop(win.add_event_listener_with_callback(WEB_EVENT_FOCUS, on_focus.as_ref().unchecked_ref()));
741 on_focus.forget();
742 let on_pageshow: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
743 web_dispatch_system_event(SystemEvent::Foreground);
744 }) as Box<dyn FnMut(Event)>);
745 drop(win.add_event_listener_with_callback(
746 WEB_EVENT_PAGE_SHOW,
747 on_pageshow.as_ref().unchecked_ref(),
748 ));
749 on_pageshow.forget();
750 let on_pagehide: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
751 web_dispatch_system_event(SystemEvent::Background);
752 }) as Box<dyn FnMut(Event)>);
753 drop(win.add_event_listener_with_callback(
754 WEB_EVENT_PAGE_HIDE,
755 on_pagehide.as_ref().unchecked_ref(),
756 ));
757 on_pagehide.forget();
758 let on_unload: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
759 web_dispatch_system_event(SystemEvent::Terminate);
760 }) as Box<dyn FnMut(Event)>);
761 drop(win.add_event_listener_with_callback(
762 WEB_EVENT_BEFORE_UNLOAD,
763 on_unload.as_ref().unchecked_ref(),
764 ));
765 on_unload.forget();
766 let on_online: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
767 web_dispatch_system_event(SystemEvent::NetworkStatusChanged(NetworkStatus::Online));
768 }) as Box<dyn FnMut(Event)>);
769 drop(
770 win.add_event_listener_with_callback(WEB_EVENT_ONLINE, on_online.as_ref().unchecked_ref()),
771 );
772 on_online.forget();
773 let on_offline: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
774 web_dispatch_system_event(SystemEvent::NetworkStatusChanged(NetworkStatus::Offline));
775 }) as Box<dyn FnMut(Event)>);
776 drop(
777 win.add_event_listener_with_callback(
778 WEB_EVENT_OFFLINE,
779 on_offline.as_ref().unchecked_ref(),
780 ),
781 );
782 on_offline.forget();
783 if let Ok(Some(mql)) = win.match_media(WEB_MEDIA_PREFERS_DARK) {
784 let mql_cb: MediaQueryList = mql.clone();
785 let on_theme: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
786 let next_theme: SystemTheme = if mql_cb.matches() {
787 ThemeMode::Dark
788 } else {
789 ThemeMode::Light
790 };
791 web_dispatch_system_event(SystemEvent::ThemeChanged(next_theme));
792 })
793 as Box<dyn FnMut(Event)>);
794 drop(
795 mql.add_event_listener_with_callback(
796 WEB_EVENT_CHANGE,
797 on_theme.as_ref().unchecked_ref(),
798 ),
799 );
800 on_theme.forget();
801 }
802 let win_hash: Window = win.clone();
803 let on_hash: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
804 if let Ok(href) = win_hash.location().href() {
805 web_dispatch_system_event(SystemEvent::DeepLink(href));
806 }
807 }) as Box<dyn FnMut(Event)>);
808 drop(
809 win.add_event_listener_with_callback(
810 WEB_EVENT_HASH_CHANGE,
811 on_hash.as_ref().unchecked_ref(),
812 ),
813 );
814 on_hash.forget();
815 let vv_key: JsValue = JsValue::from_str(WEB_PROP_VISUAL_VIEWPORT);
816 if let Ok(vv_val) = Reflect::get(win.as_ref(), &vv_key)
817 && let Ok(vv_target) = vv_val.clone().dyn_into::<EventTarget>()
818 {
819 let win_vv: Window = win.clone();
820 let vv_obj: JsValue = vv_val;
821 let on_vv_resize: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
822 let inner_h: f32 = win_vv
823 .inner_height()
824 .ok()
825 .and_then(|v: JsValue| v.as_f64())
826 .unwrap_or(0.0) as f32;
827 let h_key: JsValue = JsValue::from_str(WEB_PROP_HEIGHT);
828 let vv_h: f32 = Reflect::get(&vv_obj, &h_key)
829 .ok()
830 .and_then(|v: JsValue| v.as_f64())
831 .unwrap_or(inner_h as f64) as f32;
832 let kb_delta: f32 = (inner_h - vv_h).max(0.0);
833 let visible: bool = kb_delta >= WEB_KEYBOARD_MIN_DELTA_PX;
834 let height: f32 = if visible { kb_delta } else { 0.0 };
835 web_dispatch_system_event(SystemEvent::KeyboardVisibilityChanged { visible, height });
836 if web_sync_safe_area() {
837 web_mark_needs_frame();
838 }
839 })
840 as Box<dyn FnMut(Event)>);
841 drop(vv_target.add_event_listener_with_callback(
842 WEB_EVENT_RESIZE,
843 on_vv_resize.as_ref().unchecked_ref(),
844 ));
845 on_vv_resize.forget();
846 }
847}
848
849#[cfg(target_arch = "wasm32")]
860fn web_map_key(key: &str, code_str: &str) -> KeyCode {
861 match code_str {
862 "KeyW" => return KeyCode::Character('w'),
863 "KeyA" => return KeyCode::Character('a'),
864 "KeyS" => return KeyCode::Character('s'),
865 "KeyD" => return KeyCode::Character('d'),
866 "KeyE" => return KeyCode::Character('e'),
867 "KeyR" => return KeyCode::Character('r'),
868 "KeyP" => return KeyCode::Character('p'),
869 "KeyJ" => return KeyCode::Character('j'),
870 "Space" => return KeyCode::Space,
871 "ArrowLeft" => return KeyCode::ArrowLeft,
872 "ArrowRight" => return KeyCode::ArrowRight,
873 "ArrowUp" => return KeyCode::ArrowUp,
874 "ArrowDown" => return KeyCode::ArrowDown,
875 _ => {}
876 }
877 match key {
878 WEB_KEY_ENTER => KeyCode::Enter,
879 WEB_KEY_BACKSPACE => KeyCode::Backspace,
880 WEB_KEY_DELETE => KeyCode::Delete,
881 WEB_KEY_ESCAPE => KeyCode::Escape,
882 WEB_KEY_TAB => KeyCode::Tab,
883 WEB_KEY_SPACE => KeyCode::Space,
884 WEB_KEY_ARROW_LEFT => KeyCode::ArrowLeft,
885 WEB_KEY_ARROW_RIGHT => KeyCode::ArrowRight,
886 WEB_KEY_ARROW_UP => KeyCode::ArrowUp,
887 WEB_KEY_ARROW_DOWN => KeyCode::ArrowDown,
888 other => other
889 .chars()
890 .next()
891 .map(KeyCode::Character)
892 .unwrap_or(KeyCode::Unknown),
893 }
894}
895
896#[cfg(target_arch = "wasm32")]
902fn web_has_active_animations() -> bool {
903 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
904 match slot.try_borrow() {
905 Ok(guard) => guard
906 .as_ref()
907 .map(|(app, _): &(App, ShowcaseState)| app.has_active_animations())
908 .unwrap_or(false),
909 Err(_) => false,
910 }
911 })
912}
913
914#[cfg(target_arch = "wasm32")]
916fn web_mark_needs_frame() {
917 WEB_NEEDS_FRAME.with(|flag: &Cell<bool>| flag.set(true));
918}
919
920#[cfg(target_arch = "wasm32")]
930fn web_pointer_id_from_dom(ev: &web_sys::PointerEvent) -> u64 {
931 (ev.pointer_id() as i64).unsigned_abs().saturating_add(1)
932}
933
934#[cfg(target_arch = "wasm32")]
946fn web_pointer_from_dom(
947 ev: &web_sys::PointerEvent,
948 canvas: &HtmlCanvasElement,
949 force_pressed: Option<bool>,
950) -> PointerEvent {
951 let rect: DomRect = canvas.get_bounding_client_rect();
952 let x: f32 = (ev.client_x() as f64 - rect.left()) as f32;
953 let y: f32 = (ev.client_y() as f64 - rect.top()) as f32;
954 let pid: u64 = web_pointer_id_from_dom(ev);
955 let ptype: String = ev.pointer_type();
956 let device: PointerDevice = if ptype == WEB_PTR_TYPE_TOUCH {
957 PointerDevice::Touch
958 } else if ptype == WEB_PTR_TYPE_PEN {
959 PointerDevice::Stylus
960 } else {
961 PointerDevice::Mouse
962 };
963 let is_pressed: bool =
964 force_pressed.unwrap_or_else(|| ev.buttons() != 0 || device == PointerDevice::Touch);
965 let pressure: f32 = if is_pressed { 1.0 } else { 0.0 };
966 PointerEvent::new(
967 pid,
968 device,
969 Point::new(x, y),
970 PointerButton::Primary,
971 pressure,
972 Modifiers::default(),
973 )
974}
975
976#[cfg(target_arch = "wasm32")]
982fn web_queue_pointer_move_event(ptr: PointerEvent) {
983 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
984 if let Ok(mut borrow) = slot.try_borrow_mut()
985 && let Some((app, _)) = borrow.as_mut()
986 {
987 let wid: WindowId = app.get_window_state().get_id();
988 app.dispatch_window_event(WindowEvent::PointerMove(wid, ptr));
989 web_mark_needs_frame();
990 }
991 });
992}
993
994#[cfg(target_arch = "wasm32")]
1000fn web_queue_pointer_down_event(ptr: PointerEvent) {
1001 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1002 if let Ok(mut borrow) = slot.try_borrow_mut()
1003 && let Some((app, _)) = borrow.as_mut()
1004 {
1005 let wid: WindowId = app.get_window_state().get_id();
1006 app.dispatch_window_event(WindowEvent::PointerDown(wid, ptr));
1007 web_mark_needs_frame();
1008 }
1009 });
1010}
1011
1012#[cfg(target_arch = "wasm32")]
1018fn web_queue_pointer_up_event(ptr: PointerEvent) {
1019 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1020 if let Ok(mut borrow) = slot.try_borrow_mut()
1021 && let Some((app, _)) = borrow.as_mut()
1022 {
1023 let wid: WindowId = app.get_window_state().get_id();
1024 app.dispatch_window_event(WindowEvent::PointerUp(wid, ptr));
1025 web_mark_needs_frame();
1026 }
1027 });
1028}
1029
1030#[cfg(target_arch = "wasm32")]
1036fn web_queue_pointer_cancel(pointer_id: u64) {
1037 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1038 if let Ok(mut borrow) = slot.try_borrow_mut()
1039 && let Some((app, _)) = borrow.as_mut()
1040 {
1041 let wid: WindowId = app.get_window_state().get_id();
1042 app.dispatch_window_event(WindowEvent::PointerCancel(wid, pointer_id));
1043 web_mark_needs_frame();
1044 }
1045 });
1046}
1047
1048#[cfg(target_arch = "wasm32")]
1057fn web_queue_scroll_at(x: f32, y: f32, dx: f32, dy: f32) {
1058 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1059 if let Ok(mut borrow) = slot.try_borrow_mut()
1060 && let Some((app, _)) = borrow.as_mut()
1061 {
1062 let wid: WindowId = app.get_window_state().get_id();
1063 app.dispatch_window_event(WindowEvent::PointerMove(wid, PointerEvent::mouse(x, y)));
1064 app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(dx, dy)));
1065 web_mark_needs_frame();
1066 }
1067 });
1068}
1069
1070#[cfg(target_arch = "wasm32")]
1077fn web_queue_key_down(key: &str, code_str: &str) {
1078 if WEB_IME_COMPOSING.with(Cell::get) {
1079 return;
1080 }
1081 let ime_active: bool = WEB_IME_ACTIVE.with(Cell::get);
1082 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1083 if let Ok(mut borrow) = slot.try_borrow_mut()
1084 && let Some((app, _)) = borrow.as_mut()
1085 {
1086 let wid: WindowId = app.get_window_state().get_id();
1087 let code: KeyCode = web_map_key(key, code_str);
1088 let key_ev: WindowEvent =
1089 WindowEvent::KeyDown(wid, KeyEvent::new(code, Modifiers::default(), false));
1090 app.dispatch_window_event(key_ev);
1091 if !ime_active && key.chars().count() == 1 {
1092 app.dispatch_window_event(WindowEvent::TextInput(wid, key.to_string()));
1093 }
1094 web_mark_needs_frame();
1095 }
1096 });
1097}
1098
1099#[cfg(target_arch = "wasm32")]
1105fn web_queue_text_input(text: String) {
1106 if text.is_empty() {
1107 return;
1108 }
1109 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1110 if let Ok(mut borrow) = slot.try_borrow_mut()
1111 && let Some((app, _)) = borrow.as_mut()
1112 {
1113 let wid: WindowId = app.get_window_state().get_id();
1114 app.dispatch_window_event(WindowEvent::TextInput(wid, text));
1115 web_mark_needs_frame();
1116 }
1117 });
1118}
1119
1120#[cfg(target_arch = "wasm32")]
1126fn web_flush_ime_element(el: &HtmlElement) {
1127 let key: JsValue = JsValue::from_str(WEB_PROP_VALUE);
1128 if let Ok(val) = Reflect::get(el.as_ref(), &key)
1129 && let Some(text) = val.as_string()
1130 && !text.is_empty()
1131 {
1132 let _: Result<bool, JsValue> = Reflect::set(el.as_ref(), &key, &JsValue::from_str(""));
1133 web_queue_text_input(text);
1134 }
1135}
1136
1137#[cfg(target_arch = "wasm32")]
1143fn web_attach_ime_proxy(doc: &Document) {
1144 let Ok(raw_el) = doc.create_element(WEB_IME_INPUT_TAG) else {
1145 return;
1146 };
1147 let el: Element = raw_el;
1148 drop(el.set_attribute(WEB_IME_ATTR_ID, WEB_IME_INPUT_ID));
1149 drop(el.set_attribute(WEB_IME_ATTR_TYPE, WEB_IME_ATTR_TEXT));
1150 drop(el.set_attribute(WEB_IME_ATTR_AUTOCOMPLETE, WEB_IME_ATTR_OFF));
1151 drop(el.set_attribute(WEB_IME_ATTR_AUTOCORRECT, WEB_IME_ATTR_OFF));
1152 drop(el.set_attribute(WEB_IME_ATTR_AUTOCAPITALIZE, WEB_IME_ATTR_OFF));
1153 drop(el.set_attribute(WEB_IME_ATTR_SPELLCHECK, WEB_IME_ATTR_FALSE));
1154 drop(el.set_attribute(WEB_IME_ATTR_ARIA_LABEL, WEB_IME_ARIA_LABEL));
1155 drop(el.set_attribute(WEB_IME_ATTR_STYLE, WEB_IME_STYLE));
1156 let Ok(html_el) = el.dyn_into::<HtmlElement>() else {
1157 return;
1158 };
1159 if let Some(body) = doc.body() {
1160 drop(body.append_child(&html_el));
1161 }
1162 let comp_start: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1163 WEB_IME_COMPOSING.with(|c: &Cell<bool>| c.set(true));
1164 }) as Box<dyn FnMut(Event)>);
1165 drop(html_el.add_event_listener_with_callback(
1166 WEB_EVENT_COMPOSITION_START,
1167 comp_start.as_ref().unchecked_ref(),
1168 ));
1169 comp_start.forget();
1170 let comp_el: HtmlElement = html_el.clone();
1171 let comp_end: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1172 WEB_IME_COMPOSING.with(|c: &Cell<bool>| c.set(false));
1173 web_flush_ime_element(&comp_el);
1174 }) as Box<dyn FnMut(Event)>);
1175 drop(html_el.add_event_listener_with_callback(
1176 WEB_EVENT_COMPOSITION_END,
1177 comp_end.as_ref().unchecked_ref(),
1178 ));
1179 comp_end.forget();
1180 let inp_el: HtmlElement = html_el.clone();
1181 let on_input: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1182 if !WEB_IME_COMPOSING.with(Cell::get) {
1183 web_flush_ime_element(&inp_el);
1184 }
1185 }) as Box<dyn FnMut(Event)>);
1186 drop(
1187 html_el
1188 .add_event_listener_with_callback(WEB_EVENT_INPUT, on_input.as_ref().unchecked_ref()),
1189 );
1190 on_input.forget();
1191 let on_ime_blur: Closure<dyn FnMut(Event)> = Closure::wrap(Box::new(move |_: Event| {
1192 WEB_IME_ACTIVE.with(|a: &Cell<bool>| a.set(false));
1193 WEB_IME_COMPOSING.with(|c: &Cell<bool>| c.set(false));
1194 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1195 if let Ok(mut borrow) = slot.try_borrow_mut()
1196 && let Some((app, _)) = borrow.as_mut()
1197 {
1198 let wid: WindowId = app.get_window_state().get_id();
1199 app.dispatch_window_event(WindowEvent::Ime(wid, ImeEvent::Disabled));
1200 }
1201 });
1202 }) as Box<dyn FnMut(Event)>);
1203 drop(
1204 html_el
1205 .add_event_listener_with_callback(WEB_EVENT_BLUR, on_ime_blur.as_ref().unchecked_ref()),
1206 );
1207 on_ime_blur.forget();
1208 WEB_IME_ELEMENT.with(|slot: &RefCell<Option<HtmlElement>>| {
1209 if let Ok(mut guard) = slot.try_borrow_mut() {
1210 *guard = Some(html_el);
1211 }
1212 });
1213}
1214
1215#[cfg(target_arch = "wasm32")]
1227fn web_native_action_bridge(kind: &str, arg1: &str, _arg2: &str) -> bool {
1228 if kind == NATIVE_ACTION_FULLSCREEN {
1229 if arg1 == WEB_FS_ACTION_ON {
1230 web_set_fullscreen(true);
1231 return true;
1232 }
1233 if arg1 == WEB_FS_ACTION_OFF {
1234 web_set_fullscreen(false);
1235 return true;
1236 }
1237 return false;
1238 }
1239 if kind != NATIVE_ACTION_IME {
1240 return false;
1241 }
1242 WEB_IME_ELEMENT.with(|slot: &RefCell<Option<HtmlElement>>| {
1243 let Ok(guard) = slot.try_borrow() else {
1244 return false;
1245 };
1246 let Some(el) = guard.as_ref() else {
1247 return false;
1248 };
1249 if arg1 == WEB_IME_ACTION_SHOW {
1250 WEB_IME_ACTIVE.with(|a: &Cell<bool>| a.set(true));
1251 if let Some(win) = window()
1252 && let Some(doc) = win.document()
1253 && let Some(active_el) = doc.active_element()
1254 && active_el.id() == WEB_IME_INPUT_ID
1255 {
1256 drop(el.blur());
1257 }
1258 drop(el.focus());
1259 true
1260 } else if arg1 == WEB_IME_ACTION_HIDE {
1261 WEB_IME_ACTIVE.with(|a: &Cell<bool>| a.set(false));
1262 WEB_IME_COMPOSING.with(|c: &Cell<bool>| c.set(false));
1263 let key: JsValue = JsValue::from_str(WEB_PROP_VALUE);
1264 let _: Result<bool, JsValue> = Reflect::set(el.as_ref(), &key, &JsValue::from_str(""));
1265 drop(el.blur());
1266 true
1267 } else {
1268 false
1269 }
1270 })
1271}
1272
1273#[cfg(target_arch = "wasm32")]
1280fn web_queue_key_up(key: &str, code_str: &str) {
1281 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1282 if let Ok(mut borrow) = slot.try_borrow_mut()
1283 && let Some((app, _)) = borrow.as_mut()
1284 {
1285 let wid: WindowId = app.get_window_state().get_id();
1286 let code: KeyCode = web_map_key(key, code_str);
1287 app.dispatch_window_event(WindowEvent::KeyUp(
1288 wid,
1289 KeyEvent::new(code, Modifiers::default(), false),
1290 ));
1291 }
1292 });
1293}
1294
1295#[cfg(target_arch = "wasm32")]
1306fn web_sync_exact_viewport(win: &Window, canvas: &HtmlCanvasElement) -> bool {
1307 let rect: DomRect = canvas.get_bounding_client_rect();
1308 let css_w: f64 = if rect.width() >= 320.0 {
1309 rect.width()
1310 } else {
1311 win.inner_width()
1312 .ok()
1313 .and_then(|v: JsValue| v.as_f64())
1314 .filter(|w: &f64| *w >= 320.0)
1315 .unwrap_or(1200.0)
1316 };
1317 let css_h: f64 = if rect.height() >= 320.0 {
1318 rect.height()
1319 } else {
1320 win.inner_height()
1321 .ok()
1322 .and_then(|v: JsValue| v.as_f64())
1323 .filter(|h: &f64| *h >= 320.0)
1324 .unwrap_or(800.0)
1325 };
1326 let dpr_raw: f64 = win.device_pixel_ratio();
1327 let dpr_f64: f64 = if dpr_raw.is_finite() && dpr_raw > 0.0 {
1328 dpr_raw.clamp(0.5, 4.5)
1329 } else {
1330 1.0
1331 };
1332 let dpr: f32 = dpr_f64 as f32;
1333 let phys_w: u32 = (css_w * dpr_f64).round().max(1.0) as u32;
1334 let phys_h: u32 = (css_h * dpr_f64).round().max(1.0) as u32;
1335 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1336 let Ok(mut borrow) = slot.try_borrow_mut() else {
1337 return false;
1338 };
1339 let Some((app, _)) = borrow.as_mut() else {
1340 return false;
1341 };
1342 let ws: WindowState = app.get_window_state();
1343 let size_diff: bool = ws.get_physical_width() != phys_w
1344 || ws.get_physical_height() != phys_h
1345 || (ws.get_scale_factor() - dpr).abs() > 0.005
1346 || canvas.width() != phys_w
1347 || canvas.height() != phys_h;
1348 if !size_diff {
1349 return false;
1350 }
1351 if canvas.width() != phys_w {
1352 canvas.set_width(phys_w);
1353 }
1354 if canvas.height() != phys_h {
1355 canvas.set_height(phys_h);
1356 }
1357 app.set_exact_physical_viewport(phys_w, phys_h, dpr);
1358 true
1359 })
1360}
1361
1362#[cfg(target_arch = "wasm32")]
1368fn web_sync_safe_area() -> bool {
1369 let measured: SafeAreaInsets = web_query_safe_area_insets();
1370 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1371 let Ok(mut borrow) = slot.try_borrow_mut() else {
1372 return false;
1373 };
1374 let Some((app, _)) = borrow.as_mut() else {
1375 return false;
1376 };
1377 let effective: SafeAreaInsets = if app.is_immersive_fullscreen() {
1378 SafeAreaInsets::default()
1379 } else {
1380 measured
1381 };
1382 let current: SafeAreaInsets = app.get_context().get_safe_area().get_untracked();
1383 if current == effective {
1384 return false;
1385 }
1386 let wid: WindowId = app.get_window_state().get_id();
1387 app.dispatch_window_event(WindowEvent::SafeAreaChanged(wid, effective));
1388 true
1389 })
1390}
1391
1392#[cfg(target_arch = "wasm32")]
1398fn web_report_host_refresh_rate(measured_hz: f32) {
1399 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1400 if let Ok(mut borrow) = slot.try_borrow_mut()
1401 && let Some((app, _)) = borrow.as_mut()
1402 {
1403 let prev_fps: f32 = app.get_context().get_live_fps().get_untracked();
1404 app.report_host_refresh_rate(measured_hz);
1405 let next_fps: f32 = app.get_context().get_live_fps().get_untracked();
1406 if (next_fps - prev_fps).abs() >= 1.0 {
1407 web_mark_needs_frame();
1408 }
1409 }
1410 });
1411}
1412
1413#[cfg(target_arch = "wasm32")]
1423fn web_flush_frame(dt_secs: f32) -> u64 {
1424 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1425 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
1426 Ok(guard) => guard,
1427 Err(_) => return 0,
1428 };
1429 let Some((app, _)) = borrow.as_mut() else {
1430 return 0;
1431 };
1432 app.step_game_frame(dt_secs)
1433 .map(|stats: FrameStats| stats.get_frame_hash())
1434 .unwrap_or(0)
1435 })
1436}
1437
1438#[cfg(target_arch = "wasm32")]
1444#[wasm_bindgen]
1445pub fn euv_example_web_start() -> u64 {
1446 reset_reactive_runtime();
1447 match create_showcase_app(false, RenderMode::Software) {
1448 Ok((mut app, state)) => {
1449 if let Some(win) = window()
1450 && let Ok(hash_str) = win.location().hash()
1451 {
1452 let cleaned: &str = hash_str.trim_start_matches('#');
1453 if cleaned.starts_with('/') {
1454 let _: bool = state.get_route().set_if_changed(cleaned.to_string());
1455 }
1456 }
1457 let route_watch: Signal<String> = state.get_route();
1458 let (hash_scope, _): (Scope, Effect) = Scope::run(|_: Scope| {
1459 Effect::new(move || {
1460 let r: String = route_watch.get();
1461 if let Some(win) = window() {
1462 let target_hash: String = format!("#{r}");
1463 if win.location().hash().ok().as_deref() != Some(target_hash.as_str()) {
1464 let _: Result<(), JsValue> = win.location().set_hash(&target_hash);
1465 }
1466 }
1467 })
1468 });
1469 let root_id: NodeId = app
1470 .get_scene()
1471 .with_read(SceneTree::get_root, NodeId::default());
1472 app.get_scene().with_write(
1473 |tree: &mut SceneTree| {
1474 tree.attach_scope(root_id, hash_scope);
1475 },
1476 (),
1477 );
1478 let hash: u64 = app
1479 .step_frame()
1480 .map(|stats: FrameStats| stats.get_frame_hash())
1481 .unwrap_or(0);
1482 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1483 if let Ok(mut borrow) = slot.try_borrow_mut() {
1484 *borrow = Some((app, state));
1485 }
1486 });
1487 hash
1488 }
1489 Err(_) => 0,
1490 }
1491}
1492
1493#[cfg(target_arch = "wasm32")]
1503#[wasm_bindgen]
1504pub fn euv_example_render_route(route: &str) -> u64 {
1505 let has_runtime: bool = WEB_SHOWCASE_RUNTIME.with(
1506 |slot: &RefCell<Option<(App, ShowcaseState)>>| matches!(slot.try_borrow(), Ok(guard) if guard.is_some()),
1507 );
1508 if !has_runtime {
1509 let _: u64 = euv_example_web_start();
1510 }
1511 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1512 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
1513 Ok(guard) => guard,
1514 Err(_) => return 0,
1515 };
1516 let Some((app, state)) = borrow.as_mut() else {
1517 return 0;
1518 };
1519 let _: bool = state.get_route().set_if_changed(route.to_string());
1520 app.step_frame()
1521 .map(|stats: FrameStats| stats.get_frame_hash())
1522 .unwrap_or(0)
1523 })
1524}
1525
1526#[cfg(target_arch = "wasm32")]
1537#[wasm_bindgen]
1538pub fn euv_web_pointer_move(x: f32, y: f32) -> u64 {
1539 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1540 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
1541 Ok(guard) => guard,
1542 Err(_) => return 0,
1543 };
1544 let Some((app, _)) = borrow.as_mut() else {
1545 return 0;
1546 };
1547 let wid: WindowId = app.get_window_state().get_id();
1548 app.dispatch_window_event(WindowEvent::PointerMove(wid, PointerEvent::mouse(x, y)));
1549 app.step_frame()
1550 .map(|stats: FrameStats| stats.get_frame_hash())
1551 .unwrap_or(0)
1552 })
1553}
1554
1555#[cfg(target_arch = "wasm32")]
1566#[wasm_bindgen]
1567pub fn euv_web_pointer_down(x: f32, y: f32) -> u64 {
1568 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1569 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
1570 Ok(guard) => guard,
1571 Err(_) => return 0,
1572 };
1573 let Some((app, _)) = borrow.as_mut() else {
1574 return 0;
1575 };
1576 let wid: WindowId = app.get_window_state().get_id();
1577 app.dispatch_window_event(WindowEvent::PointerDown(wid, PointerEvent::mouse(x, y)));
1578 app.step_frame()
1579 .map(|stats: FrameStats| stats.get_frame_hash())
1580 .unwrap_or(0)
1581 })
1582}
1583
1584#[cfg(target_arch = "wasm32")]
1595#[wasm_bindgen]
1596pub fn euv_web_pointer_up(x: f32, y: f32) -> u64 {
1597 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1598 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
1599 Ok(guard) => guard,
1600 Err(_) => return 0,
1601 };
1602 let Some((app, _)) = borrow.as_mut() else {
1603 return 0;
1604 };
1605 let wid: WindowId = app.get_window_state().get_id();
1606 app.dispatch_window_event(WindowEvent::PointerUp(wid, PointerEvent::mouse(x, y)));
1607 app.step_frame()
1608 .map(|stats: FrameStats| stats.get_frame_hash())
1609 .unwrap_or(0)
1610 })
1611}
1612
1613#[cfg(target_arch = "wasm32")]
1624#[wasm_bindgen]
1625pub fn euv_web_scroll(dx: f32, dy: f32) -> u64 {
1626 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1627 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
1628 Ok(guard) => guard,
1629 Err(_) => return 0,
1630 };
1631 let Some((app, _)) = borrow.as_mut() else {
1632 return 0;
1633 };
1634 let wid: WindowId = app.get_window_state().get_id();
1635 app.dispatch_window_event(WindowEvent::Scroll(wid, Point::new(dx, dy)));
1636 app.step_frame()
1637 .map(|stats: FrameStats| stats.get_frame_hash())
1638 .unwrap_or(0)
1639 })
1640}
1641
1642#[cfg(target_arch = "wasm32")]
1652#[wasm_bindgen]
1653pub fn euv_web_key_down(key: &str) -> u64 {
1654 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1655 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
1656 Ok(guard) => guard,
1657 Err(_) => return 0,
1658 };
1659 let Some((app, state)) = borrow.as_mut() else {
1660 return 0;
1661 };
1662 let wid: WindowId = app.get_window_state().get_id();
1663 let code: KeyCode = match key {
1664 WEB_KEY_ENTER => KeyCode::Enter,
1665 WEB_KEY_BACKSPACE => KeyCode::Backspace,
1666 WEB_KEY_DELETE => KeyCode::Delete,
1667 WEB_KEY_ESCAPE => KeyCode::Escape,
1668 WEB_KEY_TAB => KeyCode::Tab,
1669 WEB_KEY_SPACE => KeyCode::Space,
1670 WEB_KEY_ARROW_LEFT => KeyCode::ArrowLeft,
1671 WEB_KEY_ARROW_RIGHT => KeyCode::ArrowRight,
1672 WEB_KEY_ARROW_UP => KeyCode::ArrowUp,
1673 WEB_KEY_ARROW_DOWN => KeyCode::ArrowDown,
1674 other => other
1675 .chars()
1676 .next()
1677 .map(KeyCode::Character)
1678 .unwrap_or(KeyCode::Unknown),
1679 };
1680 let key_ev: WindowEvent =
1681 WindowEvent::KeyDown(wid, KeyEvent::new(code, Modifiers::default(), false));
1682 state.get_game_host().ingest_event(&key_ev);
1683 app.dispatch_window_event(key_ev);
1684 if key.chars().count() == 1 {
1685 app.dispatch_window_event(WindowEvent::TextInput(wid, key.to_string()));
1686 }
1687 app.step_frame()
1688 .map(|stats: FrameStats| stats.get_frame_hash())
1689 .unwrap_or(0)
1690 })
1691}
1692
1693#[cfg(target_arch = "wasm32")]
1703#[wasm_bindgen]
1704pub fn euv_web_tick(dt_secs: f32) -> u64 {
1705 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1706 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
1707 Ok(guard) => guard,
1708 Err(_) => return 0,
1709 };
1710 let Some((app, state)) = borrow.as_mut() else {
1711 return 0;
1712 };
1713 if !app.should_pump_frames() {
1714 return app.get_renderer().get_last_stats().get_frame_hash();
1715 }
1716 let cur_route: String = state.get_route().get_untracked();
1717 let on_game: bool = cur_route == ROUTE_GAME || cur_route == ROUTE_GAME_3D;
1718 if on_game || app.has_active_animations() {
1719 return app
1720 .step_game_frame(dt_secs)
1721 .map(|stats: FrameStats| stats.get_frame_hash())
1722 .unwrap_or(0);
1723 }
1724 app.get_renderer().get_last_stats().get_frame_hash()
1725 })
1726}
1727
1728#[cfg(target_arch = "wasm32")]
1740#[wasm_bindgen]
1741pub fn euv_web_resize(width: u32, height: u32, dpr: f32) -> u64 {
1742 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1743 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
1744 Ok(guard) => guard,
1745 Err(_) => return 0,
1746 };
1747 let Some((app, _)) = borrow.as_mut() else {
1748 return 0;
1749 };
1750 let w: u32 = width.max(320);
1751 let h: u32 = height.max(320);
1752 let scale: f32 = if dpr.is_finite() && dpr > 0.0 {
1753 dpr.clamp(0.5, 4.5)
1754 } else {
1755 1.0
1756 };
1757 let phys_w: u32 = ((w as f64) * (scale as f64)).round().max(1.0) as u32;
1758 let phys_h: u32 = ((h as f64) * (scale as f64)).round().max(1.0) as u32;
1759 if let Some(win) = window()
1760 && let Some(doc) = win.document()
1761 && let Ok(Some(el)) = doc.query_selector(WEB_SELECTOR_CANVAS)
1762 && let Ok(canvas) = el.dyn_into::<HtmlCanvasElement>()
1763 {
1764 if canvas.width() != phys_w {
1765 canvas.set_width(phys_w);
1766 }
1767 if canvas.height() != phys_h {
1768 canvas.set_height(phys_h);
1769 }
1770 }
1771 app.set_exact_physical_viewport(phys_w, phys_h, scale);
1772 app.step_frame()
1773 .map(|stats: FrameStats| stats.get_frame_hash())
1774 .unwrap_or(0)
1775 })
1776}
1777
1778#[cfg(all(debug_assertions, target_arch = "wasm32"))]
1788#[wasm_bindgen]
1789pub fn euv_dev_ai_schema(request_json: &str) -> String {
1790 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1791 let mut borrow: RefMut<'_, Option<(App, ShowcaseState)>> = match slot.try_borrow_mut() {
1792 Ok(guard) => guard,
1793 Err(_) => return String::new(),
1794 };
1795 let Some((app, state)) = borrow.as_mut() else {
1796 return String::new();
1797 };
1798 let hooks: AiAppHooks = state.build_ai_hooks();
1799 AiSchemaProtocol::handle_json_with_hooks(app, request_json, Some(&hooks))
1800 })
1801}
1802
1803#[cfg(target_arch = "wasm32")]
1809#[wasm_bindgen]
1810pub fn euv_web_current_route() -> String {
1811 WEB_SHOWCASE_RUNTIME.with(|slot: &RefCell<Option<(App, ShowcaseState)>>| {
1812 match slot.try_borrow() {
1813 Ok(guard) => guard
1814 .as_ref()
1815 .map(|(_, state): &(App, ShowcaseState)| state.get_route().get_untracked())
1816 .unwrap_or_default(),
1817 Err(_) => String::new(),
1818 }
1819 })
1820}