1#![deny(unsafe_code)]
2#![allow(clippy::type_complexity)]
3
4mod fps_monitor;
5mod hit_path_tracker;
6mod shell_debug;
7mod shell_frame;
8mod shell_input;
9#[cfg(test)]
10use shell_frame::build_draw_refresh_scope;
11
12pub use fps_monitor::FpsStats;
13
14use std::fmt::{Debug, Write};
15use std::rc::Rc;
16use std::sync::{
17 atomic::{AtomicBool, Ordering},
18 Mutex, MutexGuard,
19};
20use web_time::Instant;
22
23use cranpose_core::{
24 enter_event_handler_scope, location_key, run_in_mutable_snapshot, Applier, Composition, Key,
25 MemoryApplier, NodeError, NodeId,
26};
27use cranpose_foundation::{PointerButton, PointerButtons, PointerEvent, PointerEventKind};
28use cranpose_render_common::{HitTestTarget, RenderScene, Renderer};
29use cranpose_runtime_std::StdRuntime;
30use cranpose_ui::{
31 clear_transient_scroll_motion_contexts, format_layout_tree, format_render_scene,
32 format_screen_summary, has_pending_focus_invalidations, has_pending_pointer_repasses,
33 peek_focus_invalidation, peek_layout_invalidation, peek_pointer_invalidation,
34 peek_render_invalidation, process_focus_invalidations, process_pointer_repasses,
35 request_render_invalidation, take_draw_repass_nodes, take_focus_invalidation,
36 take_layout_invalidation, take_pointer_invalidation, take_render_invalidation,
37 HeadlessRenderer, LayoutBox, LayoutNode, LayoutTree, MeasureLayoutOptions, SemanticsTree,
38 SubcomposeLayoutNode,
39};
40use cranpose_ui_graphics::{Point, Rect, Size};
41use hit_path_tracker::{HitPathTracker, PointerId};
42use std::collections::HashSet;
43
44pub use cranpose_ui::{KeyCode, KeyEvent, KeyEventType, Modifiers};
46pub use cranpose_foundation::PointerSource;
48pub use cranpose_foundation::{
51 rotary_scroll_pixels_from_detents, RotaryScrollEvent, DEFAULT_ROTARY_SCROLL_FACTOR_DP,
52};
53
54#[cfg(all(
59 feature = "clipboard-native",
60 not(target_arch = "wasm32"),
61 not(target_os = "android"),
62 not(target_os = "ios")
63))]
64struct ShellClipboard {
65 inner: std::rc::Rc<std::cell::RefCell<Option<arboard::Clipboard>>>,
66}
67
68#[cfg(all(
69 feature = "clipboard-native",
70 not(target_arch = "wasm32"),
71 not(target_os = "android"),
72 not(target_os = "ios")
73))]
74impl cranpose_ui::clipboard_session::PlatformClipboard for ShellClipboard {
75 fn write_text(&self, text: &str) {
76 if let Some(clipboard) = self.inner.borrow_mut().as_mut() {
77 let _ = clipboard.set_text(text);
78 }
79 }
80
81 fn read_text(&self) -> Option<String> {
82 self.inner
83 .borrow_mut()
84 .as_mut()
85 .and_then(|clipboard| clipboard.get_text().ok())
86 }
87}
88pub use cranpose_ui::PlatformTextInputHandler;
90pub use cranpose_ui::ImeEditorState;
92
93#[cfg(any(test, feature = "test-support"))]
94use cranpose_core::{
95 debug_recompose_scope_registry_stats, MemoryApplierDebugStats,
96 RecomposeScopeRegistryDebugStats, SlotTableDebugStats,
97};
98#[cfg(any(test, feature = "test-support"))]
99use cranpose_core::{
100 runtime::{RuntimeDebugStats, StateArenaDebugStats},
101 snapshot_pinning::{debug_snapshot_pinning_stats, SnapshotPinningDebugStats},
102 snapshot_state_observer::SnapshotStateObserverDebugStats,
103 snapshot_v2::{debug_snapshot_v2_stats, SnapshotV2DebugStats},
104 CompositionPassDebugStats, SlotId,
105};
106
107#[derive(Debug, Clone, Copy, PartialEq, Default)]
117pub enum FrameRatePreference {
118 #[default]
122 Auto,
123 NoPreference,
125 Exact(f32),
128}
129
130impl FrameRatePreference {
131 pub const AUTO_QUIET_RATE_HZ: f32 = 60.0;
138
139 pub fn desired_rate_hz(
153 self,
154 producing_frames: bool,
155 interacting: bool,
156 panel_max_hz: Option<f32>,
157 ) -> f32 {
158 match self {
159 FrameRatePreference::Auto => {
160 if interacting {
161 panel_max_hz
162 .filter(|rate| *rate > 0.0)
163 .unwrap_or(Self::AUTO_QUIET_RATE_HZ)
164 } else if producing_frames {
165 Self::AUTO_QUIET_RATE_HZ
166 } else {
167 0.0
168 }
169 }
170 FrameRatePreference::NoPreference => 0.0,
171 FrameRatePreference::Exact(rate) if rate > 0.0 => rate,
172 FrameRatePreference::Exact(_) => 0.0,
173 }
174 }
175}
176
177pub struct AppShell<R>
178where
179 R: Renderer,
180{
181 app_context: Rc<cranpose_ui::AppContext>,
182 runtime: StdRuntime,
183 composition: Composition<MemoryApplier>,
184 content: Box<dyn FnMut()>,
185 renderer: R,
186 cursor: (f32, f32),
187 viewport: (f32, f32),
188 buffer_size: (u32, u32),
189 start_time: Instant,
190 last_frame_time_nanos: u64,
191 layout_tree: Option<LayoutTree>,
192 semantics_tree: Option<SemanticsTree>,
193 semantics_enabled: bool,
194 semantics_snapshot_revision: u64,
200 frame_rate_preference: FrameRatePreference,
203 layout_requested: bool,
204 force_layout_pass: bool,
205 scene_dirty: bool,
206 scoped_layout_scene_nodes: Vec<NodeId>,
207 is_dirty: bool,
208 buttons_pressed: PointerButtons,
210 pointer_source: PointerSource,
216 hit_path_tracker: HitPathTracker,
223 hovered_nodes: Vec<NodeId>,
226 on_rotary_scroll: Option<Rc<dyn Fn(RotaryScrollEvent) -> bool>>,
233 rotary_scroll_factor: f32,
236 #[cfg(all(feature = "clipboard-native", target_os = "linux"))]
238 clipboard: Option<arboard::Clipboard>,
239 dev_options: DevOptions,
241 dev_overlay_controls: Vec<DevOverlayControl>,
242 dev_overlay_text: String,
243 dev_overlay_last_refresh: Option<Instant>,
244 dev_overlay_viewport: Option<Size>,
245 fps_monitor: fps_monitor::FpsMonitor,
246 frame_scheduler: FrameScheduler,
247}
248
249#[derive(Clone, Copy, Debug, PartialEq, Eq)]
250pub struct PointerEventTime {
252 pub platform_time_ms: Option<i64>,
254 pub animation_time_nanos: u64,
256}
257
258fn update_stage_telemetry_threshold_ms() -> Option<f64> {
259 static THRESHOLD_MS: std::sync::OnceLock<Option<f64>> = std::sync::OnceLock::new();
260 *THRESHOLD_MS.get_or_init(|| {
261 std::env::var("CRANPOSE_UPDATE_STAGE_TELEMETRY_MS")
262 .ok()
263 .and_then(|value| value.parse::<f64>().ok())
264 .filter(|value| value.is_finite() && *value >= 0.0)
265 })
266}
267
268#[derive(Clone, Copy, Debug)]
269struct UpdateStageTelemetry {
270 started_at: Instant,
271 after_frame_callbacks: Instant,
272 after_ui_drain: Instant,
273 after_reconcile: Instant,
274 after_process_frame: Instant,
275 should_render: bool,
276 reconcile_attempted: bool,
277 reconcile_changed: bool,
278}
279
280fn log_update_stage_telemetry(telemetry: UpdateStageTelemetry) {
281 let Some(threshold_ms) = update_stage_telemetry_threshold_ms() else {
282 return;
283 };
284 let total_ms = telemetry
285 .after_process_frame
286 .duration_since(telemetry.started_at)
287 .as_secs_f64()
288 * 1000.0;
289 if total_ms < threshold_ms {
290 return;
291 }
292
293 let frame_callbacks_ms = telemetry
294 .after_frame_callbacks
295 .duration_since(telemetry.started_at)
296 .as_secs_f64()
297 * 1000.0;
298 let ui_drain_ms = telemetry
299 .after_ui_drain
300 .duration_since(telemetry.after_frame_callbacks)
301 .as_secs_f64()
302 * 1000.0;
303 let reconcile_ms = telemetry
304 .after_reconcile
305 .duration_since(telemetry.after_ui_drain)
306 .as_secs_f64()
307 * 1000.0;
308 let process_frame_ms = telemetry
309 .after_process_frame
310 .duration_since(telemetry.after_reconcile)
311 .as_secs_f64()
312 * 1000.0;
313 eprintln!(
314 "[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={}",
315 telemetry.should_render,
316 telemetry.reconcile_attempted,
317 telemetry.reconcile_changed
318 );
319}
320
321#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
322pub enum FramePacingMode {
323 #[default]
326 Vsync,
327 Hard60,
328 Hard120,
329 NoVsync,
332}
333
334impl FramePacingMode {
335 pub const ALL: [Self; 4] = [Self::Vsync, Self::Hard60, Self::Hard120, Self::NoVsync];
336
337 pub fn label(self) -> &'static str {
338 match self {
339 Self::Vsync => "VSync",
340 Self::Hard60 => "60fps",
341 Self::Hard120 => "120fps",
342 Self::NoVsync => "NoVSync",
343 }
344 }
345
346 pub fn target_fps(self) -> Option<u32> {
347 match self {
348 Self::Hard60 => Some(60),
349 Self::Hard120 => Some(120),
350 Self::Vsync | Self::NoVsync => None,
351 }
352 }
353}
354
355#[derive(Clone, Copy, Debug, PartialEq)]
356pub struct FrameSchedule {
357 pub needs_update: bool,
358 pub needs_frame: bool,
359 pub next_deadline: Option<web_time::Instant>,
360}
361
362#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
363pub struct FrameUpdateResult {
364 pub visual_changed: bool,
365 pub structure_changed: bool,
366}
367
368pub trait PlatformFrameDriver {
369 fn request_frame(&self);
370 fn request_wake_at(&self, deadline: web_time::Instant);
371 fn clear_wake(&self);
372}
373
374#[derive(Debug)]
375pub struct FrameScheduler {
376 update_pending: AtomicBool,
377 frame_pending: AtomicBool,
378 next_deadline: Mutex<Option<web_time::Instant>>,
379}
380
381impl Default for FrameScheduler {
382 fn default() -> Self {
383 Self {
384 update_pending: AtomicBool::new(false),
385 frame_pending: AtomicBool::new(false),
386 next_deadline: Mutex::new(None),
387 }
388 }
389}
390
391impl FrameScheduler {
392 fn lock_deadline(&self) -> MutexGuard<'_, Option<web_time::Instant>> {
393 self.next_deadline
394 .lock()
395 .unwrap_or_else(|poisoned| poisoned.into_inner())
396 }
397
398 pub fn record(&self, schedule: FrameSchedule) {
399 self.update_pending
400 .store(schedule.needs_update, Ordering::SeqCst);
401 self.frame_pending
402 .store(schedule.needs_frame, Ordering::SeqCst);
403 let mut next_deadline = self.lock_deadline();
404 *next_deadline = if schedule.needs_update {
405 None
406 } else {
407 schedule.next_deadline
408 };
409 }
410
411 pub fn schedule<D>(&self, schedule: FrameSchedule, driver: &D)
412 where
413 D: PlatformFrameDriver + ?Sized,
414 {
415 self.record(schedule);
416 schedule.apply_to(driver);
417 }
418
419 pub fn snapshot(&self) -> FrameSchedule {
420 FrameSchedule {
421 needs_update: self.update_pending.load(Ordering::SeqCst),
422 needs_frame: self.frame_pending.load(Ordering::SeqCst),
423 next_deadline: *self.lock_deadline(),
424 }
425 }
426}
427
428impl FrameSchedule {
429 pub fn apply_to<D>(self, driver: &D)
430 where
431 D: PlatformFrameDriver + ?Sized,
432 {
433 if self.needs_frame {
434 driver.clear_wake();
435 driver.request_frame();
436 } else if self.needs_update {
437 driver.request_wake_at(web_time::Instant::now());
438 } else if let Some(deadline) = self.next_deadline {
439 driver.request_wake_at(deadline);
440 } else {
441 driver.clear_wake();
442 }
443 }
444}
445
446#[derive(Clone, Copy, Debug)]
447struct DevOverlayControl {
448 bounds: Rect,
449 mode: FramePacingMode,
450}
451
452#[derive(Clone, Debug, Default)]
457pub struct DevOptions {
458 pub fps_counter: bool,
460 pub recomposition_counter: bool,
462 pub layout_timing: bool,
464 pub frame_pacing_controls: bool,
465 pub frame_pacing_mode: FramePacingMode,
466}
467
468#[cfg(any(test, feature = "test-support"))]
469#[doc(hidden)]
470#[derive(Clone, Copy, Debug)]
471pub struct RuntimeLeakDebugStats {
472 pub applier_stats: MemoryApplierDebugStats,
473 pub live_node_heap_bytes: usize,
474 pub recycled_node_heap_bytes: usize,
475 pub slot_table_heap_bytes: usize,
476 pub pass_stats: CompositionPassDebugStats,
477 pub slot_stats: SlotTableDebugStats,
478 pub observer_stats: SnapshotStateObserverDebugStats,
479 pub runtime_stats: RuntimeDebugStats,
480 pub state_arena_stats: StateArenaDebugStats,
481 pub recompose_scope_stats: RecomposeScopeRegistryDebugStats,
482 pub snapshot_v2_stats: SnapshotV2DebugStats,
483 pub snapshot_pinning_stats: SnapshotPinningDebugStats,
484}
485
486impl<R> AppShell<R>
487where
488 R: Renderer,
489 R::Error: Debug,
490{
491 pub fn new(renderer: R, root_key: Key, content: impl FnMut() + 'static) -> Self {
492 Self::new_with_size(renderer, root_key, content, (800, 600), (800.0, 600.0))
493 }
494
495 pub fn new_with_size(
496 renderer: R,
497 root_key: Key,
498 content: impl FnMut() + 'static,
499 buffer_size: (u32, u32),
500 viewport: (f32, f32),
501 ) -> Self {
502 Self::new_with_size_and_density(renderer, root_key, content, buffer_size, viewport, 1.0)
503 }
504
505 pub fn new_with_size_and_density(
506 mut renderer: R,
507 root_key: Key,
508 content: impl FnMut() + 'static,
509 buffer_size: (u32, u32),
510 viewport: (f32, f32),
511 density: f32,
512 ) -> Self {
513 let app_context = cranpose_ui::AppContext::new_with_density(density);
514 let runtime = StdRuntime::new();
515 let mut composition = Composition::with_runtime(MemoryApplier::new(), runtime.runtime());
516 let app_content = Rc::new(std::cell::RefCell::new(content));
522 let mut build: Box<dyn FnMut()> = Box::new(move || {
523 let app_content = Rc::clone(&app_content);
524 cranpose_ui::widgets::PopupHost(move || {
525 (app_content.borrow_mut())();
526 });
527 });
528 renderer.attach_app_context_services(&app_context);
529 app_context.enter(|| {
530 #[cfg(all(
533 feature = "clipboard-native",
534 not(target_arch = "wasm32"),
535 not(target_os = "android"),
536 not(target_os = "ios")
537 ))]
538 {
539 let clipboard =
540 std::rc::Rc::new(std::cell::RefCell::new(arboard::Clipboard::new().ok()));
541 cranpose_ui::clipboard_session::set_platform_clipboard(std::rc::Rc::new(
542 ShellClipboard { inner: clipboard },
543 ));
544 }
545 if let Err(err) = composition.render_stable(root_key, &mut *build) {
546 log::error!("initial render failed: {err}");
547 }
548 });
549 renderer.scene_mut().clear();
550 let mut shell = Self {
551 app_context,
552 runtime,
553 composition,
554 content: build,
555 renderer,
556 cursor: (0.0, 0.0),
557 viewport,
558 buffer_size,
559 start_time: Instant::now(),
560 last_frame_time_nanos: 0,
561 layout_tree: None,
562 semantics_tree: None,
563 semantics_enabled: false,
564 semantics_snapshot_revision: 0,
565 frame_rate_preference: FrameRatePreference::default(),
566 layout_requested: true,
567 force_layout_pass: true,
568 scene_dirty: true,
569 scoped_layout_scene_nodes: Vec::new(),
570 is_dirty: true,
571 buttons_pressed: PointerButtons::NONE,
572 pointer_source: PointerSource::Unknown,
573 hit_path_tracker: HitPathTracker::new(),
574 hovered_nodes: Vec::new(),
575 on_rotary_scroll: None,
576 rotary_scroll_factor: DEFAULT_ROTARY_SCROLL_FACTOR_DP,
577 #[cfg(all(feature = "clipboard-native", target_os = "linux"))]
578 clipboard: arboard::Clipboard::new().ok(),
579 dev_options: DevOptions::default(),
580 dev_overlay_controls: Vec::new(),
581 dev_overlay_text: String::new(),
582 dev_overlay_last_refresh: None,
583 dev_overlay_viewport: None,
584 fps_monitor: fps_monitor::FpsMonitor::new(),
585 frame_scheduler: FrameScheduler::default(),
586 };
587 shell.process_frame();
588 shell
589 }
590
591 pub fn app_context(&self) -> &Rc<cranpose_ui::AppContext> {
596 &self.app_context
597 }
598
599 pub fn set_dev_options(&mut self, options: DevOptions) {
604 self.dev_options = options;
605 self.invalidate_dev_overlay_text();
606 let app_context = Rc::clone(&self.app_context);
607 app_context.enter(request_render_invalidation);
608 self.mark_dirty();
609 }
610
611 pub fn dev_options(&self) -> &DevOptions {
613 &self.dev_options
614 }
615
616 pub fn frame_pacing_mode(&self) -> FramePacingMode {
617 self.dev_options.frame_pacing_mode
618 }
619
620 pub fn current_fps(&self) -> f32 {
621 self.fps_monitor.current_fps()
622 }
623
624 pub fn fps_stats(&self) -> FpsStats {
625 self.fps_monitor.stats()
626 }
627
628 pub fn reset_fps_stats(&mut self) {
629 self.fps_monitor.reset_stats();
630 self.invalidate_dev_overlay_text();
631 }
632
633 pub fn record_presented_frame(
634 &mut self,
635 frame_started_at: Instant,
636 frame_finished_at: Instant,
637 ) {
638 self.fps_monitor
639 .record_frame_work(frame_started_at, frame_finished_at);
640 }
641
642 #[cfg(any(test, feature = "test-support"))]
643 #[doc(hidden)]
644 pub fn record_presented_frame_for_test(
645 &mut self,
646 frame_started_nanos: u64,
647 frame_finished_nanos: u64,
648 ) {
649 let started = self.start_time + std::time::Duration::from_nanos(frame_started_nanos);
650 let finished = self.start_time + std::time::Duration::from_nanos(frame_finished_nanos);
651 self.record_presented_frame(started, finished);
652 }
653
654 pub fn set_frame_pacing_mode(&mut self, mode: FramePacingMode) {
655 if self.dev_options.frame_pacing_mode == mode {
656 return;
657 }
658 self.dev_options.frame_pacing_mode = mode;
659 self.invalidate_dev_overlay_text();
660 let app_context = Rc::clone(&self.app_context);
661 app_context.enter(request_render_invalidation);
662 self.mark_dirty();
663 }
664
665 pub fn handle_dev_overlay_click(&mut self, x: f32, y: f32) -> Option<FramePacingMode> {
666 if !self.dev_options.frame_pacing_controls {
667 return None;
668 }
669 let mode = self
670 .dev_overlay_controls
671 .iter()
672 .find(|control| control.bounds.contains(x, y))
673 .map(|control| control.mode)?;
674 self.set_frame_pacing_mode(mode);
675 Some(mode)
676 }
677
678 fn invalidate_dev_overlay_text(&mut self) {
679 self.dev_overlay_text.clear();
680 self.dev_overlay_last_refresh = None;
681 self.dev_overlay_viewport = None;
682 }
683
684 pub fn set_viewport(&mut self, width: f32, height: f32) {
685 self.viewport = (width, height);
686 self.request_forced_layout_pass();
687 self.mark_dirty();
688 self.process_frame();
689 }
690
691 pub fn viewport_size(&self) -> (f32, f32) {
692 self.viewport
693 }
694
695 pub fn set_buffer_size(&mut self, width: u32, height: u32) {
696 self.buffer_size = (width, height);
697 }
698
699 pub fn buffer_size(&self) -> (u32, u32) {
700 self.buffer_size
701 }
702
703 pub fn scene(&self) -> &R::Scene {
704 self.renderer.scene()
705 }
706
707 pub fn renderer(&mut self) -> &mut R {
708 &mut self.renderer
709 }
710
711 #[cfg(not(target_arch = "wasm32"))]
712 pub fn set_frame_waker(&mut self, waker: impl Fn() + Send + Sync + 'static) {
713 self.runtime.set_frame_waker(waker);
714 }
715
716 #[cfg(target_arch = "wasm32")]
717 pub fn set_frame_waker(&mut self, waker: impl Fn() + 'static) {
718 self.runtime.set_frame_waker(waker);
719 }
720
721 pub fn clear_frame_waker(&mut self) {
722 self.runtime.clear_frame_waker();
723 }
724
725 pub fn should_render(&self) -> bool {
726 let app_context = Rc::clone(&self.app_context);
727 app_context.enter(|| {
728 if self.layout_requested
729 || self.scene_dirty
730 || peek_render_invalidation()
731 || peek_pointer_invalidation()
732 || peek_focus_invalidation()
733 || peek_layout_invalidation()
734 {
735 return true;
736 }
737 self.composition.should_render()
738 })
739 }
740
741 fn has_stale_pixels_in_context(&self) -> bool {
750 self.is_dirty
751 || self.layout_requested
752 || self.scene_dirty
753 || peek_render_invalidation()
754 || peek_pointer_invalidation()
755 || peek_focus_invalidation()
756 || peek_layout_invalidation()
757 || cranpose_ui::has_pending_layout_repasses()
758 || cranpose_ui::has_pending_measure_repasses()
759 || cranpose_ui::has_pending_draw_repasses()
760 || has_pending_pointer_repasses()
761 || has_pending_focus_invalidations()
762 }
763
764 fn needs_ui_update_in_context(&self) -> bool {
765 self.has_stale_pixels_in_context()
769 || self.composition.runtime_handle().has_pending_ui()
770 || self.composition.should_render()
771 }
772
773 pub fn needs_update(&self) -> bool {
774 let app_context = Rc::clone(&self.app_context);
775 app_context.enter(|| self.needs_ui_update_in_context())
776 }
777
778 pub fn needs_redraw(&self) -> bool {
791 let app_context = Rc::clone(&self.app_context);
792 app_context
793 .enter(|| self.has_stale_pixels_in_context() || self.renderer.needs_frame_warmup())
794 }
795
796 pub fn mark_dirty(&mut self) {
798 self.is_dirty = true;
799 }
800
801 pub fn request_root_render(&mut self) {
802 self.composition.request_root_render();
803 self.request_forced_layout_pass();
804 let app_context = Rc::clone(&self.app_context);
805 app_context.enter(request_render_invalidation);
806 self.mark_dirty();
807 }
808
809 pub fn set_density(&mut self, density: f32) {
810 let app_context = Rc::clone(&self.app_context);
811 let changed = app_context.enter(|| {
812 let previous = cranpose_ui::current_density().to_bits();
813 cranpose_ui::set_density(density);
814 previous != cranpose_ui::current_density().to_bits()
815 });
816 if changed {
817 self.request_forced_layout_pass();
818 self.mark_dirty();
819 }
820 }
821
822 #[cfg(any(test, feature = "test-support"))]
823 #[doc(hidden)]
824 pub fn debug_current_density(&self) -> f32 {
825 let app_context = Rc::clone(&self.app_context);
826 app_context.enter(cranpose_ui::current_density)
827 }
828
829 #[cfg(any(test, feature = "test-support"))]
830 #[doc(hidden)]
831 pub fn debug_enter_app_context<T>(&self, block: impl FnOnce() -> T) -> T {
832 let app_context = Rc::clone(&self.app_context);
833 app_context.enter(block)
834 }
835
836 fn request_layout_pass(&mut self) {
837 self.layout_requested = true;
838 }
839
840 fn request_forced_layout_pass(&mut self) {
841 self.layout_requested = true;
842 self.force_layout_pass = true;
843 }
844
845 fn composition_tree_needs_layout(&mut self) -> bool {
846 let Some(root) = self.composition.root() else {
847 return true;
848 };
849 let mut applier = self.composition.applier_mut();
850 cranpose_ui::tree_needs_layout(&mut *applier, root).unwrap_or_else(|err| {
851 log::warn!(
852 "Cannot check layout dirty status for root #{}: {}",
853 root,
854 err
855 );
856 true
857 })
858 }
859
860 pub fn has_active_animations(&self) -> bool {
862 self.composition.should_render()
863 }
864
865 pub fn has_active_pointer_gesture(&self) -> bool {
866 self.buttons_pressed != PointerButtons::NONE
867 && self.hit_path_tracker.has_path(PointerId::PRIMARY)
868 }
869
870 pub fn next_event_time(&self) -> Option<web_time::Instant> {
873 let app_context = Rc::clone(&self.app_context);
874 app_context.enter(cranpose_ui::next_cursor_blink_time)
875 }
876
877 fn compute_frame_schedule(&self) -> FrameSchedule {
878 let needs_update = self.needs_update();
879 let needs_frame = self.is_dirty
880 || self.should_render()
881 || self.has_active_pointer_gesture()
882 || self.renderer.needs_frame_warmup();
883 FrameSchedule {
884 needs_update,
885 needs_frame,
886 next_deadline: self.next_event_time(),
887 }
888 }
889
890 pub fn frame_schedule(&self) -> FrameSchedule {
891 let schedule = self.compute_frame_schedule();
892 self.frame_scheduler.record(schedule);
893 schedule
894 }
895
896 pub fn schedule_platform_frame<D>(&self, driver: &D) -> FrameSchedule
897 where
898 D: PlatformFrameDriver + ?Sized,
899 {
900 let schedule = self.compute_frame_schedule();
901 self.frame_scheduler.schedule(schedule, driver);
902 schedule
903 }
904
905 pub fn frame_scheduler_snapshot(&self) -> FrameSchedule {
906 self.frame_scheduler.snapshot()
907 }
908
909 fn frame_time_nanos_at(&self, now: Instant) -> u64 {
910 now.checked_duration_since(self.start_time)
911 .unwrap_or_default()
912 .as_nanos()
913 .min(u128::from(u64::MAX)) as u64
914 }
915
916 pub fn realtime_pointer_event_time(&self, platform_time_ms: Option<i64>) -> PointerEventTime {
918 PointerEventTime {
919 platform_time_ms,
920 animation_time_nanos: self
921 .frame_time_nanos_at(Instant::now())
922 .max(self.last_frame_time_nanos),
923 }
924 }
925
926 pub fn exact_pointer_event_time(&self, platform_time_ms: Option<i64>) -> PointerEventTime {
928 PointerEventTime {
929 platform_time_ms,
930 animation_time_nanos: self.last_frame_time_nanos,
931 }
932 }
933
934 pub fn update_after_frame_interval(
935 &mut self,
936 frame_interval: std::time::Duration,
937 ) -> FrameUpdateResult {
938 let wall_frame_time = self.frame_time_nanos_at(Instant::now());
939 let base_frame_time = self.last_frame_time_nanos.max(wall_frame_time);
940 let frame_time = base_frame_time
941 .saturating_add(frame_interval.as_nanos().min(u128::from(u64::MAX)) as u64);
942 self.update_at_frame_time_nanos(frame_time)
943 }
944
945 pub fn update_after_exact_interval(
951 &mut self,
952 frame_interval: std::time::Duration,
953 ) -> FrameUpdateResult {
954 let frame_time = self
955 .last_frame_time_nanos
956 .saturating_add(frame_interval.as_nanos().min(u128::from(u64::MAX)) as u64);
957 self.update_at_frame_time_nanos(frame_time)
958 }
959
960 pub fn update_at_frame_time_nanos(&mut self, frame_time: u64) -> FrameUpdateResult {
961 let app_context = Rc::clone(&self.app_context);
962 app_context.enter(|| {
963 let update_started_at = Instant::now();
964 let frame_time = frame_time.max(self.last_frame_time_nanos);
965 self.last_frame_time_nanos = frame_time;
966 let runtime_handle = self.runtime.runtime_handle();
967 runtime_handle.with_deferred_state_releases(|| {
968 self.runtime.drain_frame_callbacks(frame_time);
969 let after_frame_callbacks = Instant::now();
970 runtime_handle.drain_ui();
971 let after_ui_drain = Instant::now();
972 let should_render = self.composition.should_recompose();
973 let mut reconcile_attempted = false;
974 let mut reconcile_changed = false;
975 if should_render {
976 log::trace!(
977 target: "cranpose::input",
978 "update begin: should_render=true layout_requested={} scene_dirty={} is_dirty={}",
979 self.layout_requested,
980 self.scene_dirty,
981 self.is_dirty
982 );
983 }
984 if should_render {
985 let Some(root_key) = self.composition.root_key() else {
986 let result = self.process_frame_in_context(reconcile_changed);
987 let after_process_frame = Instant::now();
988 log_update_stage_telemetry(UpdateStageTelemetry {
989 started_at: update_started_at,
990 after_frame_callbacks,
991 after_ui_drain,
992 after_reconcile: after_ui_drain,
993 after_process_frame,
994 should_render,
995 reconcile_attempted,
996 reconcile_changed,
997 });
998 self.is_dirty = false;
999 return result;
1000 };
1001 reconcile_attempted = true;
1002 match self.composition.reconcile(root_key, &mut *self.content) {
1003 Ok(changed) => {
1004 reconcile_changed = changed;
1005 log::trace!(
1006 target: "cranpose::input",
1007 "reconcile changed={changed}"
1008 );
1009 if changed {
1010 self.fps_monitor.record_recomposition();
1011 if self.composition_tree_needs_layout() {
1012 self.request_layout_pass();
1013 }
1014 request_render_invalidation();
1015 }
1016 }
1017 Err(NodeError::Missing { id }) => {
1018 log::debug!("Recomposition skipped: node {} no longer exists", id);
1019 self.request_layout_pass();
1020 request_render_invalidation();
1021 }
1022 Err(err) => {
1023 log::error!("recomposition failed: {err}");
1024 self.request_layout_pass();
1025 request_render_invalidation();
1026 }
1027 }
1028 }
1029 let after_reconcile = Instant::now();
1030 let result = self.process_frame_in_context(reconcile_changed);
1031 let after_process_frame = Instant::now();
1032 log_update_stage_telemetry(UpdateStageTelemetry {
1033 started_at: update_started_at,
1034 after_frame_callbacks,
1035 after_ui_drain,
1036 after_reconcile,
1037 after_process_frame,
1038 should_render,
1039 reconcile_attempted,
1040 reconcile_changed,
1041 });
1042 self.is_dirty = false;
1043 result
1044 })
1045 })
1046 }
1047
1048 pub fn update(&mut self) -> FrameUpdateResult {
1049 let frame_time = self.frame_time_nanos_at(Instant::now());
1050 self.update_at_frame_time_nanos(frame_time)
1051 }
1052}
1053
1054impl<R> Drop for AppShell<R>
1055where
1056 R: Renderer,
1057{
1058 fn drop(&mut self) {
1059 self.runtime.clear_frame_waker();
1060 }
1061}
1062
1063pub fn default_root_key() -> Key {
1064 location_key(file!(), line!(), column!())
1065}
1066
1067#[cfg(test)]
1068mod frame_pacing_tests {
1069 use super::{FramePacingMode, FrameSchedule, FrameScheduler, PlatformFrameDriver};
1070 use std::cell::RefCell;
1071 use std::panic::{catch_unwind, AssertUnwindSafe};
1072 use std::time::Duration;
1073 use web_time::Instant;
1074
1075 #[derive(Clone, Copy, Debug, PartialEq)]
1076 enum DriverCall {
1077 RequestFrame,
1078 RequestWakeAt(Instant),
1079 ClearWake,
1080 }
1081
1082 #[derive(Default)]
1083 struct RecordingFrameDriver {
1084 calls: RefCell<Vec<DriverCall>>,
1085 }
1086
1087 impl RecordingFrameDriver {
1088 fn calls(&self) -> Vec<DriverCall> {
1089 self.calls.borrow().clone()
1090 }
1091 }
1092
1093 impl PlatformFrameDriver for RecordingFrameDriver {
1094 fn request_frame(&self) {
1095 self.calls.borrow_mut().push(DriverCall::RequestFrame);
1096 }
1097
1098 fn request_wake_at(&self, deadline: Instant) {
1099 self.calls
1100 .borrow_mut()
1101 .push(DriverCall::RequestWakeAt(deadline));
1102 }
1103
1104 fn clear_wake(&self) {
1105 self.calls.borrow_mut().push(DriverCall::ClearWake);
1106 }
1107 }
1108
1109 #[test]
1110 fn frame_pacing_labels_match_overlay_modes() {
1111 assert_eq!(FramePacingMode::Vsync.label(), "VSync");
1112 assert_eq!(FramePacingMode::Hard60.label(), "60fps");
1113 assert_eq!(FramePacingMode::Hard120.label(), "120fps");
1114 assert_eq!(FramePacingMode::NoVsync.label(), "NoVSync");
1115 }
1116
1117 #[test]
1118 fn only_hard_modes_have_fixed_targets() {
1119 assert_eq!(FramePacingMode::Vsync.target_fps(), None);
1120 assert_eq!(FramePacingMode::Hard60.target_fps(), Some(60));
1121 assert_eq!(FramePacingMode::Hard120.target_fps(), Some(120));
1122 assert_eq!(FramePacingMode::NoVsync.target_fps(), None);
1123 }
1124
1125 #[test]
1126 fn frame_schedule_requests_immediate_frame_and_clears_deadline() {
1127 let driver = RecordingFrameDriver::default();
1128 let deadline = Instant::now() + Duration::from_millis(25);
1129
1130 FrameSchedule {
1131 needs_update: true,
1132 needs_frame: true,
1133 next_deadline: Some(deadline),
1134 }
1135 .apply_to(&driver);
1136
1137 assert_eq!(
1138 driver.calls(),
1139 vec![DriverCall::ClearWake, DriverCall::RequestFrame]
1140 );
1141 }
1142
1143 #[test]
1144 fn frame_schedule_requests_deadline_when_idle_until_timer() {
1145 let driver = RecordingFrameDriver::default();
1146 let deadline = Instant::now() + Duration::from_millis(25);
1147
1148 FrameSchedule {
1149 needs_update: false,
1150 needs_frame: false,
1151 next_deadline: Some(deadline),
1152 }
1153 .apply_to(&driver);
1154
1155 assert_eq!(driver.calls(), vec![DriverCall::RequestWakeAt(deadline)]);
1156 }
1157
1158 #[test]
1159 fn frame_schedule_wakes_without_requesting_frame_for_update_only_work() {
1160 let driver = RecordingFrameDriver::default();
1161 let before = Instant::now();
1162
1163 FrameSchedule {
1164 needs_update: true,
1165 needs_frame: false,
1166 next_deadline: None,
1167 }
1168 .apply_to(&driver);
1169
1170 let calls = driver.calls();
1171 assert_eq!(calls.len(), 1);
1172 match calls[0] {
1173 DriverCall::RequestWakeAt(deadline) => {
1174 assert!(deadline >= before);
1175 }
1176 other => panic!("update-only work must wake without requesting a frame: {other:?}"),
1177 }
1178 }
1179
1180 #[test]
1181 fn frame_schedule_clears_wake_when_fully_idle() {
1182 let driver = RecordingFrameDriver::default();
1183
1184 FrameSchedule {
1185 needs_update: false,
1186 needs_frame: false,
1187 next_deadline: None,
1188 }
1189 .apply_to(&driver);
1190
1191 assert_eq!(driver.calls(), vec![DriverCall::ClearWake]);
1192 }
1193
1194 #[test]
1195 fn frame_scheduler_records_latest_schedule_and_applies_driver() {
1196 let scheduler = FrameScheduler::default();
1197 let driver = RecordingFrameDriver::default();
1198 let deadline = Instant::now() + Duration::from_millis(25);
1199
1200 scheduler.schedule(
1201 FrameSchedule {
1202 needs_update: false,
1203 needs_frame: false,
1204 next_deadline: Some(deadline),
1205 },
1206 &driver,
1207 );
1208
1209 assert_eq!(
1210 scheduler.snapshot(),
1211 FrameSchedule {
1212 needs_update: false,
1213 needs_frame: false,
1214 next_deadline: Some(deadline),
1215 }
1216 );
1217 assert_eq!(driver.calls(), vec![DriverCall::RequestWakeAt(deadline)]);
1218 }
1219
1220 #[test]
1221 fn frame_scheduler_clears_deadline_for_immediate_frame() {
1222 let scheduler = FrameScheduler::default();
1223 let driver = RecordingFrameDriver::default();
1224 let deadline = Instant::now() + Duration::from_millis(25);
1225
1226 scheduler.schedule(
1227 FrameSchedule {
1228 needs_update: true,
1229 needs_frame: true,
1230 next_deadline: Some(deadline),
1231 },
1232 &driver,
1233 );
1234
1235 assert_eq!(
1236 scheduler.snapshot(),
1237 FrameSchedule {
1238 needs_update: true,
1239 needs_frame: true,
1240 next_deadline: None,
1241 }
1242 );
1243 assert_eq!(
1244 driver.calls(),
1245 vec![DriverCall::ClearWake, DriverCall::RequestFrame]
1246 );
1247 }
1248
1249 #[test]
1250 fn frame_scheduler_recovers_poisoned_deadline_lock() {
1251 let scheduler = FrameScheduler::default();
1252 let deadline = Instant::now() + Duration::from_millis(25);
1253
1254 let _ = catch_unwind(AssertUnwindSafe(|| {
1255 let _guard = scheduler.lock_deadline();
1256 panic!("poison frame scheduler deadline lock");
1257 }));
1258
1259 scheduler.record(FrameSchedule {
1260 needs_update: false,
1261 needs_frame: false,
1262 next_deadline: Some(deadline),
1263 });
1264
1265 assert_eq!(
1266 scheduler.snapshot(),
1267 FrameSchedule {
1268 needs_update: false,
1269 needs_frame: false,
1270 next_deadline: Some(deadline),
1271 }
1272 );
1273 }
1274}
1275
1276#[cfg(test)]
1277#[path = "tests/app_shell_tests.rs"]
1278mod tests;