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 dev_overlay_control_center(&self, mode: FramePacingMode) -> Option<(f32, f32)> {
672 self.dev_overlay_controls
673 .iter()
674 .find(|control| control.mode == mode)
675 .map(|control| {
676 (
677 control.bounds.x + control.bounds.width * 0.5,
678 control.bounds.y + control.bounds.height * 0.5,
679 )
680 })
681 }
682
683 pub(crate) fn dev_overlay_press(&mut self, x: f32, y: f32) -> bool {
691 if !self.dev_options.frame_pacing_controls {
692 return false;
693 }
694 let Some(mode) = self
695 .dev_overlay_controls
696 .iter()
697 .find(|control| control.bounds.contains(x, y))
698 .map(|control| control.mode)
699 else {
700 return false;
701 };
702 self.set_frame_pacing_mode(mode);
703 true
704 }
705
706 fn invalidate_dev_overlay_text(&mut self) {
707 self.dev_overlay_text.clear();
708 self.dev_overlay_last_refresh = None;
709 self.dev_overlay_viewport = None;
710 }
711
712 pub fn set_viewport(&mut self, width: f32, height: f32) {
713 self.viewport = (width, height);
714 self.request_forced_layout_pass();
715 self.mark_dirty();
716 self.process_frame();
717 }
718
719 pub fn viewport_size(&self) -> (f32, f32) {
720 self.viewport
721 }
722
723 pub fn set_buffer_size(&mut self, width: u32, height: u32) {
724 self.buffer_size = (width, height);
725 }
726
727 pub fn buffer_size(&self) -> (u32, u32) {
728 self.buffer_size
729 }
730
731 pub fn scene(&self) -> &R::Scene {
732 self.renderer.scene()
733 }
734
735 pub fn renderer(&mut self) -> &mut R {
736 &mut self.renderer
737 }
738
739 #[cfg(not(target_arch = "wasm32"))]
740 pub fn set_frame_waker(&mut self, waker: impl Fn() + Send + Sync + 'static) {
741 self.runtime.set_frame_waker(waker);
742 }
743
744 #[cfg(target_arch = "wasm32")]
745 pub fn set_frame_waker(&mut self, waker: impl Fn() + 'static) {
746 self.runtime.set_frame_waker(waker);
747 }
748
749 pub fn clear_frame_waker(&mut self) {
750 self.runtime.clear_frame_waker();
751 }
752
753 pub fn should_render(&self) -> bool {
754 let app_context = Rc::clone(&self.app_context);
755 app_context.enter(|| {
756 if self.layout_requested
757 || self.scene_dirty
758 || peek_render_invalidation()
759 || peek_pointer_invalidation()
760 || peek_focus_invalidation()
761 || peek_layout_invalidation()
762 {
763 return true;
764 }
765 self.composition.should_render()
766 })
767 }
768
769 fn has_stale_pixels_in_context(&self) -> bool {
778 self.is_dirty
779 || self.layout_requested
780 || self.scene_dirty
781 || peek_render_invalidation()
782 || peek_pointer_invalidation()
783 || peek_focus_invalidation()
784 || peek_layout_invalidation()
785 || cranpose_ui::has_pending_layout_repasses()
786 || cranpose_ui::has_pending_measure_repasses()
787 || cranpose_ui::has_pending_draw_repasses()
788 || has_pending_pointer_repasses()
789 || has_pending_focus_invalidations()
790 }
791
792 fn needs_ui_update_in_context(&self) -> bool {
793 self.has_stale_pixels_in_context()
797 || self.composition.runtime_handle().has_pending_ui()
798 || self.composition.should_render()
799 }
800
801 pub fn needs_update(&self) -> bool {
802 let app_context = Rc::clone(&self.app_context);
803 app_context.enter(|| self.needs_ui_update_in_context())
804 }
805
806 pub fn has_pending_ui(&self) -> bool {
814 let app_context = Rc::clone(&self.app_context);
815 app_context.enter(|| self.composition.runtime_handle().has_pending_ui())
816 }
817
818 pub fn needs_redraw(&self) -> bool {
831 let app_context = Rc::clone(&self.app_context);
832 app_context
833 .enter(|| self.has_stale_pixels_in_context() || self.renderer.needs_frame_warmup())
834 }
835
836 pub fn mark_dirty(&mut self) {
838 self.is_dirty = true;
839 }
840
841 pub fn request_root_render(&mut self) {
842 self.composition.request_root_render();
843 self.request_forced_layout_pass();
844 let app_context = Rc::clone(&self.app_context);
845 app_context.enter(request_render_invalidation);
846 self.mark_dirty();
847 }
848
849 pub fn set_density(&mut self, density: f32) {
850 let app_context = Rc::clone(&self.app_context);
851 let changed = app_context.enter(|| {
852 let previous = cranpose_ui::current_density().to_bits();
853 cranpose_ui::set_density(density);
854 previous != cranpose_ui::current_density().to_bits()
855 });
856 if changed {
857 self.request_forced_layout_pass();
858 self.mark_dirty();
859 }
860 }
861
862 pub fn set_font_scale(&mut self, font_scale: f32) {
868 let app_context = Rc::clone(&self.app_context);
869 let changed = app_context.enter(|| {
870 let previous = cranpose_ui::current_font_scale().to_bits();
871 cranpose_ui::set_font_scale(font_scale);
872 previous != cranpose_ui::current_font_scale().to_bits()
873 });
874 if changed {
875 self.request_forced_layout_pass();
876 self.mark_dirty();
877 }
878 }
879
880 #[cfg(any(test, feature = "test-support"))]
881 #[doc(hidden)]
882 pub fn debug_current_density(&self) -> f32 {
883 let app_context = Rc::clone(&self.app_context);
884 app_context.enter(cranpose_ui::current_density)
885 }
886
887 #[cfg(any(test, feature = "test-support"))]
888 #[doc(hidden)]
889 pub fn debug_current_font_scale(&self) -> f32 {
890 let app_context = Rc::clone(&self.app_context);
891 app_context.enter(cranpose_ui::current_font_scale)
892 }
893
894 #[cfg(any(test, feature = "test-support"))]
895 #[doc(hidden)]
896 pub fn debug_enter_app_context<T>(&self, block: impl FnOnce() -> T) -> T {
897 let app_context = Rc::clone(&self.app_context);
898 app_context.enter(block)
899 }
900
901 fn request_layout_pass(&mut self) {
902 self.layout_requested = true;
903 }
904
905 fn request_forced_layout_pass(&mut self) {
906 self.layout_requested = true;
907 self.force_layout_pass = true;
908 }
909
910 fn composition_tree_needs_layout(&mut self) -> bool {
911 let Some(root) = self.composition.root() else {
912 return true;
913 };
914 let mut applier = self.composition.applier_mut();
915 cranpose_ui::tree_needs_layout(&mut *applier, root).unwrap_or_else(|err| {
916 log::warn!(
917 "Cannot check layout dirty status for root #{}: {}",
918 root,
919 err
920 );
921 true
922 })
923 }
924
925 pub fn has_active_animations(&self) -> bool {
927 self.composition.should_render()
928 }
929
930 pub fn has_active_pointer_gesture(&self) -> bool {
931 self.buttons_pressed != PointerButtons::NONE
932 && self.hit_path_tracker.has_path(PointerId::PRIMARY)
933 }
934
935 pub fn next_event_time(&self) -> Option<web_time::Instant> {
938 let app_context = Rc::clone(&self.app_context);
939 app_context.enter(cranpose_ui::next_cursor_blink_time)
940 }
941
942 fn compute_frame_schedule(&self) -> FrameSchedule {
943 let needs_update = self.needs_update();
944 let needs_frame = self.is_dirty
945 || self.should_render()
946 || self.has_active_pointer_gesture()
947 || self.renderer.needs_frame_warmup();
948 FrameSchedule {
949 needs_update,
950 needs_frame,
951 next_deadline: self.next_event_time(),
952 }
953 }
954
955 pub fn frame_schedule(&self) -> FrameSchedule {
956 let schedule = self.compute_frame_schedule();
957 self.frame_scheduler.record(schedule);
958 schedule
959 }
960
961 pub fn schedule_platform_frame<D>(&self, driver: &D) -> FrameSchedule
962 where
963 D: PlatformFrameDriver + ?Sized,
964 {
965 let schedule = self.compute_frame_schedule();
966 self.frame_scheduler.schedule(schedule, driver);
967 schedule
968 }
969
970 pub fn frame_scheduler_snapshot(&self) -> FrameSchedule {
971 self.frame_scheduler.snapshot()
972 }
973
974 fn frame_time_nanos_at(&self, now: Instant) -> u64 {
975 now.checked_duration_since(self.start_time)
976 .unwrap_or_default()
977 .as_nanos()
978 .min(u128::from(u64::MAX)) as u64
979 }
980
981 pub fn realtime_pointer_event_time(&self, platform_time_ms: Option<i64>) -> PointerEventTime {
983 PointerEventTime {
984 platform_time_ms,
985 animation_time_nanos: self
986 .frame_time_nanos_at(Instant::now())
987 .max(self.last_frame_time_nanos),
988 }
989 }
990
991 pub fn exact_pointer_event_time(&self, platform_time_ms: Option<i64>) -> PointerEventTime {
993 PointerEventTime {
994 platform_time_ms,
995 animation_time_nanos: self.last_frame_time_nanos,
996 }
997 }
998
999 pub fn update_after_frame_interval(
1000 &mut self,
1001 frame_interval: std::time::Duration,
1002 ) -> FrameUpdateResult {
1003 let wall_frame_time = self.frame_time_nanos_at(Instant::now());
1004 let base_frame_time = self.last_frame_time_nanos.max(wall_frame_time);
1005 let frame_time = base_frame_time
1006 .saturating_add(frame_interval.as_nanos().min(u128::from(u64::MAX)) as u64);
1007 self.update_at_frame_time_nanos(frame_time)
1008 }
1009
1010 pub fn update_after_exact_interval(
1016 &mut self,
1017 frame_interval: std::time::Duration,
1018 ) -> FrameUpdateResult {
1019 let frame_time = self
1020 .last_frame_time_nanos
1021 .saturating_add(frame_interval.as_nanos().min(u128::from(u64::MAX)) as u64);
1022 self.update_at_frame_time_nanos(frame_time)
1023 }
1024
1025 pub fn update_at_frame_time_nanos(&mut self, frame_time: u64) -> FrameUpdateResult {
1026 let app_context = Rc::clone(&self.app_context);
1027 app_context.enter(|| {
1028 let update_started_at = Instant::now();
1029 let frame_time = frame_time.max(self.last_frame_time_nanos);
1030 self.last_frame_time_nanos = frame_time;
1031 let runtime_handle = self.runtime.runtime_handle();
1032 runtime_handle.with_deferred_state_releases(|| {
1033 self.runtime.drain_frame_callbacks(frame_time);
1034 let after_frame_callbacks = Instant::now();
1035 runtime_handle.drain_ui();
1036 let after_ui_drain = Instant::now();
1037 let should_render = self.composition.should_recompose();
1038 let mut reconcile_attempted = false;
1039 let mut reconcile_changed = false;
1040 if should_render {
1041 log::trace!(
1042 target: "cranpose::input",
1043 "update begin: should_render=true layout_requested={} scene_dirty={} is_dirty={}",
1044 self.layout_requested,
1045 self.scene_dirty,
1046 self.is_dirty
1047 );
1048 }
1049 if should_render {
1050 let Some(root_key) = self.composition.root_key() else {
1051 let result = self.process_frame_in_context(reconcile_changed);
1052 let after_process_frame = Instant::now();
1053 log_update_stage_telemetry(UpdateStageTelemetry {
1054 started_at: update_started_at,
1055 after_frame_callbacks,
1056 after_ui_drain,
1057 after_reconcile: after_ui_drain,
1058 after_process_frame,
1059 should_render,
1060 reconcile_attempted,
1061 reconcile_changed,
1062 });
1063 self.is_dirty = false;
1064 return result;
1065 };
1066 reconcile_attempted = true;
1067 match self.composition.reconcile(root_key, &mut *self.content) {
1068 Ok(changed) => {
1069 reconcile_changed = changed;
1070 log::trace!(
1071 target: "cranpose::input",
1072 "reconcile changed={changed}"
1073 );
1074 if changed {
1075 self.fps_monitor.record_recomposition();
1076 if self.composition_tree_needs_layout() {
1077 self.request_layout_pass();
1078 }
1079 request_render_invalidation();
1080 }
1081 }
1082 Err(NodeError::Missing { id }) => {
1083 log::debug!("Recomposition skipped: node {} no longer exists", id);
1084 self.request_layout_pass();
1085 request_render_invalidation();
1086 }
1087 Err(err) => {
1088 log::error!("recomposition failed: {err}");
1089 self.request_layout_pass();
1090 request_render_invalidation();
1091 }
1092 }
1093 }
1094 let after_reconcile = Instant::now();
1095 let result = self.process_frame_in_context(reconcile_changed);
1096 let after_process_frame = Instant::now();
1097 log_update_stage_telemetry(UpdateStageTelemetry {
1098 started_at: update_started_at,
1099 after_frame_callbacks,
1100 after_ui_drain,
1101 after_reconcile,
1102 after_process_frame,
1103 should_render,
1104 reconcile_attempted,
1105 reconcile_changed,
1106 });
1107 self.is_dirty = false;
1108 result
1109 })
1110 })
1111 }
1112
1113 pub fn update(&mut self) -> FrameUpdateResult {
1114 let frame_time = self.frame_time_nanos_at(Instant::now());
1115 self.update_at_frame_time_nanos(frame_time)
1116 }
1117}
1118
1119impl<R> Drop for AppShell<R>
1120where
1121 R: Renderer,
1122{
1123 fn drop(&mut self) {
1124 self.runtime.clear_frame_waker();
1125 }
1126}
1127
1128pub fn default_root_key() -> Key {
1129 location_key(file!(), line!(), column!())
1130}
1131
1132#[cfg(test)]
1133mod frame_pacing_tests {
1134 use super::{FramePacingMode, FrameSchedule, FrameScheduler, PlatformFrameDriver};
1135 use std::cell::RefCell;
1136 use std::panic::{catch_unwind, AssertUnwindSafe};
1137 use std::time::Duration;
1138 use web_time::Instant;
1139
1140 #[derive(Clone, Copy, Debug, PartialEq)]
1141 enum DriverCall {
1142 RequestFrame,
1143 RequestWakeAt(Instant),
1144 ClearWake,
1145 }
1146
1147 #[derive(Default)]
1148 struct RecordingFrameDriver {
1149 calls: RefCell<Vec<DriverCall>>,
1150 }
1151
1152 impl RecordingFrameDriver {
1153 fn calls(&self) -> Vec<DriverCall> {
1154 self.calls.borrow().clone()
1155 }
1156 }
1157
1158 impl PlatformFrameDriver for RecordingFrameDriver {
1159 fn request_frame(&self) {
1160 self.calls.borrow_mut().push(DriverCall::RequestFrame);
1161 }
1162
1163 fn request_wake_at(&self, deadline: Instant) {
1164 self.calls
1165 .borrow_mut()
1166 .push(DriverCall::RequestWakeAt(deadline));
1167 }
1168
1169 fn clear_wake(&self) {
1170 self.calls.borrow_mut().push(DriverCall::ClearWake);
1171 }
1172 }
1173
1174 #[test]
1175 fn frame_pacing_labels_match_overlay_modes() {
1176 assert_eq!(FramePacingMode::Vsync.label(), "VSync");
1177 assert_eq!(FramePacingMode::Hard60.label(), "60fps");
1178 assert_eq!(FramePacingMode::Hard120.label(), "120fps");
1179 assert_eq!(FramePacingMode::NoVsync.label(), "NoVSync");
1180 }
1181
1182 #[test]
1183 fn only_hard_modes_have_fixed_targets() {
1184 assert_eq!(FramePacingMode::Vsync.target_fps(), None);
1185 assert_eq!(FramePacingMode::Hard60.target_fps(), Some(60));
1186 assert_eq!(FramePacingMode::Hard120.target_fps(), Some(120));
1187 assert_eq!(FramePacingMode::NoVsync.target_fps(), None);
1188 }
1189
1190 #[test]
1191 fn frame_schedule_requests_immediate_frame_and_clears_deadline() {
1192 let driver = RecordingFrameDriver::default();
1193 let deadline = Instant::now() + Duration::from_millis(25);
1194
1195 FrameSchedule {
1196 needs_update: true,
1197 needs_frame: true,
1198 next_deadline: Some(deadline),
1199 }
1200 .apply_to(&driver);
1201
1202 assert_eq!(
1203 driver.calls(),
1204 vec![DriverCall::ClearWake, DriverCall::RequestFrame]
1205 );
1206 }
1207
1208 #[test]
1209 fn frame_schedule_requests_deadline_when_idle_until_timer() {
1210 let driver = RecordingFrameDriver::default();
1211 let deadline = Instant::now() + Duration::from_millis(25);
1212
1213 FrameSchedule {
1214 needs_update: false,
1215 needs_frame: false,
1216 next_deadline: Some(deadline),
1217 }
1218 .apply_to(&driver);
1219
1220 assert_eq!(driver.calls(), vec![DriverCall::RequestWakeAt(deadline)]);
1221 }
1222
1223 #[test]
1224 fn frame_schedule_wakes_without_requesting_frame_for_update_only_work() {
1225 let driver = RecordingFrameDriver::default();
1226 let before = Instant::now();
1227
1228 FrameSchedule {
1229 needs_update: true,
1230 needs_frame: false,
1231 next_deadline: None,
1232 }
1233 .apply_to(&driver);
1234
1235 let calls = driver.calls();
1236 assert_eq!(calls.len(), 1);
1237 match calls[0] {
1238 DriverCall::RequestWakeAt(deadline) => {
1239 assert!(deadline >= before);
1240 }
1241 other => panic!("update-only work must wake without requesting a frame: {other:?}"),
1242 }
1243 }
1244
1245 #[test]
1246 fn frame_schedule_clears_wake_when_fully_idle() {
1247 let driver = RecordingFrameDriver::default();
1248
1249 FrameSchedule {
1250 needs_update: false,
1251 needs_frame: false,
1252 next_deadline: None,
1253 }
1254 .apply_to(&driver);
1255
1256 assert_eq!(driver.calls(), vec![DriverCall::ClearWake]);
1257 }
1258
1259 #[test]
1260 fn frame_scheduler_records_latest_schedule_and_applies_driver() {
1261 let scheduler = FrameScheduler::default();
1262 let driver = RecordingFrameDriver::default();
1263 let deadline = Instant::now() + Duration::from_millis(25);
1264
1265 scheduler.schedule(
1266 FrameSchedule {
1267 needs_update: false,
1268 needs_frame: false,
1269 next_deadline: Some(deadline),
1270 },
1271 &driver,
1272 );
1273
1274 assert_eq!(
1275 scheduler.snapshot(),
1276 FrameSchedule {
1277 needs_update: false,
1278 needs_frame: false,
1279 next_deadline: Some(deadline),
1280 }
1281 );
1282 assert_eq!(driver.calls(), vec![DriverCall::RequestWakeAt(deadline)]);
1283 }
1284
1285 #[test]
1286 fn frame_scheduler_clears_deadline_for_immediate_frame() {
1287 let scheduler = FrameScheduler::default();
1288 let driver = RecordingFrameDriver::default();
1289 let deadline = Instant::now() + Duration::from_millis(25);
1290
1291 scheduler.schedule(
1292 FrameSchedule {
1293 needs_update: true,
1294 needs_frame: true,
1295 next_deadline: Some(deadline),
1296 },
1297 &driver,
1298 );
1299
1300 assert_eq!(
1301 scheduler.snapshot(),
1302 FrameSchedule {
1303 needs_update: true,
1304 needs_frame: true,
1305 next_deadline: None,
1306 }
1307 );
1308 assert_eq!(
1309 driver.calls(),
1310 vec![DriverCall::ClearWake, DriverCall::RequestFrame]
1311 );
1312 }
1313
1314 #[test]
1315 fn frame_scheduler_recovers_poisoned_deadline_lock() {
1316 let scheduler = FrameScheduler::default();
1317 let deadline = Instant::now() + Duration::from_millis(25);
1318
1319 let _ = catch_unwind(AssertUnwindSafe(|| {
1320 let _guard = scheduler.lock_deadline();
1321 panic!("poison frame scheduler deadline lock");
1322 }));
1323
1324 scheduler.record(FrameSchedule {
1325 needs_update: false,
1326 needs_frame: false,
1327 next_deadline: Some(deadline),
1328 });
1329
1330 assert_eq!(
1331 scheduler.snapshot(),
1332 FrameSchedule {
1333 needs_update: false,
1334 needs_frame: false,
1335 next_deadline: Some(deadline),
1336 }
1337 );
1338 }
1339}
1340
1341#[cfg(test)]
1342#[path = "tests/app_shell_tests.rs"]
1343mod tests;