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