1#![deny(missing_docs)]
2#![doc = include_str!("../README.md")]
3
4mod focus_reveal;
5mod fps_monitor;
6mod frame_rate_boost;
7mod hit_path_tracker;
8pub mod inspector;
9mod modal_focus;
10#[cfg(debug_assertions)]
11mod semantics_check;
12mod shell_debug;
13mod shell_frame;
14mod shell_input;
15mod surface;
16mod touch_router;
17mod wheel;
18use std::{
19 cell::{Cell, RefCell},
20 fmt::{Debug, Write},
21 rc::Rc,
22};
23
24use cranpose_core::{
25 Applier, Composition, Key, MemoryApplier, NodeError, NodeId, NodeMarks,
26 SceneNodeAttachmentScratch, collections::map::HashSet, enter_event_handler_scope, location_key,
27 run_in_mutable_snapshot,
28};
29pub use cranpose_foundation::{
30 DEFAULT_ROTARY_SCROLL_FACTOR_DP, Modifiers, PointerSource, RotaryScrollEvent,
31 rotary_scroll_pixels_from_detents,
32};
33use cranpose_foundation::{PointerButton, PointerButtons, PointerEvent, PointerEventKind};
34use cranpose_render_common::{HitTestTarget, RenderScene, Renderer, SceneUpdates};
35use cranpose_runtime_std::StdRuntime;
36use cranpose_ui::{
37 HeadlessRenderer, LayoutBox, LayoutNode, LayoutTree, MeasureLayoutOptions, SemanticsTree,
38 SubcomposeLayoutNode, WindowRootEntry, format_layout_tree, format_render_scene,
39 format_screen_summary, process_focus_invalidations, process_pointer_repasses,
40 process_semantics_invalidations, request_render_invalidation,
41};
42pub use cranpose_ui::{KeyCode, KeyEvent, KeyEventType};
43use cranpose_ui_graphics::{Point, PointerIcon, Rect, Size};
44pub use fps_monitor::FpsStats;
45pub use frame_rate_boost::FrameRateBoost;
46use hit_path_tracker::PointerId;
47#[cfg(test)]
48use shell_frame::build_draw_refresh_scope;
49pub use surface::{RootId, RootSurface, SurfaceMut};
50use surface::{
51 SurfaceDirtyLane, TextInputRouter, TextInputRoutes, route_geometry_scene_nodes,
52 route_nodes_by_surface,
53};
54pub use touch_router::TouchRouter;
55use web_time::Instant;
56pub use wheel::WheelScroll;
57
58#[cfg(all(
59 feature = "clipboard-native",
60 not(target_arch = "wasm32"),
61 not(target_os = "android"),
62 not(target_os = "ios")
63))]
64#[derive(Default)]
65struct ShellClipboard {
66 inner: std::cell::OnceCell<std::cell::RefCell<Option<arboard::Clipboard>>>,
70}
71
72#[cfg(all(
73 feature = "clipboard-native",
74 not(target_arch = "wasm32"),
75 not(target_os = "android"),
76 not(target_os = "ios")
77))]
78impl ShellClipboard {
79 fn with<T>(
82 &self,
83 use_clipboard: impl FnOnce(&mut arboard::Clipboard) -> Option<T>,
84 ) -> Option<T> {
85 self.inner
86 .get_or_init(|| std::cell::RefCell::new(arboard::Clipboard::new().ok()))
87 .borrow_mut()
88 .as_mut()
89 .and_then(use_clipboard)
90 }
91}
92
93#[cfg(all(
94 feature = "clipboard-native",
95 not(target_arch = "wasm32"),
96 not(target_os = "android"),
97 not(target_os = "ios")
98))]
99impl cranpose_ui::clipboard_session::PlatformClipboard for ShellClipboard {
100 fn write_text(&self, text: &str) {
101 self.with(|clipboard| clipboard.set_text(text).ok());
102 }
103
104 fn read_text(&self) -> Option<String> {
105 self.with(|clipboard| clipboard.get_text().ok())
106 }
107}
108#[cfg(any(test, feature = "test-support"))]
109use cranpose_core::{
110 CompositionPassDebugStats, SlotId,
111 runtime::{RuntimeDebugStats, StateArenaDebugStats},
112 snapshot_pinning::{SnapshotPinningDebugStats, debug_snapshot_pinning_stats},
113 snapshot_v2::{SnapshotV2DebugStats, debug_snapshot_v2_stats},
114};
115#[cfg(any(test, feature = "test-support"))]
116use cranpose_core::{
117 MemoryApplierDebugStats, RecomposeScopeRegistryDebugStats, SlotTableDebugStats,
118 debug_recompose_scope_registry_stats,
119};
120pub use cranpose_ui::{ImeEditorState, PlatformTextInputHandler};
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 FrameRatePreference::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 FrameRatePreference::NoPreference => 0.0,
191 FrameRatePreference::Exact(rate) if rate > 0.0 => rate,
192 FrameRatePreference::Exact(_) => 0.0,
193 }
194 }
195}
196
197pub(crate) struct ShellApp {
198 pub(crate) app_context: Rc<cranpose_ui::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 static THRESHOLD_MS: std::sync::OnceLock<Option<f64>> = std::sync::OnceLock::new();
273 *THRESHOLD_MS.get_or_init(|| {
274 std::env::var("CRANPOSE_UPDATE_STAGE_TELEMETRY_MS")
275 .ok()
276 .and_then(|value| value.parse::<f64>().ok())
277 .filter(|value| value.is_finite() && *value >= 0.0)
278 })
279}
280
281type UpdateStages = cranpose_core::StageTimes<5>;
284
285struct UpdateOutcome {
286 should_render: bool,
287 reconcile_attempted: bool,
288 reconcile_changed: bool,
289}
290
291fn log_update_stage_telemetry(stages: &UpdateStages, outcome: UpdateOutcome) {
292 let Some(threshold_ms) = update_stage_telemetry_threshold_ms() else {
293 return;
294 };
295 let Some(
296 [
297 started_at,
298 after_frame_callbacks,
299 after_ui_drain,
300 after_reconcile,
301 after_process_frame,
302 ],
303 ) = stages.times()
304 else {
305 return;
306 };
307 let ms = cranpose_core::stage_ms;
308 let total_ms = ms(started_at, after_process_frame);
309 if total_ms < threshold_ms {
310 return;
311 }
312 eprintln!(
313 "[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={}",
314 ms(started_at, after_frame_callbacks),
315 ms(after_frame_callbacks, after_ui_drain),
316 ms(after_ui_drain, after_reconcile),
317 ms(after_reconcile, after_process_frame),
318 outcome.should_render,
319 outcome.reconcile_attempted,
320 outcome.reconcile_changed
321 );
322}
323
324#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
326pub enum FramePacingMode {
327 #[default]
330 Vsync,
331 Hard60,
333 Hard120,
335 NoVsync,
338}
339
340impl FramePacingMode {
341 pub const ALL: [Self; 4] = [Self::Vsync, Self::Hard60, Self::Hard120, Self::NoVsync];
343
344 pub fn label(self) -> &'static str {
346 match self {
347 Self::Vsync => "VSync",
348 Self::Hard60 => "60fps",
349 Self::Hard120 => "120fps",
350 Self::NoVsync => "NoVSync",
351 }
352 }
353
354 pub fn target_fps(self) -> Option<u32> {
357 match self {
358 Self::Hard60 => Some(60),
359 Self::Hard120 => Some(120),
360 Self::Vsync | Self::NoVsync => None,
361 }
362 }
363}
364
365#[derive(Clone, Copy, Debug, Default, PartialEq)]
368pub struct FrameSchedule {
369 pub needs_update: bool,
372 pub needs_frame: bool,
374 pub next_deadline: Option<web_time::Instant>,
377}
378
379#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
381pub struct FrameUpdateResult {
382 pub visual_changed: bool,
384 pub structure_changed: bool,
387 pub content_moved: bool,
392 pub content_redrawn: bool,
395}
396
397pub trait PlatformFrameDriver {
400 fn request_frame(&self);
402 fn request_wake_at(&self, deadline: web_time::Instant);
405 fn clear_wake(&self);
407}
408
409#[derive(Debug, Default)]
413pub struct FrameScheduler {
414 latest: Cell<FrameSchedule>,
415}
416
417impl FrameScheduler {
418 pub fn record(&self, schedule: FrameSchedule) {
420 self.latest.set(FrameSchedule {
421 next_deadline: if schedule.needs_update {
422 None
423 } else {
424 schedule.next_deadline
425 },
426 ..schedule
427 });
428 }
429
430 pub fn schedule<D>(&self, schedule: FrameSchedule, driver: &D)
432 where
433 D: PlatformFrameDriver + ?Sized,
434 {
435 self.record(schedule);
436 schedule.apply_to(driver);
437 }
438
439 pub fn snapshot(&self) -> FrameSchedule {
441 self.latest.get()
442 }
443}
444
445impl FrameSchedule {
446 pub fn apply_to<D>(self, driver: &D)
449 where
450 D: PlatformFrameDriver + ?Sized,
451 {
452 if self.needs_frame {
453 driver.clear_wake();
454 driver.request_frame();
455 } else if self.needs_update {
456 driver.request_wake_at(web_time::Instant::now());
457 } else if let Some(deadline) = self.next_deadline {
458 driver.request_wake_at(deadline);
459 } else {
460 driver.clear_wake();
461 }
462 }
463}
464
465#[derive(Clone, Copy, Debug)]
466pub(crate) struct DevOverlayControl {
467 bounds: Rect,
468 mode: FramePacingMode,
469}
470
471#[derive(Clone, Debug, Default)]
476pub struct DevOptions {
477 pub fps_counter: bool,
479 pub recomposition_counter: bool,
481 pub layout_timing: bool,
483 pub frame_pacing_controls: bool,
485 pub frame_pacing_mode: FramePacingMode,
487}
488
489#[cfg(any(test, feature = "test-support"))]
490#[doc(hidden)]
491#[derive(Clone, Copy, Debug)]
492pub struct RuntimeLeakDebugStats {
493 pub applier_stats: MemoryApplierDebugStats,
494 pub live_node_heap_bytes: usize,
495 pub recycled_node_heap_bytes: usize,
496 pub slot_table_heap_bytes: usize,
497 pub pass_stats: CompositionPassDebugStats,
498 pub slot_stats: SlotTableDebugStats,
499 pub runtime_stats: RuntimeDebugStats,
500 pub state_arena_stats: StateArenaDebugStats,
501 pub recompose_scope_stats: RecomposeScopeRegistryDebugStats,
502 pub snapshot_v2_stats: SnapshotV2DebugStats,
503 pub snapshot_pinning_stats: SnapshotPinningDebugStats,
504}
505
506impl ShellApp {
507 pub(crate) fn flush_semantics_invalidations(&mut self) {
508 if self.app_context.has_pending_semantics_invalidations() {
509 let mut applier = self.composition.applier_mut();
510 process_semantics_invalidations(|node_id| {
511 cranpose_core::bubble_semantics_dirty(&mut *applier, node_id);
512 });
513 }
514 }
515
516 pub(crate) fn request_layout_pass(&mut self) {
517 self.layout_requested = true;
518 }
519
520 pub(crate) fn request_forced_layout_pass(&mut self) {
521 self.layout_requested = true;
522 self.force_layout_pass = true;
523 }
524
525 pub(crate) fn composition_tree_needs_layout(&mut self) -> bool {
526 let Some(root) = self.composition.root() else {
527 return true;
528 };
529 let mut applier = self.composition.applier_mut();
530 cranpose_ui::tree_needs_layout(&mut *applier, root).unwrap_or_else(|err| {
531 log::warn!("Cannot check layout dirty status for root #{root}: {err}");
532 true
533 })
534 }
535
536 pub(crate) fn has_stale_work_in_context(&self) -> bool {
537 self.layout_requested || self.app_context.has_stale_work()
538 }
539
540 pub(crate) fn wants_frame_in_context(&self) -> bool {
541 self.layout_requested
542 || self.app_context.has_pending_frame_work()
543 || self.composition.should_render()
544 }
545
546 pub(crate) fn needs_ui_update_in_context(&self, surfaces_dirty: bool) -> bool {
547 surfaces_dirty
548 || self.has_stale_work_in_context()
549 || self.composition.runtime().has_pending_ui()
550 || self.app_context.has_pending_semantics_invalidations()
551 || self.composition.should_render()
552 }
553
554 pub(crate) fn next_event_time(&self) -> Option<web_time::Instant> {
555 self.app_context.enter(cranpose_ui::next_cursor_blink_time)
556 }
557
558 pub(crate) fn frame_time_nanos_at(&self, now: Instant) -> u64 {
559 now.checked_duration_since(self.start_time)
560 .unwrap_or_default()
561 .as_nanos()
562 .min(u128::from(u64::MAX)) as u64
563 }
564
565 pub(crate) fn realtime_pointer_event_time(
566 &self,
567 platform_time_ms: Option<i64>,
568 ) -> PointerEventTime {
569 PointerEventTime {
570 platform_time_ms,
571 animation_time_nanos: self
572 .frame_time_nanos_at(Instant::now())
573 .max(self.last_frame_time_nanos),
574 }
575 }
576
577 pub(crate) fn install_text_input_router(&mut self) {
578 if self.text_input_router_installed {
579 return;
580 }
581 let router = Rc::new(TextInputRouter {
582 routes: Rc::clone(&self.text_input_routes),
583 });
584 self.app_context
585 .enter(|| cranpose_ui::text_input_session::set_platform_text_input_handler(router));
586 self.text_input_router_installed = true;
587 }
588}
589
590impl<R> AppShell<R>
591where
592 R: Renderer,
593 R::Error: Debug,
594{
595 pub fn new(renderer: R, root_key: Key, content: impl FnMut() + 'static) -> Self {
598 Self::new_with_size(renderer, root_key, content, (800, 600), (800.0, 600.0))
599 }
600
601 pub fn new_with_size(
604 renderer: R,
605 root_key: Key,
606 content: impl FnMut() + 'static,
607 buffer_size: (u32, u32),
608 viewport: (f32, f32),
609 ) -> Self {
610 Self::new_with_size_and_density(renderer, root_key, content, buffer_size, viewport, 1.0)
611 }
612
613 pub fn new_with_size_and_density(
616 mut renderer: R,
617 root_key: Key,
618 content: impl FnMut() + 'static,
619 buffer_size: (u32, u32),
620 viewport: (f32, f32),
621 density: f32,
622 ) -> Self {
623 renderer.set_root_scale(density);
624 let app_context = cranpose_ui::AppContext::new_with_density(density);
625 let runtime = StdRuntime::new();
626 let mut composition = Composition::with_runtime(MemoryApplier::new(), runtime.runtime());
627 let app_content = Rc::new(std::cell::RefCell::new(content));
628 let mut build: Box<dyn FnMut()> = Box::new(move || {
629 let app_content = Rc::clone(&app_content);
630 cranpose_ui::density::ProvideDensity(cranpose_ui::Density::from_host(), move || {
631 cranpose_ui::widgets::PopupHost(move || {
632 (app_content.borrow_mut())();
633 });
634 });
635 });
636 renderer.attach_app_context_services(&app_context);
637 app_context.enter(|| {
638 #[cfg(all(
639 feature = "clipboard-native",
640 not(target_arch = "wasm32"),
641 not(target_os = "android"),
642 not(target_os = "ios")
643 ))]
644 {
645 cranpose_ui::clipboard_session::set_platform_clipboard(std::rc::Rc::new(
646 ShellClipboard::default(),
647 ));
648 }
649 if let Err(err) = composition.render_stable(root_key, &mut *build) {
650 log::error!("initial render failed: {err}");
651 }
652 });
653 renderer.scene_mut().clear();
654 let app = ShellApp {
655 app_context,
656 runtime,
657 composition,
658 content: build,
659 start_time: Instant::now(),
660 last_frame_time_nanos: 0,
661 semantics_enabled: false,
662 semantics_snapshot_revision: 0,
663 revealed_focus: None,
664 layout_requested: true,
665 content_moved: false,
666 force_layout_pass: true,
667 modifiers: None,
668 rotary_scroll_factor: DEFAULT_ROTARY_SCROLL_FACTOR_DP,
669 #[cfg(all(feature = "clipboard-native", target_os = "linux"))]
670 clipboard: arboard::Clipboard::new().ok(),
671 dev_options: DevOptions::default(),
672 inspector_projector: None,
673 fps_monitor: fps_monitor::FpsMonitor::new(),
674 text_input_routes: Rc::new(RefCell::new(TextInputRoutes::default())),
675 text_input_router_installed: false,
676 window_roots_seen: None,
677 rebuilt_frames_since_observation_prune: 0,
678 #[cfg(feature = "installed-fonts")]
679 installed_fonts: 0,
680 };
681 let mut shell = Self {
682 app,
683 surfaces: vec![RootSurface::new(
684 RootId::Primary,
685 renderer,
686 buffer_size,
687 viewport,
688 )],
689 routing_scratch: SurfaceRoutingScratch::default(),
690 pending_dirty_nodes: Vec::new(),
691 pending_layer_property_nodes: Vec::new(),
692 geometry_scene_nodes: cranpose_ui::GeometrySceneNodes::default(),
693 };
694 shell.process_frame();
695 shell
696 }
697
698 pub fn app_context(&self) -> &Rc<cranpose_ui::AppContext> {
703 &self.app.app_context
704 }
705
706 pub fn surface(&mut self, root: RootId) -> Option<SurfaceMut<'_, R>> {
709 let index = self.surface_index(root)?;
710 Some(SurfaceMut::new(self, index))
711 }
712
713 pub fn primary(&mut self) -> SurfaceMut<'_, R> {
715 SurfaceMut::new(self, 0)
716 }
717
718 pub fn root_holding_the_press(&mut self) -> Option<RootId> {
727 let pressed = self
728 .surfaces
729 .iter()
730 .find_map(|surface| surface.hit_path_tracker.dispatch_order(PointerId::PRIMARY))?;
731 let primary_root = self.app.composition.root()?;
732 let mut applier = self.app.composition.applier_mut();
733 let holder = pressed.into_iter().find_map(|node| {
734 let node = applier.scene_node_attached_to(node, primary_root)?;
735 Some(cranpose_ui::nearest_window_root(&mut applier, node))
736 })?;
737 drop(applier);
738 self.surfaces
739 .iter()
740 .find(|surface| surface.owns_nodes_under(holder))
741 .map(|surface| surface.id)
742 }
743
744 fn surface_index(&self, root: RootId) -> Option<usize> {
745 self.surfaces.iter().position(|surface| surface.id == root)
746 }
747
748 pub fn add_window_surface(
758 &mut self,
759 window: u64,
760 renderer: R,
761 buffer_size: (u32, u32),
762 viewport: (f32, f32),
763 ) -> Option<R> {
764 let previous = self.remove_window_surface(window);
765 self.surfaces.push(RootSurface::new(
766 RootId::Window(window),
767 renderer,
768 buffer_size,
769 viewport,
770 ));
771 self.app.window_roots_seen = None;
772 self.sync_window_roots();
773 previous
774 }
775
776 pub fn remove_window_surface(&mut self, window: u64) -> Option<R> {
778 let root = RootId::Window(window);
779 let index = self.surface_index(root)?;
780 self.app.text_input_routes.borrow_mut().remove(root);
781 Some(self.surfaces.remove(index).renderer)
782 }
783
784 pub fn surface_ids(&self) -> Vec<RootId> {
786 self.surfaces.iter().map(|surface| surface.id).collect()
787 }
788
789 pub fn window_roots(&self) -> Vec<WindowRootEntry> {
793 self.app.app_context.enter(cranpose_ui::window_roots)
794 }
795
796 pub fn window_roots_revision(&self) -> u64 {
800 self.app
801 .app_context
802 .enter(cranpose_ui::window_roots_revision)
803 }
804
805 pub fn primary_has_content(&mut self) -> bool {
810 self.read_primary_boxes(cranpose_ui::has_placed_content)
811 .unwrap_or(false)
812 }
813
814 pub fn primary_content_size(&mut self) -> Option<Size> {
820 self.read_primary_boxes(cranpose_ui::placed_content_extent)
821 .flatten()
822 }
823
824 fn read_primary_boxes<T>(
828 &mut self,
829 read: impl FnOnce(&mut MemoryApplier, NodeId) -> Result<T, NodeError>,
830 ) -> Option<T> {
831 let _app_context = self.app.app_context.enter_scope();
832 let root = self.surfaces[0].root_node(&self.app)?;
833 let mut applier = self.app.composition.applier_mut();
834 read(&mut applier, root)
835 .inspect_err(|err| log::debug!("failed to read the primary root's boxes: {err}"))
836 .ok()
837 }
838
839 pub(crate) fn drag_and_drop_target_at(
845 &self,
846 point: cranpose_ui::DragAndDropPoint,
847 source: usize,
848 ) -> Option<(NodeId, cranpose_ui::Point)> {
849 let drag_and_drop = self.app.app_context.drag_and_drop();
850 let target_in = |index: usize, local: cranpose_ui::Point| {
851 self.surfaces[index]
852 .renderer
853 .scene()
854 .hit_test_nodes(local.x, local.y)
855 .into_iter()
856 .find(|node| drag_and_drop.is_target(*node))
857 .map(|node| (node, local))
858 };
859 match point.screen {
860 Some(screen) => (0..self.surfaces.len()).rev().find_map(|index| {
861 let local = self.surfaces[index].screen_point_inside(screen)?;
862 target_in(index, local)
863 }),
864 None => target_in(source, point.local),
865 }
866 }
867
868 pub fn set_active_root(&mut self, root: RootId) {
872 self.app.text_input_routes.borrow_mut().set_active(root);
873 }
874
875 pub fn active_root(&self) -> RootId {
877 self.app.text_input_routes.borrow().active()
878 }
879
880 fn sync_window_roots(&mut self) {
881 let _app_context = self.app.app_context.enter_scope();
882 self.sync_window_roots_in_context();
883 }
884
885 pub(crate) fn sync_window_roots_in_context(&mut self) {
886 let revision = self.app.app_context.window_roots().revision();
887 if self.app.window_roots_seen == Some(revision) {
888 return;
889 }
890 self.app.window_roots_seen = Some(revision);
891 let entries = cranpose_ui::window_roots();
892 for surface in &mut self.surfaces {
893 let RootId::Window(id) = surface.id else {
894 continue;
895 };
896 let root = entries
897 .iter()
898 .find(|entry| entry.node as u64 == id)
899 .map(|entry| entry.node);
900 surface.set_root(root);
901 }
902 }
903
904 pub(crate) fn any_surface_dirty(&self) -> bool {
905 self.surfaces
906 .iter()
907 .any(|surface| surface.is_dirty || surface.scene_dirty)
908 }
909
910 pub(crate) fn mark_all_dirty(&mut self) {
911 for surface in &mut self.surfaces {
912 surface.is_dirty = true;
913 }
914 }
915
916 fn clear_surface_dirt(&mut self) {
917 for surface in &mut self.surfaces {
918 surface.is_dirty = false;
919 }
920 }
921
922 fn invalidate_dev_overlay_text(&mut self) {
923 for surface in &mut self.surfaces {
924 surface.invalidate_dev_overlay_text();
925 }
926 }
927
928 pub fn set_dev_options(&mut self, options: DevOptions) {
933 self.app.dev_options = options;
934 self.invalidate_dev_overlay_text();
935 self.app.app_context.enter(request_render_invalidation);
936 self.mark_all_dirty();
937 }
938
939 pub fn dev_options(&self) -> &DevOptions {
941 &self.app.dev_options
942 }
943
944 pub fn frame_pacing_mode(&self) -> FramePacingMode {
946 self.app.dev_options.frame_pacing_mode
947 }
948
949 pub fn current_fps(&self) -> f32 {
951 self.app.fps_monitor.current_fps()
952 }
953
954 pub fn fps_stats(&self) -> FpsStats {
956 self.app.fps_monitor.stats()
957 }
958
959 pub fn reset_fps_stats(&mut self) {
961 self.app.fps_monitor.reset_stats();
962 self.invalidate_dev_overlay_text();
963 }
964
965 pub fn record_presented_frame(
968 &mut self,
969 frame_started_at: Instant,
970 frame_finished_at: Instant,
971 ) {
972 self.app
973 .fps_monitor
974 .record_frame_work(frame_started_at, frame_finished_at);
975 }
976
977 #[cfg(any(test, feature = "test-support"))]
978 #[doc(hidden)]
979 pub fn record_presented_frame_for_test(
980 &mut self,
981 frame_started_nanos: u64,
982 frame_finished_nanos: u64,
983 ) {
984 let started = self.app.start_time + std::time::Duration::from_nanos(frame_started_nanos);
985 let finished = self.app.start_time + std::time::Duration::from_nanos(frame_finished_nanos);
986 self.record_presented_frame(started, finished);
987 }
988
989 pub fn set_frame_pacing_mode(&mut self, mode: FramePacingMode) {
992 if self.app.dev_options.frame_pacing_mode == mode {
993 return;
994 }
995 self.app.dev_options.frame_pacing_mode = mode;
996 self.invalidate_dev_overlay_text();
997 self.app.app_context.enter(request_render_invalidation);
998 self.mark_all_dirty();
999 }
1000
1001 pub fn dev_overlay_control_center(&self, mode: FramePacingMode) -> Option<(f32, f32)> {
1008 self.surfaces[0].dev_overlay_control_center(mode)
1009 }
1010
1011 pub fn set_viewport(&mut self, width: f32, height: f32) {
1014 if self.surfaces[0].viewport == (width, height) {
1015 return;
1016 }
1017 self.primary().set_viewport(width, height);
1018 self.process_frame();
1019 }
1020
1021 pub fn viewport_size(&self) -> (f32, f32) {
1023 self.surfaces[0].viewport
1024 }
1025
1026 pub fn set_screen_origin(&mut self, origin: Option<cranpose_ui_graphics::Point>) {
1029 self.surfaces[0].screen_origin = origin;
1030 }
1031
1032 pub fn set_buffer_size(&mut self, width: u32, height: u32) {
1034 self.surfaces[0].buffer_size = (width, height);
1035 }
1036
1037 pub fn buffer_size(&self) -> (u32, u32) {
1039 self.surfaces[0].buffer_size
1040 }
1041
1042 pub fn scene(&self) -> &R::Scene {
1044 self.surfaces[0].renderer.scene()
1045 }
1046
1047 pub fn renderer(&mut self) -> &mut R {
1049 &mut self.surfaces[0].renderer
1050 }
1051
1052 #[cfg(not(target_arch = "wasm32"))]
1055 pub fn set_frame_waker(&mut self, waker: impl Fn() + Send + Sync + 'static) {
1056 self.app.runtime.set_frame_waker(waker);
1057 }
1058
1059 #[cfg(target_arch = "wasm32")]
1062 pub fn set_frame_waker(&mut self, waker: impl Fn() + 'static) {
1063 self.app.runtime.set_frame_waker(waker);
1064 }
1065
1066 pub fn clear_frame_waker(&mut self) {
1068 self.app.runtime.clear_frame_waker();
1069 }
1070
1071 pub fn should_render(&self) -> bool {
1074 self.app.app_context.enter(|| {
1075 self.app.wants_frame_in_context()
1076 || self.surfaces.iter().any(|surface| surface.scene_dirty)
1077 })
1078 }
1079
1080 pub fn needs_update(&self) -> bool {
1083 self.app.app_context.enter(|| {
1084 self.app
1085 .needs_ui_update_in_context(self.any_surface_dirty())
1086 })
1087 }
1088
1089 pub fn needs_update_without_frame(&self) -> bool {
1092 self.app.app_context.enter(|| {
1093 self.any_surface_dirty()
1094 || self.app.has_stale_work_in_context()
1095 || self.app.composition.should_recompose()
1096 || self.app.composition.runtime().has_pending_ui()
1097 || self.app.app_context.has_pending_semantics_invalidations()
1098 || cranpose_ui::next_cursor_blink_time().is_some_and(|at| at <= Instant::now())
1099 || self
1100 .surfaces
1101 .iter()
1102 .any(|surface| surface.renderer_warmup_due(&self.app))
1103 })
1104 }
1105
1106 pub fn has_pending_ui(&self) -> bool {
1114 self.app.composition.runtime().has_pending_ui()
1115 }
1116
1117 pub fn run_pending_tasks(&mut self) {
1124 if !self.app.composition.runtime().has_pending_ui() {
1127 return;
1128 }
1129 let runtime_handle = self.app.composition.runtime_handle();
1130 self.app.app_context.enter(|| {
1131 runtime_handle.with_deferred_state_releases(|| runtime_handle.drain_ui());
1132 });
1133 }
1134
1135 pub fn needs_redraw(&self) -> bool {
1148 self.app
1149 .app_context
1150 .enter(|| self.surfaces[0].needs_redraw_in_context(&self.app))
1151 }
1152
1153 pub fn mark_dirty(&mut self) {
1155 self.surfaces[0].is_dirty = true;
1156 }
1157
1158 pub fn request_root_render(&mut self) {
1161 self.app.composition.request_root_render();
1162 self.app.request_forced_layout_pass();
1163 self.app.app_context.enter(request_render_invalidation);
1164 self.mark_all_dirty();
1165 }
1166
1167 pub fn set_density(&mut self, density: f32) {
1170 self.surfaces[0].renderer.set_root_scale(density);
1171 let changed = self.app.app_context.enter(|| {
1172 let previous = cranpose_ui::current_density().to_bits();
1173 cranpose_ui::set_density(density);
1174 previous != cranpose_ui::current_density().to_bits()
1175 });
1176 if changed {
1177 self.request_root_render();
1178 }
1179 }
1180
1181 pub fn set_font_scale(&mut self, font_scale: f32) {
1192 self.set_font_scale_curve(cranpose_ui::FontScaleCurve::linear(font_scale));
1193 }
1194
1195 pub fn set_font_scale_curve(&mut self, curve: cranpose_ui::FontScaleCurve) {
1202 let changed = self.app.app_context.enter(|| {
1203 let previous = cranpose_ui::current_font_scale_curve();
1204 cranpose_ui::set_font_scale_curve(curve);
1205 previous != cranpose_ui::current_font_scale_curve()
1206 });
1207 if changed {
1208 self.request_root_render();
1209 }
1210 }
1211
1212 #[cfg(any(test, feature = "test-support"))]
1213 #[doc(hidden)]
1214 pub fn debug_current_density(&self) -> f32 {
1215 self.app.app_context.enter(cranpose_ui::current_density)
1216 }
1217
1218 #[cfg(any(test, feature = "test-support"))]
1219 #[doc(hidden)]
1220 pub fn debug_current_font_scale(&self) -> f32 {
1221 self.app.app_context.enter(cranpose_ui::current_font_scale)
1222 }
1223
1224 #[cfg(any(test, feature = "test-support"))]
1225 #[doc(hidden)]
1226 pub fn debug_current_font_scale_curve(&self) -> cranpose_ui::FontScaleCurve {
1227 self.app
1228 .app_context
1229 .enter(cranpose_ui::current_font_scale_curve)
1230 }
1231
1232 #[cfg(any(test, feature = "test-support"))]
1233 #[doc(hidden)]
1234 pub fn debug_enter_app_context<T>(&self, block: impl FnOnce() -> T) -> T {
1235 self.app.app_context.enter(block)
1236 }
1237
1238 pub fn has_active_animations(&self) -> bool {
1240 self.app.composition.should_render()
1241 }
1242
1243 pub fn has_transient_frame_callbacks(&self) -> bool {
1246 self.app
1247 .composition
1248 .runtime()
1249 .has_transient_frame_callbacks()
1250 }
1251
1252 pub fn has_active_pointer_gesture(&self) -> bool {
1254 self.surfaces[0].has_active_pointer_gesture()
1255 }
1256
1257 pub fn has_active_primary_gesture(&self) -> bool {
1259 self.surfaces[0].has_active_primary_gesture()
1260 }
1261
1262 pub fn frame_owed(&self) -> bool {
1264 self.surfaces[0].frame_owed
1265 }
1266
1267 pub fn take_frame_owed(&mut self) -> bool {
1269 std::mem::take(&mut self.surfaces[0].frame_owed)
1270 }
1271
1272 pub fn next_event_time(&self) -> Option<web_time::Instant> {
1275 self.app.next_event_time()
1276 }
1277
1278 fn compute_frame_schedule(&self) -> FrameSchedule {
1279 self.surfaces[0].compute_frame_schedule(&self.app, self.any_surface_dirty())
1280 }
1281
1282 pub fn frame_schedule(&self) -> FrameSchedule {
1285 let schedule = self.compute_frame_schedule();
1286 self.surfaces[0].frame_scheduler.record(schedule);
1287 schedule
1288 }
1289
1290 pub fn schedule_platform_frame<D>(&self, driver: &D) -> FrameSchedule
1293 where
1294 D: PlatformFrameDriver + ?Sized,
1295 {
1296 let schedule = self.compute_frame_schedule();
1297 self.surfaces[0].frame_scheduler.schedule(schedule, driver);
1298 schedule
1299 }
1300
1301 pub fn frame_scheduler_snapshot(&self) -> FrameSchedule {
1304 self.surfaces[0].frame_scheduler.snapshot()
1305 }
1306
1307 pub fn realtime_pointer_event_time(&self, platform_time_ms: Option<i64>) -> PointerEventTime {
1309 self.app.realtime_pointer_event_time(platform_time_ms)
1310 }
1311
1312 pub fn exact_pointer_event_time(&self, platform_time_ms: Option<i64>) -> PointerEventTime {
1314 PointerEventTime {
1315 platform_time_ms,
1316 animation_time_nanos: self.app.last_frame_time_nanos,
1317 }
1318 }
1319
1320 pub fn update_after_frame_interval(
1323 &mut self,
1324 frame_interval: std::time::Duration,
1325 ) -> FrameUpdateResult {
1326 let wall_frame_time = self.app.frame_time_nanos_at(Instant::now());
1327 let base_frame_time = self.app.last_frame_time_nanos.max(wall_frame_time);
1328 let frame_time = base_frame_time
1329 .saturating_add(frame_interval.as_nanos().min(u128::from(u64::MAX)) as u64);
1330 self.update_at_frame_time_nanos(frame_time)
1331 }
1332
1333 pub fn update_after_exact_interval(
1339 &mut self,
1340 frame_interval: std::time::Duration,
1341 ) -> FrameUpdateResult {
1342 let frame_time = self
1343 .app
1344 .last_frame_time_nanos
1345 .saturating_add(frame_interval.as_nanos().min(u128::from(u64::MAX)) as u64);
1346 self.update_at_frame_time_nanos(frame_time)
1347 }
1348
1349 pub fn dispatch_frame_at(&mut self, frame_time: Instant) {
1355 let frame_time = self.app.frame_time_nanos_at(frame_time);
1356 let _app_context = self.app.app_context.enter_scope();
1357 let runtime_handle = self.app.runtime.runtime_handle();
1358 runtime_handle.with_deferred_state_releases(|| {
1359 self.app.last_frame_time_nanos = frame_time.max(self.app.last_frame_time_nanos);
1360 self.app
1361 .runtime
1362 .drain_frame_callbacks(self.app.last_frame_time_nanos);
1363 self.apply_pointer_claim();
1364 runtime_handle.drain_ui();
1365 self.dispatch_requested_mouse_moves(self.app.last_frame_time_nanos);
1366 });
1367 }
1368
1369 pub fn update_without_frame(&mut self) -> FrameUpdateResult {
1372 self.update_with_frame_time(None)
1373 }
1374
1375 pub fn update_at_frame_time_nanos(&mut self, frame_time: u64) -> FrameUpdateResult {
1379 self.update_with_frame_time(Some(frame_time))
1380 }
1381
1382 fn update_with_frame_time(&mut self, frame_time: Option<u64>) -> FrameUpdateResult {
1383 let _app_context = self.app.app_context.enter_scope();
1384 let mut stages = UpdateStages::start(update_stage_telemetry_threshold_ms().is_some());
1385 let runtime_handle = self.app.runtime.runtime_handle();
1386 runtime_handle.with_deferred_state_releases(|| {
1387 if let Some(frame_time) = frame_time {
1388 self.app.last_frame_time_nanos = frame_time.max(self.app.last_frame_time_nanos);
1389 self.app.runtime.drain_frame_callbacks(self.app.last_frame_time_nanos);
1390 self.apply_pointer_claim();
1391 }
1392 stages.reached();
1393 runtime_handle.drain_ui();
1394 self.dispatch_requested_mouse_moves(self.app.last_frame_time_nanos);
1395 stages.reached();
1396 let should_render = self.app.composition.should_recompose();
1397 let mut reconcile_attempted = false;
1398 let mut reconcile_changed = false;
1399 if should_render {
1400 log::trace!(
1401 target: "cranpose::input",
1402 "update begin: should_render=true layout_requested={} scene_dirty={} is_dirty={}",
1403 self.app.layout_requested,
1404 self.surfaces[0].scene_dirty,
1405 self.surfaces[0].is_dirty
1406 );
1407 (reconcile_attempted, reconcile_changed) = self.reconcile_in_context();
1408 }
1409 stages.reached();
1410 let result = self.process_frame_in_context(reconcile_changed);
1411 stages.reached();
1412 log_update_stage_telemetry(
1413 &stages,
1414 UpdateOutcome {
1415 should_render,
1416 reconcile_attempted,
1417 reconcile_changed,
1418 },
1419 );
1420 self.clear_surface_dirt();
1421 result
1422 })
1423 }
1424
1425 fn apply_pointer_claim(&mut self) {
1428 let Some(node) = self.app.app_context.take_pointer_claim() else {
1429 return;
1430 };
1431 for index in 0..self.surfaces.len() {
1432 SurfaceMut::new(self, index).give_press_to(node);
1433 }
1434 }
1435
1436 fn dispatch_requested_mouse_moves(&mut self, frame_time: u64) {
1437 use cranpose_ui::mouse_input::MouseInputTarget;
1438 let pending = self.app.app_context.pending_mouse_moves();
1439 for _ in 0..pending {
1440 let Some(request) = self.app.app_context.take_mouse_move() else {
1441 break;
1442 };
1443 let root = match request.target {
1444 MouseInputTarget::Primary => RootId::Primary,
1445 MouseInputTarget::Window(id) => RootId::Window(id),
1446 };
1447 if let Some(mut surface) = self.surface(root) {
1448 surface.set_pointer_source(PointerSource::Mouse);
1449 surface.set_cursor_at_event_time(request.position.x, request.position.y, PointerEventTime {
1450 platform_time_ms: Some((frame_time / 1_000_000).min(i64::MAX as u64) as i64),
1451 animation_time_nanos: frame_time,
1452 });
1453 }
1454 }
1455 }
1456
1457 fn reconcile_in_context(&mut self) -> (bool, bool) {
1458 let Some(root_key) = self.app.composition.root_key() else {
1459 return (false, false);
1460 };
1461 match self
1462 .app
1463 .composition
1464 .reconcile(root_key, &mut *self.app.content)
1465 {
1466 Ok(changed) => {
1467 log::trace!(
1468 target: "cranpose::input",
1469 "reconcile changed={changed}"
1470 );
1471 if changed {
1472 self.app.fps_monitor.record_recomposition();
1473 if self.app.composition_tree_needs_layout() {
1474 self.app.request_layout_pass();
1475 }
1476 request_render_invalidation();
1477 }
1478 (true, changed)
1479 }
1480 Err(NodeError::Missing { id }) => {
1481 log::debug!("Recomposition skipped: node {id} no longer exists");
1482 self.app.request_layout_pass();
1483 request_render_invalidation();
1484 (true, false)
1485 }
1486 Err(err) => {
1487 log::error!("recomposition failed: {err}");
1488 self.app.request_layout_pass();
1489 request_render_invalidation();
1490 (true, false)
1491 }
1492 }
1493 }
1494
1495 pub fn update(&mut self) -> FrameUpdateResult {
1498 let frame_time = self.app.frame_time_nanos_at(Instant::now());
1499 self.update_at_frame_time_nanos(frame_time)
1500 }
1501}
1502
1503impl<R> Drop for AppShell<R>
1504where
1505 R: Renderer,
1506{
1507 fn drop(&mut self) {
1508 self.app.runtime.clear_frame_waker();
1509 }
1510}
1511
1512pub fn default_root_key() -> Key {
1514 location_key(file!(), line!(), column!())
1515}
1516
1517#[cfg(test)]
1518#[path = "tests/app_shell_frame_pacing_tests.rs"]
1519mod frame_pacing_tests;
1520
1521#[cfg(test)]
1522#[path = "tests/app_shell_tests.rs"]
1523mod tests;
1524
1525#[cfg(test)]
1526#[path = "tests/surface_tests.rs"]
1527mod surface_tests;