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