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