1#![allow(clippy::type_complexity)]
2
3mod focus_reveal;
4mod fps_monitor;
5mod hit_path_tracker;
6pub mod inspector;
7mod modal_focus;
8mod shell_debug;
9mod shell_frame;
10mod shell_input;
11mod surface;
12mod wheel;
13use std::{
14 cell::RefCell,
15 fmt::{Debug, Write},
16 rc::Rc,
17 sync::{
18 Mutex, MutexGuard,
19 atomic::{AtomicBool, Ordering},
20 },
21};
22
23use cranpose_core::{
24 Applier, Composition, Key, MemoryApplier, NodeError, NodeId, collections::map::HashSet,
25 enter_event_handler_scope, location_key, run_in_mutable_snapshot,
26};
27pub use cranpose_foundation::{
28 DEFAULT_ROTARY_SCROLL_FACTOR_DP, Modifiers, PointerSource, RotaryScrollEvent,
29 rotary_scroll_pixels_from_detents,
30};
31use cranpose_foundation::{PointerButton, PointerButtons, PointerEvent, PointerEventKind};
32use cranpose_render_common::{HitTestTarget, RenderScene, Renderer};
33use cranpose_runtime_std::StdRuntime;
34use cranpose_ui::{
35 HeadlessRenderer, LayoutBox, LayoutNode, LayoutTree, MeasureLayoutOptions, SemanticsTree,
36 SubcomposeLayoutNode, WindowRootEntry, clear_transient_scroll_motion_contexts,
37 format_layout_tree, format_render_scene, format_screen_summary,
38 has_pending_focus_invalidations, has_pending_pointer_repasses,
39 has_pending_semantics_invalidations, peek_focus_invalidation, peek_layout_invalidation,
40 peek_pointer_invalidation, peek_render_invalidation, process_focus_invalidations,
41 process_pointer_repasses, process_semantics_invalidations, request_render_invalidation,
42 take_draw_repass_nodes, take_focus_invalidation, take_layout_invalidation,
43 take_pointer_invalidation, take_render_invalidation,
44};
45pub use cranpose_ui::{KeyCode, KeyEvent, KeyEventType};
46use cranpose_ui_graphics::{Point, PointerIcon, Rect, Size};
47pub use fps_monitor::FpsStats;
48use hit_path_tracker::PointerId;
49#[cfg(test)]
50use shell_frame::build_draw_refresh_scope;
51pub use surface::{RootId, RootSurface, SurfaceMut};
52use surface::{TextInputRouter, TextInputRoutes, partition_nodes_by_surface};
53use web_time::Instant;
54pub use wheel::WheelScroll;
55
56#[cfg(all(
57 feature = "clipboard-native",
58 not(target_arch = "wasm32"),
59 not(target_os = "android"),
60 not(target_os = "ios")
61))]
62struct ShellClipboard {
63 inner: std::rc::Rc<std::cell::RefCell<Option<arboard::Clipboard>>>,
64}
65
66#[cfg(all(
67 feature = "clipboard-native",
68 not(target_arch = "wasm32"),
69 not(target_os = "android"),
70 not(target_os = "ios")
71))]
72impl cranpose_ui::clipboard_session::PlatformClipboard for ShellClipboard {
73 fn write_text(&self, text: &str) {
74 if let Some(clipboard) = self.inner.borrow_mut().as_mut() {
75 let _ = clipboard.set_text(text);
76 }
77 }
78
79 fn read_text(&self) -> Option<String> {
80 self.inner
81 .borrow_mut()
82 .as_mut()
83 .and_then(|clipboard| clipboard.get_text().ok())
84 }
85}
86#[cfg(any(test, feature = "test-support"))]
87use cranpose_core::{
88 CompositionPassDebugStats, SlotId,
89 runtime::{RuntimeDebugStats, StateArenaDebugStats},
90 snapshot_pinning::{SnapshotPinningDebugStats, debug_snapshot_pinning_stats},
91 snapshot_state_observer::SnapshotStateObserverDebugStats,
92 snapshot_v2::{SnapshotV2DebugStats, debug_snapshot_v2_stats},
93};
94#[cfg(any(test, feature = "test-support"))]
95use cranpose_core::{
96 MemoryApplierDebugStats, RecomposeScopeRegistryDebugStats, SlotTableDebugStats,
97 debug_recompose_scope_registry_stats,
98};
99pub use cranpose_ui::{ImeEditorState, PlatformTextInputHandler};
100#[cfg(any(test, feature = "test-support"))]
101pub mod accessibility_audit;
102#[cfg(any(test, feature = "test-support"))]
103pub mod placed_semantics;
104
105#[derive(Debug, Clone, Copy, PartialEq, Default)]
115pub enum FrameRatePreference {
116 #[default]
120 Auto,
121 NoPreference,
123 Exact(f32),
126}
127
128impl FrameRatePreference {
129 pub const AUTO_QUIET_RATE_HZ: f32 = 60.0;
136
137 pub fn desired_rate_hz(
151 self,
152 producing_frames: bool,
153 interacting: bool,
154 panel_max_hz: Option<f32>,
155 ) -> f32 {
156 match self {
157 FrameRatePreference::Auto => {
158 if interacting {
159 panel_max_hz
160 .filter(|rate| *rate > 0.0)
161 .unwrap_or(Self::AUTO_QUIET_RATE_HZ)
162 } else if producing_frames {
163 Self::AUTO_QUIET_RATE_HZ
164 } else {
165 0.0
166 }
167 }
168 FrameRatePreference::NoPreference => 0.0,
169 FrameRatePreference::Exact(rate) if rate > 0.0 => rate,
170 FrameRatePreference::Exact(_) => 0.0,
171 }
172 }
173}
174
175pub(crate) struct ShellApp {
176 pub(crate) app_context: Rc<cranpose_ui::AppContext>,
177 pub(crate) runtime: StdRuntime,
178 pub(crate) composition: Composition<MemoryApplier>,
179 pub(crate) content: Box<dyn FnMut()>,
180 pub(crate) start_time: Instant,
181 pub(crate) last_frame_time_nanos: u64,
182 pub(crate) semantics_enabled: bool,
183 pub(crate) semantics_snapshot_revision: u64,
184 pub(crate) revealed_focus: Option<NodeId>,
185 pub(crate) layout_requested: bool,
186 pub(crate) force_layout_pass: bool,
187 pub(crate) modifiers: Option<Modifiers>,
188 pub(crate) rotary_scroll_factor: f32,
189 #[cfg(all(feature = "clipboard-native", target_os = "linux"))]
190 pub(crate) clipboard: Option<arboard::Clipboard>,
191 pub(crate) dev_options: DevOptions,
192 pub(crate) inspector_projector: Option<inspector::InspectorProjector>,
193 pub(crate) fps_monitor: fps_monitor::FpsMonitor,
194 pub(crate) text_input_routes: Rc<RefCell<TextInputRoutes>>,
195 pub(crate) text_input_router_installed: bool,
196 pub(crate) window_roots_seen: Option<u64>,
197}
198
199pub struct AppShell<R>
207where
208 R: Renderer,
209{
210 pub(crate) app: ShellApp,
211 pub(crate) surfaces: Vec<RootSurface<R>>,
212}
213
214#[derive(Clone, Copy, Debug, PartialEq, Eq)]
215pub struct PointerEventTime {
217 pub platform_time_ms: Option<i64>,
219 pub animation_time_nanos: u64,
221}
222
223fn update_stage_telemetry_threshold_ms() -> Option<f64> {
224 static THRESHOLD_MS: std::sync::OnceLock<Option<f64>> = std::sync::OnceLock::new();
225 *THRESHOLD_MS.get_or_init(|| {
226 std::env::var("CRANPOSE_UPDATE_STAGE_TELEMETRY_MS")
227 .ok()
228 .and_then(|value| value.parse::<f64>().ok())
229 .filter(|value| value.is_finite() && *value >= 0.0)
230 })
231}
232
233#[derive(Clone, Copy, Debug)]
234struct UpdateStageTelemetry {
235 started_at: Instant,
236 after_frame_callbacks: Instant,
237 after_ui_drain: Instant,
238 after_reconcile: Instant,
239 after_process_frame: Instant,
240 should_render: bool,
241 reconcile_attempted: bool,
242 reconcile_changed: bool,
243}
244
245fn log_update_stage_telemetry(telemetry: UpdateStageTelemetry) {
246 let Some(threshold_ms) = update_stage_telemetry_threshold_ms() else {
247 return;
248 };
249 let total_ms = telemetry
250 .after_process_frame
251 .duration_since(telemetry.started_at)
252 .as_secs_f64()
253 * 1000.0;
254 if total_ms < threshold_ms {
255 return;
256 }
257
258 let frame_callbacks_ms = telemetry
259 .after_frame_callbacks
260 .duration_since(telemetry.started_at)
261 .as_secs_f64()
262 * 1000.0;
263 let ui_drain_ms = telemetry
264 .after_ui_drain
265 .duration_since(telemetry.after_frame_callbacks)
266 .as_secs_f64()
267 * 1000.0;
268 let reconcile_ms = telemetry
269 .after_reconcile
270 .duration_since(telemetry.after_ui_drain)
271 .as_secs_f64()
272 * 1000.0;
273 let process_frame_ms = telemetry
274 .after_process_frame
275 .duration_since(telemetry.after_reconcile)
276 .as_secs_f64()
277 * 1000.0;
278 eprintln!(
279 "[update-stage-telemetry] total_ms={total_ms:.2} frame_callbacks_ms={frame_callbacks_ms:.2} ui_drain_ms={ui_drain_ms:.2} reconcile_ms={reconcile_ms:.2} process_frame_ms={process_frame_ms:.2} should_render={} reconcile_attempted={} reconcile_changed={}",
280 telemetry.should_render, telemetry.reconcile_attempted, telemetry.reconcile_changed
281 );
282}
283
284#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
285pub enum FramePacingMode {
286 #[default]
289 Vsync,
290 Hard60,
291 Hard120,
292 NoVsync,
295}
296
297impl FramePacingMode {
298 pub const ALL: [Self; 4] = [Self::Vsync, Self::Hard60, Self::Hard120, Self::NoVsync];
299
300 pub fn label(self) -> &'static str {
301 match self {
302 Self::Vsync => "VSync",
303 Self::Hard60 => "60fps",
304 Self::Hard120 => "120fps",
305 Self::NoVsync => "NoVSync",
306 }
307 }
308
309 pub fn target_fps(self) -> Option<u32> {
310 match self {
311 Self::Hard60 => Some(60),
312 Self::Hard120 => Some(120),
313 Self::Vsync | Self::NoVsync => None,
314 }
315 }
316}
317
318#[derive(Clone, Copy, Debug, PartialEq)]
319pub struct FrameSchedule {
320 pub needs_update: bool,
321 pub needs_frame: bool,
322 pub next_deadline: Option<web_time::Instant>,
323}
324
325#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
326pub struct FrameUpdateResult {
327 pub visual_changed: bool,
328 pub structure_changed: bool,
329}
330
331pub trait PlatformFrameDriver {
332 fn request_frame(&self);
333 fn request_wake_at(&self, deadline: web_time::Instant);
334 fn clear_wake(&self);
335}
336
337#[derive(Debug)]
338pub struct FrameScheduler {
339 update_pending: AtomicBool,
340 frame_pending: AtomicBool,
341 next_deadline: Mutex<Option<web_time::Instant>>,
342}
343
344impl Default for FrameScheduler {
345 fn default() -> Self {
346 Self {
347 update_pending: AtomicBool::new(false),
348 frame_pending: AtomicBool::new(false),
349 next_deadline: Mutex::new(None),
350 }
351 }
352}
353
354impl FrameScheduler {
355 fn lock_deadline(&self) -> MutexGuard<'_, Option<web_time::Instant>> {
356 self.next_deadline
357 .lock()
358 .unwrap_or_else(|poisoned| poisoned.into_inner())
359 }
360
361 pub fn record(&self, schedule: FrameSchedule) {
362 self.update_pending
363 .store(schedule.needs_update, Ordering::SeqCst);
364 self.frame_pending
365 .store(schedule.needs_frame, Ordering::SeqCst);
366 let mut next_deadline = self.lock_deadline();
367 *next_deadline = if schedule.needs_update {
368 None
369 } else {
370 schedule.next_deadline
371 };
372 }
373
374 pub fn schedule<D>(&self, schedule: FrameSchedule, driver: &D)
375 where
376 D: PlatformFrameDriver + ?Sized,
377 {
378 self.record(schedule);
379 schedule.apply_to(driver);
380 }
381
382 pub fn snapshot(&self) -> FrameSchedule {
383 FrameSchedule {
384 needs_update: self.update_pending.load(Ordering::SeqCst),
385 needs_frame: self.frame_pending.load(Ordering::SeqCst),
386 next_deadline: *self.lock_deadline(),
387 }
388 }
389}
390
391impl FrameSchedule {
392 pub fn apply_to<D>(self, driver: &D)
393 where
394 D: PlatformFrameDriver + ?Sized,
395 {
396 if self.needs_frame {
397 driver.clear_wake();
398 driver.request_frame();
399 } else if self.needs_update {
400 driver.request_wake_at(web_time::Instant::now());
401 } else if let Some(deadline) = self.next_deadline {
402 driver.request_wake_at(deadline);
403 } else {
404 driver.clear_wake();
405 }
406 }
407}
408
409#[derive(Clone, Copy, Debug)]
410pub(crate) struct DevOverlayControl {
411 bounds: Rect,
412 mode: FramePacingMode,
413}
414
415#[derive(Clone, Debug, Default)]
420pub struct DevOptions {
421 pub fps_counter: bool,
423 pub recomposition_counter: bool,
425 pub layout_timing: bool,
427 pub frame_pacing_controls: bool,
428 pub frame_pacing_mode: FramePacingMode,
429}
430
431#[cfg(any(test, feature = "test-support"))]
432#[doc(hidden)]
433#[derive(Clone, Copy, Debug)]
434pub struct RuntimeLeakDebugStats {
435 pub applier_stats: MemoryApplierDebugStats,
436 pub live_node_heap_bytes: usize,
437 pub recycled_node_heap_bytes: usize,
438 pub slot_table_heap_bytes: usize,
439 pub pass_stats: CompositionPassDebugStats,
440 pub slot_stats: SlotTableDebugStats,
441 pub observer_stats: SnapshotStateObserverDebugStats,
442 pub runtime_stats: RuntimeDebugStats,
443 pub state_arena_stats: StateArenaDebugStats,
444 pub recompose_scope_stats: RecomposeScopeRegistryDebugStats,
445 pub snapshot_v2_stats: SnapshotV2DebugStats,
446 pub snapshot_pinning_stats: SnapshotPinningDebugStats,
447}
448
449impl ShellApp {
450 pub(crate) fn request_layout_pass(&mut self) {
451 self.layout_requested = true;
452 }
453
454 pub(crate) fn request_forced_layout_pass(&mut self) {
455 self.layout_requested = true;
456 self.force_layout_pass = true;
457 }
458
459 pub(crate) fn composition_tree_needs_layout(&mut self) -> bool {
460 let Some(root) = self.composition.root() else {
461 return true;
462 };
463 let mut applier = self.composition.applier_mut();
464 cranpose_ui::tree_needs_layout(&mut *applier, root).unwrap_or_else(|err| {
465 log::warn!(
466 "Cannot check layout dirty status for root #{}: {}",
467 root,
468 err
469 );
470 true
471 })
472 }
473
474 pub(crate) fn has_stale_work_in_context(&self) -> bool {
475 self.layout_requested
476 || peek_render_invalidation()
477 || peek_pointer_invalidation()
478 || peek_focus_invalidation()
479 || peek_layout_invalidation()
480 || cranpose_ui::has_pending_layout_repasses()
481 || cranpose_ui::has_pending_measure_repasses()
482 || cranpose_ui::has_pending_draw_repasses()
483 || has_pending_pointer_repasses()
484 || has_pending_focus_invalidations()
485 }
486
487 pub(crate) fn wants_frame_in_context(&self) -> bool {
488 self.layout_requested
489 || peek_render_invalidation()
490 || peek_pointer_invalidation()
491 || peek_focus_invalidation()
492 || peek_layout_invalidation()
493 || self.composition.should_render()
494 }
495
496 pub(crate) fn needs_ui_update_in_context(&self, surfaces_dirty: bool) -> bool {
497 surfaces_dirty
498 || self.has_stale_work_in_context()
499 || self.composition.runtime_handle().has_pending_ui()
500 || has_pending_semantics_invalidations()
501 || self.composition.should_render()
502 }
503
504 pub(crate) fn next_event_time(&self) -> Option<web_time::Instant> {
505 let app_context = Rc::clone(&self.app_context);
506 app_context.enter(cranpose_ui::next_cursor_blink_time)
507 }
508
509 pub(crate) fn frame_time_nanos_at(&self, now: Instant) -> u64 {
510 now.checked_duration_since(self.start_time)
511 .unwrap_or_default()
512 .as_nanos()
513 .min(u128::from(u64::MAX)) as u64
514 }
515
516 pub(crate) fn realtime_pointer_event_time(
517 &self,
518 platform_time_ms: Option<i64>,
519 ) -> PointerEventTime {
520 PointerEventTime {
521 platform_time_ms,
522 animation_time_nanos: self
523 .frame_time_nanos_at(Instant::now())
524 .max(self.last_frame_time_nanos),
525 }
526 }
527
528 pub(crate) fn install_text_input_router(&mut self) {
529 if self.text_input_router_installed {
530 return;
531 }
532 let router = Rc::new(TextInputRouter {
533 routes: Rc::clone(&self.text_input_routes),
534 });
535 let app_context = Rc::clone(&self.app_context);
536 app_context
537 .enter(|| cranpose_ui::text_input_session::set_platform_text_input_handler(router));
538 self.text_input_router_installed = true;
539 }
540}
541
542impl<R> AppShell<R>
543where
544 R: Renderer,
545 R::Error: Debug,
546{
547 pub fn new(renderer: R, root_key: Key, content: impl FnMut() + 'static) -> Self {
548 Self::new_with_size(renderer, root_key, content, (800, 600), (800.0, 600.0))
549 }
550
551 pub fn new_with_size(
552 renderer: R,
553 root_key: Key,
554 content: impl FnMut() + 'static,
555 buffer_size: (u32, u32),
556 viewport: (f32, f32),
557 ) -> Self {
558 Self::new_with_size_and_density(renderer, root_key, content, buffer_size, viewport, 1.0)
559 }
560
561 pub fn new_with_size_and_density(
562 mut renderer: R,
563 root_key: Key,
564 content: impl FnMut() + 'static,
565 buffer_size: (u32, u32),
566 viewport: (f32, f32),
567 density: f32,
568 ) -> Self {
569 let app_context = cranpose_ui::AppContext::new_with_density(density);
570 let runtime = StdRuntime::new();
571 let mut composition = Composition::with_runtime(MemoryApplier::new(), runtime.runtime());
572 let app_content = Rc::new(std::cell::RefCell::new(content));
573 let mut build: Box<dyn FnMut()> = Box::new(move || {
574 let app_content = Rc::clone(&app_content);
575 cranpose_ui::widgets::PopupHost(move || {
576 (app_content.borrow_mut())();
577 });
578 });
579 renderer.attach_app_context_services(&app_context);
580 app_context.enter(|| {
581 #[cfg(all(
582 feature = "clipboard-native",
583 not(target_arch = "wasm32"),
584 not(target_os = "android"),
585 not(target_os = "ios")
586 ))]
587 {
588 let clipboard =
589 std::rc::Rc::new(std::cell::RefCell::new(arboard::Clipboard::new().ok()));
590 cranpose_ui::clipboard_session::set_platform_clipboard(std::rc::Rc::new(
591 ShellClipboard { inner: clipboard },
592 ));
593 }
594 if let Err(err) = composition.render_stable(root_key, &mut *build) {
595 log::error!("initial render failed: {err}");
596 }
597 });
598 renderer.scene_mut().clear();
599 let app = ShellApp {
600 app_context,
601 runtime,
602 composition,
603 content: build,
604 start_time: Instant::now(),
605 last_frame_time_nanos: 0,
606 semantics_enabled: false,
607 semantics_snapshot_revision: 0,
608 revealed_focus: None,
609 layout_requested: true,
610 force_layout_pass: true,
611 modifiers: None,
612 rotary_scroll_factor: DEFAULT_ROTARY_SCROLL_FACTOR_DP,
613 #[cfg(all(feature = "clipboard-native", target_os = "linux"))]
614 clipboard: arboard::Clipboard::new().ok(),
615 dev_options: DevOptions::default(),
616 inspector_projector: None,
617 fps_monitor: fps_monitor::FpsMonitor::new(),
618 text_input_routes: Rc::new(RefCell::new(TextInputRoutes::default())),
619 text_input_router_installed: false,
620 window_roots_seen: None,
621 };
622 let mut shell = Self {
623 app,
624 surfaces: vec![RootSurface::new(
625 RootId::Primary,
626 renderer,
627 buffer_size,
628 viewport,
629 )],
630 };
631 shell.process_frame();
632 shell
633 }
634
635 pub fn app_context(&self) -> &Rc<cranpose_ui::AppContext> {
640 &self.app.app_context
641 }
642
643 pub fn surface(&mut self, root: RootId) -> Option<SurfaceMut<'_, R>> {
646 let index = self.surface_index(root)?;
647 Some(SurfaceMut::new(self, index))
648 }
649
650 pub fn primary(&mut self) -> SurfaceMut<'_, R> {
652 SurfaceMut::new(self, 0)
653 }
654
655 pub fn root_holding_the_press(&mut self) -> Option<RootId> {
664 let pressed = self
665 .surfaces
666 .iter()
667 .find_map(|surface| surface.hit_path_tracker.dispatch_order(PointerId::PRIMARY))?;
668 let primary_root = self.app.composition.root()?;
669 let mut applier = self.app.composition.applier_mut();
670 let holder = pressed.into_iter().find_map(|node| {
671 let node = applier.scene_node_attached_to(node, primary_root)?;
672 Some(cranpose_ui::nearest_window_root(&mut applier, node))
673 })?;
674 drop(applier);
675 self.surfaces
676 .iter()
677 .find(|surface| surface.owns_nodes_under(holder))
678 .map(|surface| surface.id)
679 }
680
681 fn surface_index(&self, root: RootId) -> Option<usize> {
682 self.surfaces.iter().position(|surface| surface.id == root)
683 }
684
685 pub fn add_window_surface(
695 &mut self,
696 window: u64,
697 renderer: R,
698 buffer_size: (u32, u32),
699 viewport: (f32, f32),
700 ) -> Option<R> {
701 let previous = self.remove_window_surface(window);
702 self.surfaces.push(RootSurface::new(
703 RootId::Window(window),
704 renderer,
705 buffer_size,
706 viewport,
707 ));
708 self.app.window_roots_seen = None;
709 self.sync_window_roots();
710 previous
711 }
712
713 pub fn remove_window_surface(&mut self, window: u64) -> Option<R> {
715 let root = RootId::Window(window);
716 let index = self.surface_index(root)?;
717 self.app.text_input_routes.borrow_mut().remove(root);
718 Some(self.surfaces.remove(index).renderer)
719 }
720
721 pub fn surface_ids(&self) -> Vec<RootId> {
723 self.surfaces.iter().map(|surface| surface.id).collect()
724 }
725
726 pub fn window_roots(&self) -> Vec<WindowRootEntry> {
730 let app_context = Rc::clone(&self.app.app_context);
731 app_context.enter(cranpose_ui::window_roots)
732 }
733
734 pub fn window_roots_revision(&self) -> u64 {
738 let app_context = Rc::clone(&self.app.app_context);
739 app_context.enter(cranpose_ui::window_roots_revision)
740 }
741
742 pub fn primary_has_content(&mut self) -> bool {
747 let app_context = Rc::clone(&self.app.app_context);
748 app_context.enter(|| {
749 self.surfaces[0]
750 .layout_tree_in_context(&mut self.app)
751 .is_some_and(|tree| tree.root().children.iter().any(layout_has_area))
752 })
753 }
754
755 pub fn primary_content_size(&mut self) -> Option<Size> {
761 let app_context = Rc::clone(&self.app.app_context);
762 app_context.enter(|| {
763 self.surfaces[0]
764 .layout_tree_in_context(&mut self.app)
765 .and_then(|tree| {
766 tree.root()
767 .children
768 .iter()
769 .filter_map(layout_extent)
770 .reduce(farther_extent)
771 })
772 })
773 }
774
775 pub(crate) fn drag_and_drop_target_at(
781 &mut self,
782 point: cranpose_ui::DragAndDropPoint,
783 source: usize,
784 ) -> Option<(NodeId, cranpose_ui::Point)> {
785 let app_context = Rc::clone(&self.app.app_context);
786 let candidates: Vec<(usize, cranpose_ui::Point)> = match point.screen {
787 Some(screen) => (0..self.surfaces.len())
788 .rev()
789 .filter_map(|index| {
790 let local = self.surfaces[index].screen_point_inside(screen)?;
791 Some((index, local))
792 })
793 .collect(),
794 None => vec![(source, point.local)],
795 };
796 candidates.into_iter().find_map(|(index, local)| {
797 self.surfaces[index]
798 .renderer
799 .scene()
800 .hit_test_nodes(local.x, local.y)
801 .into_iter()
802 .find(|node| app_context.drag_and_drop().is_target(*node))
803 .map(|node| (node, local))
804 })
805 }
806
807 pub fn set_active_root(&mut self, root: RootId) {
811 self.app.text_input_routes.borrow_mut().set_active(root);
812 }
813
814 pub fn active_root(&self) -> RootId {
816 self.app.text_input_routes.borrow().active()
817 }
818
819 fn sync_window_roots(&mut self) {
820 let app_context = Rc::clone(&self.app.app_context);
821 app_context.enter(|| self.sync_window_roots_in_context());
822 }
823
824 pub(crate) fn sync_window_roots_in_context(&mut self) {
825 let revision = cranpose_ui::window_roots_revision();
826 if self.app.window_roots_seen == Some(revision) {
827 return;
828 }
829 self.app.window_roots_seen = Some(revision);
830 let entries = cranpose_ui::window_roots();
831 for surface in &mut self.surfaces {
832 let RootId::Window(id) = surface.id else {
833 continue;
834 };
835 let root = entries
836 .iter()
837 .find(|entry| entry.node as u64 == id)
838 .map(|entry| entry.node);
839 surface.set_root(root);
840 }
841 }
842
843 pub(crate) fn any_surface_dirty(&self) -> bool {
844 self.surfaces
845 .iter()
846 .any(|surface| surface.is_dirty || surface.scene_dirty)
847 }
848
849 pub(crate) fn mark_all_dirty(&mut self) {
850 for surface in &mut self.surfaces {
851 surface.is_dirty = true;
852 }
853 }
854
855 fn clear_surface_dirt(&mut self) {
856 for surface in &mut self.surfaces {
857 surface.is_dirty = false;
858 }
859 }
860
861 fn invalidate_dev_overlay_text(&mut self) {
862 for surface in &mut self.surfaces {
863 surface.invalidate_dev_overlay_text();
864 }
865 }
866
867 pub fn set_dev_options(&mut self, options: DevOptions) {
872 self.app.dev_options = options;
873 self.invalidate_dev_overlay_text();
874 let app_context = Rc::clone(&self.app.app_context);
875 app_context.enter(request_render_invalidation);
876 self.mark_all_dirty();
877 }
878
879 pub fn dev_options(&self) -> &DevOptions {
881 &self.app.dev_options
882 }
883
884 pub fn frame_pacing_mode(&self) -> FramePacingMode {
885 self.app.dev_options.frame_pacing_mode
886 }
887
888 pub fn current_fps(&self) -> f32 {
889 self.app.fps_monitor.current_fps()
890 }
891
892 pub fn fps_stats(&self) -> FpsStats {
893 self.app.fps_monitor.stats()
894 }
895
896 pub fn reset_fps_stats(&mut self) {
897 self.app.fps_monitor.reset_stats();
898 self.invalidate_dev_overlay_text();
899 }
900
901 pub fn record_presented_frame(
902 &mut self,
903 frame_started_at: Instant,
904 frame_finished_at: Instant,
905 ) {
906 self.app
907 .fps_monitor
908 .record_frame_work(frame_started_at, frame_finished_at);
909 }
910
911 #[cfg(any(test, feature = "test-support"))]
912 #[doc(hidden)]
913 pub fn record_presented_frame_for_test(
914 &mut self,
915 frame_started_nanos: u64,
916 frame_finished_nanos: u64,
917 ) {
918 let started = self.app.start_time + std::time::Duration::from_nanos(frame_started_nanos);
919 let finished = self.app.start_time + std::time::Duration::from_nanos(frame_finished_nanos);
920 self.record_presented_frame(started, finished);
921 }
922
923 pub fn set_frame_pacing_mode(&mut self, mode: FramePacingMode) {
924 if self.app.dev_options.frame_pacing_mode == mode {
925 return;
926 }
927 self.app.dev_options.frame_pacing_mode = mode;
928 self.invalidate_dev_overlay_text();
929 let app_context = Rc::clone(&self.app.app_context);
930 app_context.enter(request_render_invalidation);
931 self.mark_all_dirty();
932 }
933
934 pub fn dev_overlay_control_center(&self, mode: FramePacingMode) -> Option<(f32, f32)> {
941 self.surfaces[0].dev_overlay_control_center(mode)
942 }
943
944 pub fn set_viewport(&mut self, width: f32, height: f32) {
946 self.primary().set_viewport(width, height);
947 self.process_frame();
948 }
949
950 pub fn viewport_size(&self) -> (f32, f32) {
951 self.surfaces[0].viewport
952 }
953
954 pub fn set_screen_origin(&mut self, origin: Option<cranpose_ui_graphics::Point>) {
957 self.surfaces[0].screen_origin = origin;
958 }
959
960 pub fn set_buffer_size(&mut self, width: u32, height: u32) {
961 self.surfaces[0].buffer_size = (width, height);
962 }
963
964 pub fn buffer_size(&self) -> (u32, u32) {
965 self.surfaces[0].buffer_size
966 }
967
968 pub fn scene(&self) -> &R::Scene {
969 self.surfaces[0].renderer.scene()
970 }
971
972 pub fn renderer(&mut self) -> &mut R {
973 &mut self.surfaces[0].renderer
974 }
975
976 #[cfg(not(target_arch = "wasm32"))]
977 pub fn set_frame_waker(&mut self, waker: impl Fn() + Send + Sync + 'static) {
978 self.app.runtime.set_frame_waker(waker);
979 }
980
981 #[cfg(target_arch = "wasm32")]
982 pub fn set_frame_waker(&mut self, waker: impl Fn() + 'static) {
983 self.app.runtime.set_frame_waker(waker);
984 }
985
986 pub fn clear_frame_waker(&mut self) {
987 self.app.runtime.clear_frame_waker();
988 }
989
990 pub fn should_render(&self) -> bool {
991 let app_context = Rc::clone(&self.app.app_context);
992 app_context.enter(|| {
993 self.app.wants_frame_in_context()
994 || self.surfaces.iter().any(|surface| surface.scene_dirty)
995 })
996 }
997
998 pub fn needs_update(&self) -> bool {
999 let app_context = Rc::clone(&self.app.app_context);
1000 app_context.enter(|| {
1001 self.app
1002 .needs_ui_update_in_context(self.any_surface_dirty())
1003 })
1004 }
1005
1006 pub fn has_pending_ui(&self) -> bool {
1014 let app_context = Rc::clone(&self.app.app_context);
1015 app_context.enter(|| self.app.composition.runtime_handle().has_pending_ui())
1016 }
1017
1018 pub fn needs_redraw(&self) -> bool {
1031 let app_context = Rc::clone(&self.app.app_context);
1032 app_context.enter(|| self.surfaces[0].needs_redraw_in_context(&self.app))
1033 }
1034
1035 pub fn mark_dirty(&mut self) {
1037 self.surfaces[0].is_dirty = true;
1038 }
1039
1040 pub fn request_root_render(&mut self) {
1041 self.app.composition.request_root_render();
1042 self.app.request_forced_layout_pass();
1043 let app_context = Rc::clone(&self.app.app_context);
1044 app_context.enter(request_render_invalidation);
1045 self.mark_all_dirty();
1046 }
1047
1048 pub fn set_density(&mut self, density: f32) {
1049 let app_context = Rc::clone(&self.app.app_context);
1050 let changed = app_context.enter(|| {
1051 let previous = cranpose_ui::current_density().to_bits();
1052 cranpose_ui::set_density(density);
1053 previous != cranpose_ui::current_density().to_bits()
1054 });
1055 if changed {
1056 self.app.request_forced_layout_pass();
1057 self.mark_all_dirty();
1058 }
1059 }
1060
1061 pub fn set_font_scale(&mut self, font_scale: f32) {
1072 self.set_font_scale_curve(cranpose_ui::FontScaleCurve::linear(font_scale));
1073 }
1074
1075 pub fn set_font_scale_curve(&mut self, curve: cranpose_ui::FontScaleCurve) {
1082 let app_context = Rc::clone(&self.app.app_context);
1083 let changed = app_context.enter(|| {
1084 let previous = cranpose_ui::current_font_scale_curve();
1085 cranpose_ui::set_font_scale_curve(curve);
1086 previous != cranpose_ui::current_font_scale_curve()
1087 });
1088 if changed {
1089 self.app.request_forced_layout_pass();
1090 self.mark_all_dirty();
1091 }
1092 }
1093
1094 #[cfg(any(test, feature = "test-support"))]
1095 #[doc(hidden)]
1096 pub fn debug_current_density(&self) -> f32 {
1097 let app_context = Rc::clone(&self.app.app_context);
1098 app_context.enter(cranpose_ui::current_density)
1099 }
1100
1101 #[cfg(any(test, feature = "test-support"))]
1102 #[doc(hidden)]
1103 pub fn debug_current_font_scale(&self) -> f32 {
1104 let app_context = Rc::clone(&self.app.app_context);
1105 app_context.enter(cranpose_ui::current_font_scale)
1106 }
1107
1108 #[cfg(any(test, feature = "test-support"))]
1109 #[doc(hidden)]
1110 pub fn debug_current_font_scale_curve(&self) -> cranpose_ui::FontScaleCurve {
1111 let app_context = Rc::clone(&self.app.app_context);
1112 app_context.enter(cranpose_ui::current_font_scale_curve)
1113 }
1114
1115 #[cfg(any(test, feature = "test-support"))]
1116 #[doc(hidden)]
1117 pub fn debug_enter_app_context<T>(&self, block: impl FnOnce() -> T) -> T {
1118 let app_context = Rc::clone(&self.app.app_context);
1119 app_context.enter(block)
1120 }
1121
1122 pub fn has_active_animations(&self) -> bool {
1124 self.app.composition.should_render()
1125 }
1126
1127 pub fn has_transient_frame_callbacks(&self) -> bool {
1128 self.app
1129 .composition
1130 .runtime_handle()
1131 .has_transient_frame_callbacks()
1132 }
1133
1134 pub fn has_active_pointer_gesture(&self) -> bool {
1135 self.surfaces[0].has_active_pointer_gesture()
1136 }
1137
1138 pub fn frame_owed(&self) -> bool {
1140 self.surfaces[0].frame_owed
1141 }
1142
1143 pub fn take_frame_owed(&mut self) -> bool {
1145 std::mem::take(&mut self.surfaces[0].frame_owed)
1146 }
1147
1148 pub fn next_event_time(&self) -> Option<web_time::Instant> {
1151 self.app.next_event_time()
1152 }
1153
1154 fn compute_frame_schedule(&self) -> FrameSchedule {
1155 self.surfaces[0].compute_frame_schedule(&self.app, self.any_surface_dirty())
1156 }
1157
1158 pub fn frame_schedule(&self) -> FrameSchedule {
1159 let schedule = self.compute_frame_schedule();
1160 self.surfaces[0].frame_scheduler.record(schedule);
1161 schedule
1162 }
1163
1164 pub fn schedule_platform_frame<D>(&self, driver: &D) -> FrameSchedule
1165 where
1166 D: PlatformFrameDriver + ?Sized,
1167 {
1168 let schedule = self.compute_frame_schedule();
1169 self.surfaces[0].frame_scheduler.schedule(schedule, driver);
1170 schedule
1171 }
1172
1173 pub fn frame_scheduler_snapshot(&self) -> FrameSchedule {
1174 self.surfaces[0].frame_scheduler.snapshot()
1175 }
1176
1177 pub fn realtime_pointer_event_time(&self, platform_time_ms: Option<i64>) -> PointerEventTime {
1179 self.app.realtime_pointer_event_time(platform_time_ms)
1180 }
1181
1182 pub fn exact_pointer_event_time(&self, platform_time_ms: Option<i64>) -> PointerEventTime {
1184 PointerEventTime {
1185 platform_time_ms,
1186 animation_time_nanos: self.app.last_frame_time_nanos,
1187 }
1188 }
1189
1190 pub fn update_after_frame_interval(
1191 &mut self,
1192 frame_interval: std::time::Duration,
1193 ) -> FrameUpdateResult {
1194 let wall_frame_time = self.app.frame_time_nanos_at(Instant::now());
1195 let base_frame_time = self.app.last_frame_time_nanos.max(wall_frame_time);
1196 let frame_time = base_frame_time
1197 .saturating_add(frame_interval.as_nanos().min(u128::from(u64::MAX)) as u64);
1198 self.update_at_frame_time_nanos(frame_time)
1199 }
1200
1201 pub fn update_after_exact_interval(
1207 &mut self,
1208 frame_interval: std::time::Duration,
1209 ) -> FrameUpdateResult {
1210 let frame_time = self
1211 .app
1212 .last_frame_time_nanos
1213 .saturating_add(frame_interval.as_nanos().min(u128::from(u64::MAX)) as u64);
1214 self.update_at_frame_time_nanos(frame_time)
1215 }
1216
1217 pub fn update_at_frame_time_nanos(&mut self, frame_time: u64) -> FrameUpdateResult {
1218 let app_context = Rc::clone(&self.app.app_context);
1219 app_context.enter(|| {
1220 let update_started_at = Instant::now();
1221 let frame_time = frame_time.max(self.app.last_frame_time_nanos);
1222 self.app.last_frame_time_nanos = frame_time;
1223 let runtime_handle = self.app.runtime.runtime_handle();
1224 runtime_handle.with_deferred_state_releases(|| {
1225 self.app.runtime.drain_frame_callbacks(frame_time);
1226 let after_frame_callbacks = Instant::now();
1227 runtime_handle.drain_ui();
1228 let after_ui_drain = Instant::now();
1229 let should_render = self.app.composition.should_recompose();
1230 let mut reconcile_attempted = false;
1231 let mut reconcile_changed = false;
1232 if should_render {
1233 log::trace!(
1234 target: "cranpose::input",
1235 "update begin: should_render=true layout_requested={} scene_dirty={} is_dirty={}",
1236 self.app.layout_requested,
1237 self.surfaces[0].scene_dirty,
1238 self.surfaces[0].is_dirty
1239 );
1240 (reconcile_attempted, reconcile_changed) = self.reconcile_in_context();
1241 }
1242 let after_reconcile = Instant::now();
1243 let result = self.process_frame_in_context(reconcile_changed);
1244 let after_process_frame = Instant::now();
1245 log_update_stage_telemetry(UpdateStageTelemetry {
1246 started_at: update_started_at,
1247 after_frame_callbacks,
1248 after_ui_drain,
1249 after_reconcile,
1250 after_process_frame,
1251 should_render,
1252 reconcile_attempted,
1253 reconcile_changed,
1254 });
1255 self.clear_surface_dirt();
1256 result
1257 })
1258 })
1259 }
1260
1261 fn reconcile_in_context(&mut self) -> (bool, bool) {
1262 let Some(root_key) = self.app.composition.root_key() else {
1263 return (false, false);
1264 };
1265 match self
1266 .app
1267 .composition
1268 .reconcile(root_key, &mut *self.app.content)
1269 {
1270 Ok(changed) => {
1271 log::trace!(
1272 target: "cranpose::input",
1273 "reconcile changed={changed}"
1274 );
1275 if changed {
1276 self.app.fps_monitor.record_recomposition();
1277 if self.app.composition_tree_needs_layout() {
1278 self.app.request_layout_pass();
1279 }
1280 request_render_invalidation();
1281 }
1282 (true, changed)
1283 }
1284 Err(NodeError::Missing { id }) => {
1285 log::debug!("Recomposition skipped: node {} no longer exists", id);
1286 self.app.request_layout_pass();
1287 request_render_invalidation();
1288 (true, false)
1289 }
1290 Err(err) => {
1291 log::error!("recomposition failed: {err}");
1292 self.app.request_layout_pass();
1293 request_render_invalidation();
1294 (true, false)
1295 }
1296 }
1297 }
1298
1299 pub fn update(&mut self) -> FrameUpdateResult {
1300 let frame_time = self.app.frame_time_nanos_at(Instant::now());
1301 self.update_at_frame_time_nanos(frame_time)
1302 }
1303}
1304
1305impl<R> Drop for AppShell<R>
1306where
1307 R: Renderer,
1308{
1309 fn drop(&mut self) {
1310 self.app.runtime.clear_frame_waker();
1311 }
1312}
1313
1314fn layout_has_area(layout: &cranpose_ui::LayoutBox) -> bool {
1315 (layout.rect.width > 0.0 && layout.rect.height > 0.0)
1316 || layout.children.iter().any(layout_has_area)
1317}
1318
1319fn layout_extent(layout: &cranpose_ui::LayoutBox) -> Option<Size> {
1320 let own = (layout.rect.width > 0.0 && layout.rect.height > 0.0).then(|| {
1321 Size::new(
1322 layout.rect.x + layout.rect.width,
1323 layout.rect.y + layout.rect.height,
1324 )
1325 });
1326 layout
1327 .children
1328 .iter()
1329 .filter_map(layout_extent)
1330 .chain(own)
1331 .reduce(farther_extent)
1332}
1333
1334fn farther_extent(a: Size, b: Size) -> Size {
1335 Size::new(a.width.max(b.width), a.height.max(b.height))
1336}
1337
1338pub fn default_root_key() -> Key {
1339 location_key(file!(), line!(), column!())
1340}
1341
1342#[cfg(test)]
1343#[path = "tests/app_shell_frame_pacing_tests.rs"]
1344mod frame_pacing_tests;
1345
1346#[cfg(test)]
1347#[path = "tests/app_shell_tests.rs"]
1348mod tests;
1349
1350#[cfg(test)]
1351#[path = "tests/surface_tests.rs"]
1352mod surface_tests;