1#![deny(missing_docs)]
2#![doc = include_str!("../README.md")]
3
4mod focus_reveal;
5mod fps_monitor;
6mod frame_rate_boost;
7mod frame_scheduler;
8mod hit_path_tracker;
9pub mod inspector;
10mod modal_focus;
11mod requested_mouse_moves;
12#[cfg(debug_assertions)]
13mod semantics_check;
14mod shell_debug;
15#[expect(clippy::multiple_inherent_impl, reason = "one file per shell concern")]
16mod shell_frame;
17#[expect(clippy::multiple_inherent_impl, reason = "one file per shell concern")]
18mod shell_input;
19mod surface;
20mod touch_router;
21mod wheel;
22use std::{
23 cell::RefCell,
24 fmt::{Debug, Write},
25 rc::Rc,
26};
27
28use cranpose_core::{
29 Applier, Composition, MemoryApplier, NodeError, NodeId, NodeMarks, SceneNodeAttachmentScratch,
30 collections::map::HashSet, enter_event_handler_scope, location_key, run_in_mutable_snapshot,
31};
32pub use cranpose_foundation::{
33 DEFAULT_ROTARY_SCROLL_FACTOR_DP, Modifiers, PointerId, PointerSource, RotaryScrollEvent,
34 rotary_scroll_pixels_from_detents,
35};
36use cranpose_foundation::{PointerButton, PointerButtons, PointerEvent, PointerEventKind};
37use cranpose_render_common::{HitTestTarget, NodeUpdate, RenderScene, Renderer};
38use cranpose_runtime_std::StdRuntime;
39use cranpose_ui::{
40 AppContext, HeadlessRenderer, LayoutBox, LayoutNode, LayoutTree, SemanticsTree,
41 SubcomposeLayoutNode, WindowRootEntry, format_layout_tree, format_render_scene,
42 format_screen_summary, process_focus_invalidations, process_pointer_repasses,
43 process_semantics_invalidations, request_render_invalidation,
44};
45pub use cranpose_ui::{Key, KeyEvent, KeyEventType, NativeKeyEvent};
46use cranpose_ui_graphics::{Point, PointerIcon, Rect, Size};
47pub use fps_monitor::FpsStats;
48pub use frame_rate_boost::FrameRateBoost;
49pub use frame_scheduler::FrameScheduler;
50use shell_frame::Composed;
51#[cfg(test)]
52use shell_frame::build_draw_refresh_scope;
53pub use surface::{RootId, RootSurface, SurfaceMut};
54use surface::{SurfaceDirtyLane, TextInputRouter, TextInputRoutes, route_nodes_by_surface};
55pub use touch_router::TouchRouter;
56use web_time::Instant;
57pub use wheel::WheelScroll;
58
59#[cfg(all(
60 feature = "clipboard-native",
61 not(target_arch = "wasm32"),
62 not(target_os = "android"),
63 not(target_os = "ios")
64))]
65#[derive(Default)]
66struct ShellClipboard {
67 inner: std::cell::OnceCell<RefCell<Option<arboard::Clipboard>>>,
71}
72
73#[cfg(all(
74 feature = "clipboard-native",
75 not(target_arch = "wasm32"),
76 not(target_os = "android"),
77 not(target_os = "ios")
78))]
79impl ShellClipboard {
80 fn with<T>(
83 &self,
84 use_clipboard: impl FnOnce(&mut arboard::Clipboard) -> Option<T>,
85 ) -> Option<T> {
86 self.inner
87 .get_or_init(|| RefCell::new(arboard::Clipboard::new().ok()))
88 .borrow_mut()
89 .as_mut()
90 .and_then(use_clipboard)
91 }
92}
93
94#[cfg(all(
95 feature = "clipboard-native",
96 not(target_arch = "wasm32"),
97 not(target_os = "android"),
98 not(target_os = "ios")
99))]
100impl cranpose_ui::clipboard_session::PlatformClipboard for ShellClipboard {
101 fn write_text(&self, text: &str) {
102 self.with(|clipboard| clipboard.set_text(text).ok());
103 }
104
105 fn read_text(&self) -> Option<String> {
106 self.with(|clipboard| clipboard.get_text().ok())
107 }
108}
109#[cfg(any(test, feature = "test-support"))]
110use cranpose_core::{
111 CompositionPassDebugStats, MemoryApplierDebugStats, RecomposeScopeRegistryDebugStats, SlotId,
112 SlotTableDebugStats, debug_recompose_scope_registry_stats,
113 runtime::{RuntimeDebugStats, StateArenaDebugStats},
114 snapshot_pinning::{SnapshotPinningDebugStats, debug_snapshot_pinning_stats},
115 snapshot_v2::{SnapshotV2DebugStats, debug_snapshot_v2_stats},
116};
117pub use cranpose_ui::{ImeEditorState, PlatformTextInputHandler};
118const PAUSABLE_BUDGET: std::time::Duration = std::time::Duration::from_millis(4);
121#[cfg(any(test, feature = "test-support"))]
122pub mod accessibility_audit;
123#[cfg(any(test, feature = "test-support"))]
124pub mod placed_semantics;
125
126#[derive(Debug, Clone, Copy, PartialEq, Default)]
136pub enum FrameRatePreference {
137 #[default]
142 Auto,
143 NoPreference,
145 Exact(f32),
148}
149
150impl FrameRatePreference {
151 pub const AUTO_QUIET_RATE_HZ: f32 = 60.0;
158
159 pub fn desired_rate_hz(
173 self,
174 producing_frames: bool,
175 boosted: bool,
176 panel_max_hz: Option<f32>,
177 ) -> f32 {
178 match self {
179 Self::Auto => {
180 if boosted {
181 panel_max_hz
182 .filter(|rate| *rate > 0.0)
183 .unwrap_or(Self::AUTO_QUIET_RATE_HZ)
184 } else if producing_frames {
185 Self::AUTO_QUIET_RATE_HZ
186 } else {
187 0.0
188 }
189 }
190 Self::NoPreference => 0.0,
191 Self::Exact(rate) if rate > 0.0 => rate,
192 Self::Exact(_) => 0.0,
193 }
194 }
195}
196
197pub(crate) struct ShellApp {
198 pub(crate) app_context: Rc<AppContext>,
199 pub(crate) runtime: StdRuntime,
200 pub(crate) composition: Composition<MemoryApplier>,
201 pub(crate) content: Box<dyn FnMut()>,
202 pub(crate) start_time: Instant,
203 pub(crate) last_frame_time_nanos: u64,
204 pub(crate) semantics_enabled: bool,
205 pub(crate) semantics_snapshot_revision: u64,
206 pub(crate) revealed_focus: Option<NodeId>,
207 pub(crate) layout_requested: bool,
208 pub(crate) content_moved: bool,
209 pub(crate) force_layout_pass: bool,
210 pub(crate) modifiers: Option<Modifiers>,
211 pub(crate) rotary_scroll_factor: f32,
212 #[cfg(all(feature = "clipboard-native", target_os = "linux"))]
213 pub(crate) clipboard: Option<arboard::Clipboard>,
214 pub(crate) dev_options: DevOptions,
215 pub(crate) inspector_projector: Option<inspector::InspectorProjector>,
216 pub(crate) fps_monitor: fps_monitor::FpsMonitor,
217 pub(crate) text_input_routes: Rc<RefCell<TextInputRoutes>>,
218 pub(crate) text_input_router_installed: bool,
219 pub(crate) window_roots_seen: Option<u64>,
220 pub(crate) rebuilt_frames_since_observation_prune: u32,
222 #[cfg(feature = "installed-fonts")]
224 pub(crate) installed_fonts: usize,
225}
226
227pub struct AppShell<R>
235where
236 R: Renderer,
237{
238 pub(crate) app: ShellApp,
239 pub(crate) surfaces: Vec<RootSurface<R>>,
240 pub(crate) routing_scratch: SurfaceRoutingScratch,
241 pub(crate) pending_dirty_nodes: Vec<NodeId>,
242 pub(crate) pending_layer_property_nodes: Vec<NodeId>,
243 pub(crate) geometry_scene_nodes: cranpose_ui::GeometrySceneNodes,
244}
245
246#[derive(Default)]
247pub(crate) struct SurfaceRoutingScratch {
248 pub(crate) attached: Vec<Option<NodeId>>,
249 pub(crate) owners: Vec<Option<NodeId>>,
250 pub(crate) seen: HashSet<(usize, NodeId)>,
251 pub(crate) attachment: SceneNodeAttachmentScratch,
252 pub(crate) window_roots: cranpose_ui::WindowRootRoutingScratch,
253 pub(crate) laid_out: NodeMarks,
256 pub(crate) laid_out_starts: Vec<usize>,
258 pub(crate) moved: Vec<NodeId>,
260}
261
262#[derive(Clone, Copy, Debug, PartialEq, Eq)]
263pub struct PointerEventTime {
265 pub platform_time_ms: Option<i64>,
267 pub animation_time_nanos: u64,
269}
270
271fn update_stage_telemetry_threshold_ms() -> Option<f64> {
272 cranpose_core::DIAGNOSTICS
273 .update_stage_telemetry_ms
274 .threshold_ms()
275}
276
277type UpdateStages = cranpose_core::StageTimes<5>;
280
281struct UpdateOutcome {
282 should_render: bool,
283 reconcile_attempted: bool,
284 reconcile_changed: bool,
285}
286
287fn log_update_stage_telemetry(stages: &UpdateStages, outcome: UpdateOutcome) {
288 if let Some(threshold_ms) = update_stage_telemetry_threshold_ms() {
289 report_update_stages(threshold_ms, stages, outcome);
290 }
291}
292
293#[inline(never)]
296#[expect(clippy::print_stderr, reason = "an update telemetry threshold asks")]
297fn report_update_stages(threshold_ms: f64, stages: &UpdateStages, outcome: UpdateOutcome) {
298 let Some(
299 [
300 started_at,
301 after_frame_callbacks,
302 after_ui_drain,
303 after_reconcile,
304 after_process_frame,
305 ],
306 ) = stages.times()
307 else {
308 return;
309 };
310 let ms = cranpose_core::stage_ms;
311 let total_ms = ms(started_at, after_process_frame);
312 if total_ms < threshold_ms {
313 return;
314 }
315 eprintln!(
316 "[update-stage-telemetry] total_ms={total_ms:.2} frame_callbacks_ms={:.2} ui_drain_ms={:.2} reconcile_ms={:.2} process_frame_ms={:.2} should_render={} reconcile_attempted={} reconcile_changed={}",
317 ms(started_at, after_frame_callbacks),
318 ms(after_frame_callbacks, after_ui_drain),
319 ms(after_ui_drain, after_reconcile),
320 ms(after_reconcile, after_process_frame),
321 outcome.should_render,
322 outcome.reconcile_attempted,
323 outcome.reconcile_changed
324 );
325}
326
327#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
329pub enum FramePacingMode {
330 #[default]
333 Vsync,
334 Hard60,
336 Hard120,
338 NoVsync,
341}
342
343impl FramePacingMode {
344 pub const ALL: [Self; 4] = [Self::Vsync, Self::Hard60, Self::Hard120, Self::NoVsync];
346
347 pub fn label(self) -> &'static str {
349 match self {
350 Self::Vsync => "VSync",
351 Self::Hard60 => "60fps",
352 Self::Hard120 => "120fps",
353 Self::NoVsync => "NoVSync",
354 }
355 }
356
357 pub fn target_fps(self) -> Option<u32> {
360 match self {
361 Self::Hard60 => Some(60),
362 Self::Hard120 => Some(120),
363 Self::Vsync | Self::NoVsync => None,
364 }
365 }
366}
367
368#[derive(Clone, Copy, Debug, Default, PartialEq)]
371pub struct FrameSchedule {
372 pub needs_update: bool,
375 pub needs_frame: bool,
377 pub next_deadline: Option<Instant>,
380}
381
382#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
384pub struct FrameUpdateResult {
385 pub visual_changed: bool,
387 pub structure_changed: bool,
390 pub content_moved: bool,
395 pub content_redrawn: bool,
398}
399
400pub trait PlatformFrameDriver {
403 fn request_frame(&self);
405 fn request_wake_at(&self, deadline: Instant);
408 fn clear_wake(&self);
410}
411
412impl FrameSchedule {
413 pub fn is_idle(self) -> bool {
415 !self.needs_frame && !self.needs_update && self.next_deadline.is_none()
416 }
417
418 pub fn apply_to<D>(self, driver: &D)
421 where
422 D: PlatformFrameDriver + ?Sized,
423 {
424 if self.needs_frame {
425 driver.clear_wake();
426 driver.request_frame();
427 } else if self.needs_update {
428 driver.request_wake_at(Instant::now());
429 } else if let Some(deadline) = self.next_deadline {
430 driver.request_wake_at(deadline);
431 } else {
432 driver.clear_wake();
433 }
434 }
435}
436
437#[derive(Clone, Debug, Default)]
442pub struct DevOptions {
443 pub fps_counter: bool,
445 pub recomposition_counter: bool,
447 pub layout_timing: bool,
449 pub frame_pacing_controls: bool,
451 pub frame_pacing_mode: FramePacingMode,
453}
454
455#[cfg(any(test, feature = "test-support"))]
456#[doc(hidden)]
457#[derive(Clone, Copy, Debug)]
458pub struct RuntimeLeakDebugStats {
459 pub applier_stats: MemoryApplierDebugStats,
460 pub live_node_heap_bytes: usize,
461 pub recycled_node_heap_bytes: usize,
462 pub slot_table_heap_bytes: usize,
463 pub pass_stats: CompositionPassDebugStats,
464 pub slot_stats: SlotTableDebugStats,
465 pub runtime_stats: RuntimeDebugStats,
466 pub state_arena_stats: StateArenaDebugStats,
467 pub recompose_scope_stats: RecomposeScopeRegistryDebugStats,
468 pub snapshot_v2_stats: SnapshotV2DebugStats,
469 pub snapshot_pinning_stats: SnapshotPinningDebugStats,
470}
471
472impl ShellApp {
473 pub(crate) fn flush_semantics_invalidations(&mut self) {
474 if self.app_context.has_pending_semantics_invalidations() {
475 self.bubble_semantics_invalidations();
476 }
477 }
478
479 #[inline(never)]
482 fn bubble_semantics_invalidations(&mut self) {
483 let mut applier = self.composition.applier_mut();
484 process_semantics_invalidations(|node_id| {
485 cranpose_core::bubble_semantics_dirty(&mut *applier, node_id);
486 });
487 }
488
489 pub(crate) fn request_layout_pass(&mut self) {
490 self.layout_requested = true;
491 }
492
493 pub(crate) fn request_forced_layout_pass(&mut self) {
494 self.layout_requested = true;
495 self.force_layout_pass = true;
496 }
497
498 pub(crate) fn composition_tree_needs_layout(&mut self) -> bool {
499 let Some(root) = self.composition.root() else {
500 return true;
501 };
502 let mut applier = self.composition.applier_mut();
503 cranpose_ui::tree_needs_layout(&mut *applier, root).unwrap_or_else(|err| {
504 log::warn!("Cannot check layout dirty status for root #{root}: {err}");
505 true
506 })
507 }
508
509 pub(crate) fn has_stale_work_in_context(&self) -> bool {
510 self.layout_requested || self.app_context.has_stale_work()
511 }
512
513 pub(crate) fn wants_frame_in_context(&self) -> bool {
514 self.layout_requested
515 || self.app_context.has_pending_frame_work()
516 || self.composition.should_render()
517 }
518
519 pub(crate) fn needs_ui_update_in_context(&self, surfaces_dirty: bool) -> bool {
520 surfaces_dirty
521 || self.has_stale_work_in_context()
522 || self.composition.runtime().has_pending_ui()
523 || self.app_context.has_pending_semantics_invalidations()
524 || self.composition.should_render()
525 }
526
527 pub(crate) fn next_event_time(&self) -> Option<Instant> {
528 let blink = self.app_context.enter(cranpose_ui::next_cursor_blink_time);
529 match (blink, cranpose_core::concurrency::next_alarm_deadline()) {
530 (Some(blink), Some(alarm)) => Some(blink.min(alarm)),
531 (blink, alarm) => blink.or(alarm),
532 }
533 }
534
535 pub(crate) fn frame_time_nanos_at(&self, now: Instant) -> u64 {
536 now.checked_duration_since(self.start_time)
537 .unwrap_or_default()
538 .as_nanos()
539 .min(u128::from(u64::MAX)) as u64
540 }
541
542 pub(crate) fn realtime_pointer_event_time(
543 &self,
544 platform_time_ms: Option<i64>,
545 ) -> PointerEventTime {
546 PointerEventTime {
547 platform_time_ms,
548 animation_time_nanos: self
549 .frame_time_nanos_at(Instant::now())
550 .max(self.last_frame_time_nanos),
551 }
552 }
553
554 pub(crate) fn install_text_input_router(&mut self) {
555 if self.text_input_router_installed {
556 return;
557 }
558 let router = Rc::new(TextInputRouter {
559 routes: Rc::clone(&self.text_input_routes),
560 });
561 self.app_context
562 .enter(|| cranpose_ui::text_input_session::set_platform_text_input_handler(router));
563 self.text_input_router_installed = true;
564 }
565}
566
567#[expect(clippy::multiple_inherent_impl, reason = "one file per shell concern")]
568impl<R> AppShell<R>
569where
570 R: Renderer,
571 R::Error: Debug,
572{
573 pub fn new(renderer: R, root_key: cranpose_core::Key, content: impl FnMut() + 'static) -> Self {
576 Self::new_with_size(renderer, root_key, content, (800, 600), (800.0, 600.0))
577 }
578
579 pub fn new_with_size(
582 renderer: R,
583 root_key: cranpose_core::Key,
584 content: impl FnMut() + 'static,
585 buffer_size: (u32, u32),
586 viewport: (f32, f32),
587 ) -> Self {
588 Self::new_with_size_and_density(renderer, root_key, content, buffer_size, viewport, 1.0)
589 }
590
591 pub fn new_with_size_and_density(
594 mut renderer: R,
595 root_key: cranpose_core::Key,
596 content: impl FnMut() + 'static,
597 buffer_size: (u32, u32),
598 viewport: (f32, f32),
599 density: f32,
600 ) -> Self {
601 renderer.set_root_scale(density);
602 let runtime = StdRuntime::new();
603 let app_context = AppContext::new_with_density(density, Some(runtime.runtime_handle()));
604 let mut composition = Composition::with_runtime(MemoryApplier::new(), runtime.runtime());
605 composition.set_pausable_budget(Some(PAUSABLE_BUDGET));
606 let app_content = Rc::new(RefCell::new(content));
607 let mut build: Box<dyn FnMut()> = Box::new(move || {
608 let app_content = Rc::clone(&app_content);
609 cranpose_ui::density::ProvideDensity(cranpose_ui::Density::from_host(), move || {
610 cranpose_ui::widgets::PopupHost(move || {
611 (app_content.borrow_mut())();
612 });
613 });
614 });
615 renderer.attach_app_context_services(&app_context);
616 app_context.enter(|| {
617 #[cfg(all(
618 feature = "clipboard-native",
619 not(target_arch = "wasm32"),
620 not(target_os = "android"),
621 not(target_os = "ios")
622 ))]
623 {
624 cranpose_ui::clipboard_session::set_platform_clipboard(Rc::new(
625 ShellClipboard::default(),
626 ));
627 }
628 if let Err(err) = composition.render_stable(root_key, &mut *build) {
629 log::error!("initial render failed: {err}");
630 }
631 });
632 renderer.scene_mut().clear();
633 let app = ShellApp {
634 app_context,
635 runtime,
636 composition,
637 content: build,
638 start_time: Instant::now(),
639 last_frame_time_nanos: 0,
640 semantics_enabled: false,
641 semantics_snapshot_revision: 0,
642 revealed_focus: None,
643 layout_requested: true,
644 content_moved: false,
645 force_layout_pass: true,
646 modifiers: None,
647 rotary_scroll_factor: DEFAULT_ROTARY_SCROLL_FACTOR_DP,
648 #[cfg(all(feature = "clipboard-native", target_os = "linux"))]
649 clipboard: arboard::Clipboard::new().ok(),
650 dev_options: DevOptions::default(),
651 inspector_projector: None,
652 fps_monitor: fps_monitor::FpsMonitor::new(),
653 text_input_routes: Rc::new(RefCell::new(TextInputRoutes::default())),
654 text_input_router_installed: false,
655 window_roots_seen: None,
656 rebuilt_frames_since_observation_prune: 0,
657 #[cfg(feature = "installed-fonts")]
658 installed_fonts: 0,
659 };
660 let mut shell = Self {
661 app,
662 surfaces: vec![RootSurface::new(
663 RootId::Primary,
664 renderer,
665 buffer_size,
666 viewport,
667 )],
668 routing_scratch: SurfaceRoutingScratch::default(),
669 pending_dirty_nodes: Vec::new(),
670 pending_layer_property_nodes: Vec::new(),
671 geometry_scene_nodes: cranpose_ui::GeometrySceneNodes::default(),
672 };
673 shell.process_frame();
674 shell
675 }
676
677 pub fn app_context(&self) -> &Rc<AppContext> {
682 &self.app.app_context
683 }
684
685 pub fn surface(&mut self, root: RootId) -> Option<SurfaceMut<'_, R>> {
688 let index = self.surface_index(root)?;
689 Some(SurfaceMut::new(self, index))
690 }
691
692 pub fn primary(&mut self) -> SurfaceMut<'_, R> {
694 SurfaceMut::new(self, 0)
695 }
696
697 pub fn root_holding_the_press(&mut self) -> Option<RootId> {
706 let pressed = self
707 .surfaces
708 .iter()
709 .find_map(|surface| surface.hit_path_tracker.dispatch_order(PointerId::PRIMARY))?;
710 let primary_root = self.app.composition.root()?;
711 let mut applier = self.app.composition.applier_mut();
712 let holder = pressed.into_iter().find_map(|node| {
713 let node = applier.scene_node_attached_to(node, primary_root)?;
714 Some(cranpose_ui::nearest_window_root(&mut applier, node))
715 })?;
716 drop(applier);
717 self.surfaces
718 .iter()
719 .find(|surface| surface.owns_nodes_under(holder))
720 .map(|surface| surface.id)
721 }
722
723 fn surface_index(&self, root: RootId) -> Option<usize> {
724 self.surfaces.iter().position(|surface| surface.id == root)
725 }
726
727 pub fn add_window_surface(
737 &mut self,
738 window: NodeId,
739 renderer: R,
740 buffer_size: (u32, u32),
741 viewport: (f32, f32),
742 ) -> Option<R> {
743 let previous = self.remove_window_surface(window);
744 self.surfaces.push(RootSurface::new(
745 RootId::Window(window),
746 renderer,
747 buffer_size,
748 viewport,
749 ));
750 self.app.window_roots_seen = None;
751 self.sync_window_roots();
752 previous
753 }
754
755 pub fn remove_window_surface(&mut self, window: NodeId) -> Option<R> {
757 let root = RootId::Window(window);
758 let index = self.surface_index(root)?;
759 self.app.text_input_routes.borrow_mut().remove(root);
760 Some(self.surfaces.remove(index).renderer)
761 }
762
763 pub fn surface_ids(&self) -> Vec<RootId> {
765 self.surfaces.iter().map(|surface| surface.id).collect()
766 }
767
768 pub fn window_roots(&self) -> Vec<WindowRootEntry> {
772 self.app.app_context.enter(cranpose_ui::window_roots)
773 }
774
775 pub fn window_roots_revision(&self) -> u64 {
779 self.app
780 .app_context
781 .enter(cranpose_ui::window_roots_revision)
782 }
783
784 pub fn primary_has_content(&mut self) -> bool {
789 self.read_primary_boxes(cranpose_ui::has_placed_content)
790 .unwrap_or(false)
791 }
792
793 pub fn primary_content_size(&mut self) -> Option<Size> {
799 self.read_primary_boxes(cranpose_ui::placed_content_extent)
800 .flatten()
801 }
802
803 fn read_primary_boxes<T>(
807 &mut self,
808 read: impl FnOnce(&mut MemoryApplier, NodeId) -> Result<T, NodeError>,
809 ) -> Option<T> {
810 let _app_context = self.app.app_context.enter_scope();
811 let root = self.surfaces[0].root_node(&self.app)?;
812 let mut applier = self.app.composition.applier_mut();
813 read(&mut applier, root)
814 .inspect_err(|err| log::debug!("failed to read the primary root's boxes: {err}"))
815 .ok()
816 }
817
818 pub(crate) fn drag_and_drop_target_at(
824 &self,
825 point: cranpose_ui::DragAndDropPoint,
826 source: usize,
827 ) -> Option<(NodeId, Point)> {
828 let drag_and_drop = self.app.app_context.drag_and_drop();
829 let target_in = |index: usize, local: Point| {
830 self.surfaces[index]
831 .renderer
832 .scene()
833 .hit_test_nodes(local.x, local.y)
834 .into_iter()
835 .find(|node| drag_and_drop.is_target(*node))
836 .map(|node| (node, local))
837 };
838 match point.screen {
839 Some(screen) => (0..self.surfaces.len()).rev().find_map(|index| {
840 let local = self.surfaces[index].screen_point_inside(screen)?;
841 target_in(index, local)
842 }),
843 None => target_in(source, point.local),
844 }
845 }
846
847 pub fn set_active_root(&mut self, root: RootId) {
851 self.app.text_input_routes.borrow_mut().set_active(root);
852 }
853
854 pub fn active_root(&self) -> RootId {
856 self.app.text_input_routes.borrow().active()
857 }
858
859 fn sync_window_roots(&mut self) {
860 let _app_context = self.app.app_context.enter_scope();
861 self.sync_window_roots_in_context();
862 }
863
864 pub(crate) fn sync_window_roots_in_context(&mut self) {
865 let revision = self.app.app_context.window_roots().revision();
866 if self.app.window_roots_seen == Some(revision) {
867 return;
868 }
869 self.app.window_roots_seen = Some(revision);
870 let entries = cranpose_ui::window_roots();
871 for surface in &mut self.surfaces {
872 let RootId::Window(id) = surface.id else {
873 continue;
874 };
875 let root = entries
876 .iter()
877 .find(|entry| entry.node == id)
878 .map(|entry| entry.node);
879 surface.set_root(root);
880 }
881 }
882
883 pub(crate) fn any_surface_dirty(&self) -> bool {
884 self.surfaces
885 .iter()
886 .any(|surface| surface.is_dirty || surface.scene_dirty)
887 }
888
889 pub(crate) fn mark_all_dirty(&mut self) {
890 for surface in &mut self.surfaces {
891 surface.is_dirty = true;
892 }
893 }
894
895 fn invalidate_dev_overlay_text(&mut self) {
896 for surface in &mut self.surfaces {
897 surface.dev_overlay.invalidate();
898 }
899 }
900
901 pub fn set_dev_options(&mut self, options: DevOptions) {
906 self.app.dev_options = options;
907 self.invalidate_dev_overlay_text();
908 self.app.app_context.enter(request_render_invalidation);
909 self.mark_all_dirty();
910 }
911
912 pub fn dev_options(&self) -> &DevOptions {
914 &self.app.dev_options
915 }
916
917 pub fn frame_pacing_mode(&self) -> FramePacingMode {
919 self.app.dev_options.frame_pacing_mode
920 }
921
922 pub fn current_fps(&self) -> f32 {
924 self.app.fps_monitor.current_fps()
925 }
926
927 pub fn fps_stats(&self) -> FpsStats {
929 self.app.fps_monitor.stats()
930 }
931
932 pub fn reset_fps_stats(&mut self) {
934 self.app.fps_monitor.reset_stats();
935 self.invalidate_dev_overlay_text();
936 }
937
938 pub fn record_presented_frame(
941 &mut self,
942 frame_started_at: Instant,
943 frame_finished_at: Instant,
944 ) {
945 self.app
946 .fps_monitor
947 .record_frame_work(frame_started_at, frame_finished_at);
948 }
949
950 #[cfg(any(test, feature = "test-support"))]
951 #[doc(hidden)]
952 pub fn record_presented_frame_for_test(
953 &mut self,
954 frame_started_nanos: u64,
955 frame_finished_nanos: u64,
956 ) {
957 let started = self.app.start_time + std::time::Duration::from_nanos(frame_started_nanos);
958 let finished = self.app.start_time + std::time::Duration::from_nanos(frame_finished_nanos);
959 self.record_presented_frame(started, finished);
960 }
961
962 pub fn set_frame_pacing_mode(&mut self, mode: FramePacingMode) {
965 if self.app.dev_options.frame_pacing_mode == mode {
966 return;
967 }
968 self.app.dev_options.frame_pacing_mode = mode;
969 self.invalidate_dev_overlay_text();
970 self.app.app_context.enter(request_render_invalidation);
971 self.mark_all_dirty();
972 }
973
974 pub fn dev_overlay_control_center(&self, mode: FramePacingMode) -> Option<(f32, f32)> {
981 self.surfaces[0].dev_overlay.control_center(mode)
982 }
983
984 pub fn set_viewport(&mut self, width: f32, height: f32) {
987 if self.surfaces[0].viewport == (width, height) {
988 return;
989 }
990 self.primary().set_viewport(width, height);
991 self.process_frame();
992 }
993
994 pub fn viewport_size(&self) -> (f32, f32) {
996 self.surfaces[0].viewport
997 }
998
999 pub fn set_screen_origin(&mut self, origin: Option<Point>) {
1002 self.surfaces[0].screen_origin = origin;
1003 }
1004
1005 pub fn set_buffer_size(&mut self, width: u32, height: u32) {
1007 self.surfaces[0].buffer_size = (width, height);
1008 }
1009
1010 pub fn buffer_size(&self) -> (u32, u32) {
1012 self.surfaces[0].buffer_size
1013 }
1014
1015 pub fn scene(&self) -> &R::Scene {
1017 self.surfaces[0].renderer.scene()
1018 }
1019
1020 pub fn renderer(&mut self) -> &mut R {
1022 &mut self.surfaces[0].renderer
1023 }
1024
1025 #[cfg(not(target_arch = "wasm32"))]
1028 pub fn set_frame_waker(&mut self, waker: impl Fn() + Send + Sync + 'static) {
1029 self.app.runtime.set_frame_waker(waker);
1030 }
1031
1032 #[cfg(target_arch = "wasm32")]
1035 pub fn set_frame_waker(&mut self, waker: impl Fn() + 'static) {
1036 self.app.runtime.set_frame_waker(waker);
1037 }
1038
1039 pub fn clear_frame_waker(&mut self) {
1041 self.app.runtime.clear_frame_waker();
1042 }
1043
1044 pub fn should_render(&self) -> bool {
1047 self.app.app_context.enter(|| {
1048 self.app.wants_frame_in_context()
1049 || self.surfaces.iter().any(|surface| surface.scene_dirty)
1050 })
1051 }
1052
1053 pub fn needs_update(&self) -> bool {
1056 self.app.app_context.enter(|| {
1057 self.app
1058 .needs_ui_update_in_context(self.any_surface_dirty())
1059 })
1060 }
1061
1062 pub fn needs_update_without_frame(&self) -> bool {
1065 self.app.app_context.enter(|| {
1066 self.any_surface_dirty()
1067 || self.app.has_stale_work_in_context()
1068 || self.app.composition.should_recompose()
1069 || self.app.composition.runtime().has_pending_ui()
1070 || self.app.app_context.has_pending_semantics_invalidations()
1071 || cranpose_ui::next_cursor_blink_time().is_some_and(|at| at <= Instant::now())
1072 || self
1073 .surfaces
1074 .iter()
1075 .any(|surface| surface.renderer_warmup_due(&self.app))
1076 })
1077 }
1078
1079 pub fn has_pending_ui(&self) -> bool {
1087 self.app.composition.runtime().has_pending_ui()
1088 }
1089
1090 pub fn run_pending_tasks(&mut self) {
1097 if !self.app.composition.runtime().has_pending_ui() {
1100 return;
1101 }
1102 let runtime_handle = self.app.composition.runtime_handle();
1103 self.app.app_context.enter(|| {
1104 runtime_handle.with_deferred_state_releases(|| runtime_handle.drain_ui());
1105 });
1106 }
1107
1108 pub fn needs_redraw(&self) -> bool {
1121 self.app
1122 .app_context
1123 .enter(|| self.surfaces[0].needs_redraw_in_context(&self.app))
1124 }
1125
1126 pub fn mark_dirty(&mut self) {
1128 self.surfaces[0].is_dirty = true;
1129 }
1130
1131 pub fn request_root_render(&mut self) {
1134 self.app.composition.request_root_render();
1135 self.app.request_forced_layout_pass();
1136 self.app.app_context.enter(request_render_invalidation);
1137 self.mark_all_dirty();
1138 }
1139
1140 pub fn set_density(&mut self, density: f32) {
1143 self.surfaces[0].renderer.set_root_scale(density);
1144 let changed = self.app.app_context.enter(|| {
1145 let previous = cranpose_ui::current_density().to_bits();
1146 cranpose_ui::set_density(density);
1147 previous != cranpose_ui::current_density().to_bits()
1148 });
1149 if changed {
1150 self.request_root_render();
1151 }
1152 }
1153
1154 pub fn set_font_scale(&mut self, font_scale: f32) {
1165 self.set_font_scale_curve(cranpose_ui::FontScaleCurve::linear(font_scale));
1166 }
1167
1168 pub fn set_font_scale_curve(&mut self, curve: cranpose_ui::FontScaleCurve) {
1175 let changed = self.app.app_context.enter(|| {
1176 let previous = cranpose_ui::current_font_scale_curve();
1177 cranpose_ui::set_font_scale_curve(curve);
1178 previous != cranpose_ui::current_font_scale_curve()
1179 });
1180 if changed {
1181 self.request_root_render();
1182 }
1183 }
1184
1185 #[cfg(any(test, feature = "test-support"))]
1186 #[doc(hidden)]
1187 pub fn debug_current_density(&self) -> f32 {
1188 self.app.app_context.enter(cranpose_ui::current_density)
1189 }
1190
1191 #[cfg(any(test, feature = "test-support"))]
1192 #[doc(hidden)]
1193 pub fn debug_current_font_scale(&self) -> f32 {
1194 self.app.app_context.enter(cranpose_ui::current_font_scale)
1195 }
1196
1197 #[cfg(any(test, feature = "test-support"))]
1198 #[doc(hidden)]
1199 pub fn debug_current_font_scale_curve(&self) -> cranpose_ui::FontScaleCurve {
1200 self.app
1201 .app_context
1202 .enter(cranpose_ui::current_font_scale_curve)
1203 }
1204
1205 #[cfg(any(test, feature = "test-support"))]
1206 #[doc(hidden)]
1207 pub fn debug_enter_app_context<T>(&self, block: impl FnOnce() -> T) -> T {
1208 self.app.app_context.enter(block)
1209 }
1210
1211 pub fn has_active_animations(&self) -> bool {
1213 self.app.composition.should_render()
1214 }
1215
1216 pub fn has_transient_frame_callbacks(&self) -> bool {
1219 self.app
1220 .composition
1221 .runtime()
1222 .has_transient_frame_callbacks()
1223 }
1224
1225 pub fn has_active_pointer_gesture(&self) -> bool {
1227 self.surfaces[0].has_active_pointer_gesture()
1228 }
1229
1230 pub fn has_active_primary_gesture(&self) -> bool {
1232 self.surfaces[0].has_active_primary_gesture()
1233 }
1234
1235 pub fn frame_owed(&self) -> bool {
1237 self.surfaces[0].frame_owed
1238 }
1239
1240 pub fn take_frame_owed(&mut self) -> bool {
1242 std::mem::take(&mut self.surfaces[0].frame_owed)
1243 }
1244
1245 pub fn next_event_time(&self) -> Option<Instant> {
1249 self.app.next_event_time()
1250 }
1251
1252 fn compute_frame_schedule(&self) -> FrameSchedule {
1253 self.surfaces[0].compute_frame_schedule(&self.app, self.any_surface_dirty())
1254 }
1255
1256 pub fn frame_schedule(&self) -> FrameSchedule {
1259 let schedule = self.compute_frame_schedule();
1260 self.surfaces[0].frame_scheduler.record(schedule);
1261 schedule
1262 }
1263
1264 pub fn schedule_platform_frame<D>(&self, driver: &D) -> FrameSchedule
1267 where
1268 D: PlatformFrameDriver + ?Sized,
1269 {
1270 let schedule = self.compute_frame_schedule();
1271 self.surfaces[0].frame_scheduler.schedule(schedule, driver);
1272 schedule
1273 }
1274
1275 pub fn frame_scheduler_snapshot(&self) -> FrameSchedule {
1278 self.surfaces[0].frame_scheduler.snapshot()
1279 }
1280
1281 pub fn realtime_pointer_event_time(&self, platform_time_ms: Option<i64>) -> PointerEventTime {
1283 self.app.realtime_pointer_event_time(platform_time_ms)
1284 }
1285
1286 pub fn exact_pointer_event_time(&self, platform_time_ms: Option<i64>) -> PointerEventTime {
1288 PointerEventTime {
1289 platform_time_ms,
1290 animation_time_nanos: self.app.last_frame_time_nanos,
1291 }
1292 }
1293
1294 pub fn update_after_frame_interval(
1297 &mut self,
1298 frame_interval: std::time::Duration,
1299 ) -> FrameUpdateResult {
1300 let wall_frame_time = self.app.frame_time_nanos_at(Instant::now());
1301 let base_frame_time = self.app.last_frame_time_nanos.max(wall_frame_time);
1302 let frame_time = base_frame_time
1303 .saturating_add(frame_interval.as_nanos().min(u128::from(u64::MAX)) as u64);
1304 self.update_at_frame_time_nanos(frame_time)
1305 }
1306
1307 pub fn update_after_exact_interval(
1313 &mut self,
1314 frame_interval: std::time::Duration,
1315 ) -> FrameUpdateResult {
1316 let frame_time = self
1317 .app
1318 .last_frame_time_nanos
1319 .saturating_add(frame_interval.as_nanos().min(u128::from(u64::MAX)) as u64);
1320 self.update_at_frame_time_nanos(frame_time)
1321 }
1322
1323 pub fn dispatch_frame_at(&mut self, frame_time: Instant) {
1329 let frame_time = self.app.frame_time_nanos_at(frame_time);
1330 let _app_context = self.app.app_context.enter_scope();
1331 let runtime_handle = self.app.runtime.runtime_handle();
1332 runtime_handle.with_deferred_state_releases(|| {
1333 self.app.last_frame_time_nanos = frame_time.max(self.app.last_frame_time_nanos);
1334 self.app
1335 .runtime
1336 .drain_frame_callbacks(self.app.last_frame_time_nanos);
1337 self.apply_pointer_claim();
1338 runtime_handle.drain_ui();
1339 self.dispatch_requested_mouse_moves(self.app.last_frame_time_nanos);
1340 });
1341 }
1342
1343 pub fn update_without_frame(&mut self) -> FrameUpdateResult {
1346 self.update_with_frame_time(None)
1347 }
1348
1349 pub fn update_at_frame_time_nanos(&mut self, frame_time: u64) -> FrameUpdateResult {
1353 self.update_with_frame_time(Some(frame_time))
1354 }
1355
1356 #[inline(never)]
1360 fn update_with_frame_time(&mut self, frame_time: Option<u64>) -> FrameUpdateResult {
1361 let _app_context = self.app.app_context.enter_scope();
1362 let mut stages = UpdateStages::start(update_stage_telemetry_threshold_ms().is_some());
1363 let runtime_handle = self.app.runtime.runtime_handle();
1364 runtime_handle.with_deferred_state_releases(|| {
1365 if let Some(frame_time) = frame_time {
1366 self.app.last_frame_time_nanos = frame_time.max(self.app.last_frame_time_nanos);
1367 self.app.runtime.drain_frame_callbacks(self.app.last_frame_time_nanos);
1368 self.apply_pointer_claim();
1369 }
1370 stages.reached();
1371 runtime_handle.drain_ui();
1372 self.dispatch_requested_mouse_moves(self.app.last_frame_time_nanos);
1373 stages.reached();
1374 let should_render = self.app.composition.should_recompose();
1375 let composed = if should_render {
1376 log::trace!(
1377 target: "cranpose::input",
1378 "update begin: should_render=true layout_requested={} scene_dirty={} is_dirty={}",
1379 self.app.layout_requested,
1380 self.surfaces[0].scene_dirty,
1381 self.surfaces[0].is_dirty
1382 );
1383 self.compose_phase()
1384 } else {
1385 Composed::SKIPPED
1386 };
1387 stages.reached();
1388 let outcome = UpdateOutcome {
1389 should_render,
1390 reconcile_attempted: composed.attempted(),
1391 reconcile_changed: composed.recomposed(),
1392 };
1393 let result = self.process_frame_in_context(composed);
1394 stages.reached();
1395 log_update_stage_telemetry(&stages, outcome);
1396 self.end_update(result.structure_changed);
1397 result
1398 })
1399 }
1400
1401 fn apply_pointer_claim(&mut self) {
1404 let Some(node) = self.app.app_context.take_pointer_claim() else {
1405 return;
1406 };
1407 self.give_press_to(node);
1408 }
1409
1410 #[inline(never)]
1413 fn give_press_to(&mut self, node: NodeId) {
1414 for index in 0..self.surfaces.len() {
1415 SurfaceMut::new(self, index).give_press_to(node);
1416 }
1417 }
1418
1419 pub fn update(&mut self) -> FrameUpdateResult {
1422 let frame_time = self.app.frame_time_nanos_at(Instant::now());
1423 self.update_at_frame_time_nanos(frame_time)
1424 }
1425}
1426
1427impl<R> Drop for AppShell<R>
1428where
1429 R: Renderer,
1430{
1431 fn drop(&mut self) {
1432 self.app.runtime.clear_frame_waker();
1433 }
1434}
1435
1436pub fn default_root_key() -> cranpose_core::Key {
1438 location_key(file!(), line!(), column!())
1439}
1440
1441#[cfg(test)]
1442#[path = "tests/app_shell_frame_pacing_tests.rs"]
1443mod frame_pacing_tests;
1444
1445#[cfg(test)]
1446#[path = "tests/app_shell_tests.rs"]
1447mod tests;
1448
1449#[cfg(test)]
1450#[path = "tests/surface_tests.rs"]
1451mod surface_tests;