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 has_pending_ui(&self) -> bool {
786 let app_context = Rc::clone(&self.app_context);
787 app_context.enter(|| self.composition.runtime_handle().has_pending_ui())
788 }
789
790 pub fn needs_redraw(&self) -> bool {
803 let app_context = Rc::clone(&self.app_context);
804 app_context
805 .enter(|| self.has_stale_pixels_in_context() || self.renderer.needs_frame_warmup())
806 }
807
808 pub fn mark_dirty(&mut self) {
810 self.is_dirty = true;
811 }
812
813 pub fn request_root_render(&mut self) {
814 self.composition.request_root_render();
815 self.request_forced_layout_pass();
816 let app_context = Rc::clone(&self.app_context);
817 app_context.enter(request_render_invalidation);
818 self.mark_dirty();
819 }
820
821 pub fn set_density(&mut self, density: f32) {
822 let app_context = Rc::clone(&self.app_context);
823 let changed = app_context.enter(|| {
824 let previous = cranpose_ui::current_density().to_bits();
825 cranpose_ui::set_density(density);
826 previous != cranpose_ui::current_density().to_bits()
827 });
828 if changed {
829 self.request_forced_layout_pass();
830 self.mark_dirty();
831 }
832 }
833
834 pub fn set_font_scale(&mut self, font_scale: f32) {
840 let app_context = Rc::clone(&self.app_context);
841 let changed = app_context.enter(|| {
842 let previous = cranpose_ui::current_font_scale().to_bits();
843 cranpose_ui::set_font_scale(font_scale);
844 previous != cranpose_ui::current_font_scale().to_bits()
845 });
846 if changed {
847 self.request_forced_layout_pass();
848 self.mark_dirty();
849 }
850 }
851
852 #[cfg(any(test, feature = "test-support"))]
853 #[doc(hidden)]
854 pub fn debug_current_density(&self) -> f32 {
855 let app_context = Rc::clone(&self.app_context);
856 app_context.enter(cranpose_ui::current_density)
857 }
858
859 #[cfg(any(test, feature = "test-support"))]
860 #[doc(hidden)]
861 pub fn debug_current_font_scale(&self) -> f32 {
862 let app_context = Rc::clone(&self.app_context);
863 app_context.enter(cranpose_ui::current_font_scale)
864 }
865
866 #[cfg(any(test, feature = "test-support"))]
867 #[doc(hidden)]
868 pub fn debug_enter_app_context<T>(&self, block: impl FnOnce() -> T) -> T {
869 let app_context = Rc::clone(&self.app_context);
870 app_context.enter(block)
871 }
872
873 fn request_layout_pass(&mut self) {
874 self.layout_requested = true;
875 }
876
877 fn request_forced_layout_pass(&mut self) {
878 self.layout_requested = true;
879 self.force_layout_pass = true;
880 }
881
882 fn composition_tree_needs_layout(&mut self) -> bool {
883 let Some(root) = self.composition.root() else {
884 return true;
885 };
886 let mut applier = self.composition.applier_mut();
887 cranpose_ui::tree_needs_layout(&mut *applier, root).unwrap_or_else(|err| {
888 log::warn!(
889 "Cannot check layout dirty status for root #{}: {}",
890 root,
891 err
892 );
893 true
894 })
895 }
896
897 pub fn has_active_animations(&self) -> bool {
899 self.composition.should_render()
900 }
901
902 pub fn has_active_pointer_gesture(&self) -> bool {
903 self.buttons_pressed != PointerButtons::NONE
904 && self.hit_path_tracker.has_path(PointerId::PRIMARY)
905 }
906
907 pub fn next_event_time(&self) -> Option<web_time::Instant> {
910 let app_context = Rc::clone(&self.app_context);
911 app_context.enter(cranpose_ui::next_cursor_blink_time)
912 }
913
914 fn compute_frame_schedule(&self) -> FrameSchedule {
915 let needs_update = self.needs_update();
916 let needs_frame = self.is_dirty
917 || self.should_render()
918 || self.has_active_pointer_gesture()
919 || self.renderer.needs_frame_warmup();
920 FrameSchedule {
921 needs_update,
922 needs_frame,
923 next_deadline: self.next_event_time(),
924 }
925 }
926
927 pub fn frame_schedule(&self) -> FrameSchedule {
928 let schedule = self.compute_frame_schedule();
929 self.frame_scheduler.record(schedule);
930 schedule
931 }
932
933 pub fn schedule_platform_frame<D>(&self, driver: &D) -> FrameSchedule
934 where
935 D: PlatformFrameDriver + ?Sized,
936 {
937 let schedule = self.compute_frame_schedule();
938 self.frame_scheduler.schedule(schedule, driver);
939 schedule
940 }
941
942 pub fn frame_scheduler_snapshot(&self) -> FrameSchedule {
943 self.frame_scheduler.snapshot()
944 }
945
946 fn frame_time_nanos_at(&self, now: Instant) -> u64 {
947 now.checked_duration_since(self.start_time)
948 .unwrap_or_default()
949 .as_nanos()
950 .min(u128::from(u64::MAX)) as u64
951 }
952
953 pub fn realtime_pointer_event_time(&self, platform_time_ms: Option<i64>) -> PointerEventTime {
955 PointerEventTime {
956 platform_time_ms,
957 animation_time_nanos: self
958 .frame_time_nanos_at(Instant::now())
959 .max(self.last_frame_time_nanos),
960 }
961 }
962
963 pub fn exact_pointer_event_time(&self, platform_time_ms: Option<i64>) -> PointerEventTime {
965 PointerEventTime {
966 platform_time_ms,
967 animation_time_nanos: self.last_frame_time_nanos,
968 }
969 }
970
971 pub fn update_after_frame_interval(
972 &mut self,
973 frame_interval: std::time::Duration,
974 ) -> FrameUpdateResult {
975 let wall_frame_time = self.frame_time_nanos_at(Instant::now());
976 let base_frame_time = self.last_frame_time_nanos.max(wall_frame_time);
977 let frame_time = base_frame_time
978 .saturating_add(frame_interval.as_nanos().min(u128::from(u64::MAX)) as u64);
979 self.update_at_frame_time_nanos(frame_time)
980 }
981
982 pub fn update_after_exact_interval(
988 &mut self,
989 frame_interval: std::time::Duration,
990 ) -> FrameUpdateResult {
991 let frame_time = self
992 .last_frame_time_nanos
993 .saturating_add(frame_interval.as_nanos().min(u128::from(u64::MAX)) as u64);
994 self.update_at_frame_time_nanos(frame_time)
995 }
996
997 pub fn update_at_frame_time_nanos(&mut self, frame_time: u64) -> FrameUpdateResult {
998 let app_context = Rc::clone(&self.app_context);
999 app_context.enter(|| {
1000 let update_started_at = Instant::now();
1001 let frame_time = frame_time.max(self.last_frame_time_nanos);
1002 self.last_frame_time_nanos = frame_time;
1003 let runtime_handle = self.runtime.runtime_handle();
1004 runtime_handle.with_deferred_state_releases(|| {
1005 self.runtime.drain_frame_callbacks(frame_time);
1006 let after_frame_callbacks = Instant::now();
1007 runtime_handle.drain_ui();
1008 let after_ui_drain = Instant::now();
1009 let should_render = self.composition.should_recompose();
1010 let mut reconcile_attempted = false;
1011 let mut reconcile_changed = false;
1012 if should_render {
1013 log::trace!(
1014 target: "cranpose::input",
1015 "update begin: should_render=true layout_requested={} scene_dirty={} is_dirty={}",
1016 self.layout_requested,
1017 self.scene_dirty,
1018 self.is_dirty
1019 );
1020 }
1021 if should_render {
1022 let Some(root_key) = self.composition.root_key() else {
1023 let result = self.process_frame_in_context(reconcile_changed);
1024 let after_process_frame = Instant::now();
1025 log_update_stage_telemetry(UpdateStageTelemetry {
1026 started_at: update_started_at,
1027 after_frame_callbacks,
1028 after_ui_drain,
1029 after_reconcile: after_ui_drain,
1030 after_process_frame,
1031 should_render,
1032 reconcile_attempted,
1033 reconcile_changed,
1034 });
1035 self.is_dirty = false;
1036 return result;
1037 };
1038 reconcile_attempted = true;
1039 match self.composition.reconcile(root_key, &mut *self.content) {
1040 Ok(changed) => {
1041 reconcile_changed = changed;
1042 log::trace!(
1043 target: "cranpose::input",
1044 "reconcile changed={changed}"
1045 );
1046 if changed {
1047 self.fps_monitor.record_recomposition();
1048 if self.composition_tree_needs_layout() {
1049 self.request_layout_pass();
1050 }
1051 request_render_invalidation();
1052 }
1053 }
1054 Err(NodeError::Missing { id }) => {
1055 log::debug!("Recomposition skipped: node {} no longer exists", id);
1056 self.request_layout_pass();
1057 request_render_invalidation();
1058 }
1059 Err(err) => {
1060 log::error!("recomposition failed: {err}");
1061 self.request_layout_pass();
1062 request_render_invalidation();
1063 }
1064 }
1065 }
1066 let after_reconcile = Instant::now();
1067 let result = self.process_frame_in_context(reconcile_changed);
1068 let after_process_frame = Instant::now();
1069 log_update_stage_telemetry(UpdateStageTelemetry {
1070 started_at: update_started_at,
1071 after_frame_callbacks,
1072 after_ui_drain,
1073 after_reconcile,
1074 after_process_frame,
1075 should_render,
1076 reconcile_attempted,
1077 reconcile_changed,
1078 });
1079 self.is_dirty = false;
1080 result
1081 })
1082 })
1083 }
1084
1085 pub fn update(&mut self) -> FrameUpdateResult {
1086 let frame_time = self.frame_time_nanos_at(Instant::now());
1087 self.update_at_frame_time_nanos(frame_time)
1088 }
1089}
1090
1091impl<R> Drop for AppShell<R>
1092where
1093 R: Renderer,
1094{
1095 fn drop(&mut self) {
1096 self.runtime.clear_frame_waker();
1097 }
1098}
1099
1100pub fn default_root_key() -> Key {
1101 location_key(file!(), line!(), column!())
1102}
1103
1104#[cfg(test)]
1105mod frame_pacing_tests {
1106 use super::{FramePacingMode, FrameSchedule, FrameScheduler, PlatformFrameDriver};
1107 use std::cell::RefCell;
1108 use std::panic::{catch_unwind, AssertUnwindSafe};
1109 use std::time::Duration;
1110 use web_time::Instant;
1111
1112 #[derive(Clone, Copy, Debug, PartialEq)]
1113 enum DriverCall {
1114 RequestFrame,
1115 RequestWakeAt(Instant),
1116 ClearWake,
1117 }
1118
1119 #[derive(Default)]
1120 struct RecordingFrameDriver {
1121 calls: RefCell<Vec<DriverCall>>,
1122 }
1123
1124 impl RecordingFrameDriver {
1125 fn calls(&self) -> Vec<DriverCall> {
1126 self.calls.borrow().clone()
1127 }
1128 }
1129
1130 impl PlatformFrameDriver for RecordingFrameDriver {
1131 fn request_frame(&self) {
1132 self.calls.borrow_mut().push(DriverCall::RequestFrame);
1133 }
1134
1135 fn request_wake_at(&self, deadline: Instant) {
1136 self.calls
1137 .borrow_mut()
1138 .push(DriverCall::RequestWakeAt(deadline));
1139 }
1140
1141 fn clear_wake(&self) {
1142 self.calls.borrow_mut().push(DriverCall::ClearWake);
1143 }
1144 }
1145
1146 #[test]
1147 fn frame_pacing_labels_match_overlay_modes() {
1148 assert_eq!(FramePacingMode::Vsync.label(), "VSync");
1149 assert_eq!(FramePacingMode::Hard60.label(), "60fps");
1150 assert_eq!(FramePacingMode::Hard120.label(), "120fps");
1151 assert_eq!(FramePacingMode::NoVsync.label(), "NoVSync");
1152 }
1153
1154 #[test]
1155 fn only_hard_modes_have_fixed_targets() {
1156 assert_eq!(FramePacingMode::Vsync.target_fps(), None);
1157 assert_eq!(FramePacingMode::Hard60.target_fps(), Some(60));
1158 assert_eq!(FramePacingMode::Hard120.target_fps(), Some(120));
1159 assert_eq!(FramePacingMode::NoVsync.target_fps(), None);
1160 }
1161
1162 #[test]
1163 fn frame_schedule_requests_immediate_frame_and_clears_deadline() {
1164 let driver = RecordingFrameDriver::default();
1165 let deadline = Instant::now() + Duration::from_millis(25);
1166
1167 FrameSchedule {
1168 needs_update: true,
1169 needs_frame: true,
1170 next_deadline: Some(deadline),
1171 }
1172 .apply_to(&driver);
1173
1174 assert_eq!(
1175 driver.calls(),
1176 vec![DriverCall::ClearWake, DriverCall::RequestFrame]
1177 );
1178 }
1179
1180 #[test]
1181 fn frame_schedule_requests_deadline_when_idle_until_timer() {
1182 let driver = RecordingFrameDriver::default();
1183 let deadline = Instant::now() + Duration::from_millis(25);
1184
1185 FrameSchedule {
1186 needs_update: false,
1187 needs_frame: false,
1188 next_deadline: Some(deadline),
1189 }
1190 .apply_to(&driver);
1191
1192 assert_eq!(driver.calls(), vec![DriverCall::RequestWakeAt(deadline)]);
1193 }
1194
1195 #[test]
1196 fn frame_schedule_wakes_without_requesting_frame_for_update_only_work() {
1197 let driver = RecordingFrameDriver::default();
1198 let before = Instant::now();
1199
1200 FrameSchedule {
1201 needs_update: true,
1202 needs_frame: false,
1203 next_deadline: None,
1204 }
1205 .apply_to(&driver);
1206
1207 let calls = driver.calls();
1208 assert_eq!(calls.len(), 1);
1209 match calls[0] {
1210 DriverCall::RequestWakeAt(deadline) => {
1211 assert!(deadline >= before);
1212 }
1213 other => panic!("update-only work must wake without requesting a frame: {other:?}"),
1214 }
1215 }
1216
1217 #[test]
1218 fn frame_schedule_clears_wake_when_fully_idle() {
1219 let driver = RecordingFrameDriver::default();
1220
1221 FrameSchedule {
1222 needs_update: false,
1223 needs_frame: false,
1224 next_deadline: None,
1225 }
1226 .apply_to(&driver);
1227
1228 assert_eq!(driver.calls(), vec![DriverCall::ClearWake]);
1229 }
1230
1231 #[test]
1232 fn frame_scheduler_records_latest_schedule_and_applies_driver() {
1233 let scheduler = FrameScheduler::default();
1234 let driver = RecordingFrameDriver::default();
1235 let deadline = Instant::now() + Duration::from_millis(25);
1236
1237 scheduler.schedule(
1238 FrameSchedule {
1239 needs_update: false,
1240 needs_frame: false,
1241 next_deadline: Some(deadline),
1242 },
1243 &driver,
1244 );
1245
1246 assert_eq!(
1247 scheduler.snapshot(),
1248 FrameSchedule {
1249 needs_update: false,
1250 needs_frame: false,
1251 next_deadline: Some(deadline),
1252 }
1253 );
1254 assert_eq!(driver.calls(), vec![DriverCall::RequestWakeAt(deadline)]);
1255 }
1256
1257 #[test]
1258 fn frame_scheduler_clears_deadline_for_immediate_frame() {
1259 let scheduler = FrameScheduler::default();
1260 let driver = RecordingFrameDriver::default();
1261 let deadline = Instant::now() + Duration::from_millis(25);
1262
1263 scheduler.schedule(
1264 FrameSchedule {
1265 needs_update: true,
1266 needs_frame: true,
1267 next_deadline: Some(deadline),
1268 },
1269 &driver,
1270 );
1271
1272 assert_eq!(
1273 scheduler.snapshot(),
1274 FrameSchedule {
1275 needs_update: true,
1276 needs_frame: true,
1277 next_deadline: None,
1278 }
1279 );
1280 assert_eq!(
1281 driver.calls(),
1282 vec![DriverCall::ClearWake, DriverCall::RequestFrame]
1283 );
1284 }
1285
1286 #[test]
1287 fn frame_scheduler_recovers_poisoned_deadline_lock() {
1288 let scheduler = FrameScheduler::default();
1289 let deadline = Instant::now() + Duration::from_millis(25);
1290
1291 let _ = catch_unwind(AssertUnwindSafe(|| {
1292 let _guard = scheduler.lock_deadline();
1293 panic!("poison frame scheduler deadline lock");
1294 }));
1295
1296 scheduler.record(FrameSchedule {
1297 needs_update: false,
1298 needs_frame: false,
1299 next_deadline: Some(deadline),
1300 });
1301
1302 assert_eq!(
1303 scheduler.snapshot(),
1304 FrameSchedule {
1305 needs_update: false,
1306 needs_frame: false,
1307 next_deadline: Some(deadline),
1308 }
1309 );
1310 }
1311}
1312
1313#[cfg(test)]
1314#[path = "tests/app_shell_tests.rs"]
1315mod tests;