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