Skip to main content

cranpose_app_shell/
lib.rs

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};
20// Use web_time for cross-platform time support (native + WASM) - compatible with winit
21use 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
44// Re-export key event types for use by cranpose
45pub use cranpose_ui::{KeyCode, KeyEvent, KeyEventType, Modifiers};
46// Re-export the platform soft-keyboard hook so runtimes only depend on the shell
47pub use cranpose_ui::PlatformTextInputHandler;
48
49#[cfg(any(test, feature = "test-support"))]
50use cranpose_core::{
51    debug_recompose_scope_registry_stats, MemoryApplierDebugStats,
52    RecomposeScopeRegistryDebugStats, SlotTableDebugStats,
53};
54#[cfg(any(test, feature = "test-support"))]
55use cranpose_core::{
56    runtime::{RuntimeDebugStats, StateArenaDebugStats},
57    snapshot_pinning::{debug_snapshot_pinning_stats, SnapshotPinningDebugStats},
58    snapshot_state_observer::SnapshotStateObserverDebugStats,
59    snapshot_v2::{debug_snapshot_v2_stats, SnapshotV2DebugStats},
60    CompositionPassDebugStats, SlotId,
61};
62
63pub struct AppShell<R>
64where
65    R: Renderer,
66{
67    app_context: Rc<cranpose_ui::AppContext>,
68    runtime: StdRuntime,
69    composition: Composition<MemoryApplier>,
70    content: Box<dyn FnMut()>,
71    renderer: R,
72    cursor: (f32, f32),
73    viewport: (f32, f32),
74    buffer_size: (u32, u32),
75    start_time: Instant,
76    last_frame_time_nanos: u64,
77    layout_tree: Option<LayoutTree>,
78    semantics_tree: Option<SemanticsTree>,
79    semantics_enabled: bool,
80    layout_requested: bool,
81    force_layout_pass: bool,
82    scene_dirty: bool,
83    scoped_layout_scene_nodes: Vec<NodeId>,
84    is_dirty: bool,
85    /// Tracks which mouse buttons are currently pressed
86    buttons_pressed: PointerButtons,
87    /// Tracks which nodes were hit on PointerDown (by stable NodeId).
88    ///
89    /// This follows Jetpack Compose's HitPathTracker pattern:
90    /// - On Down: cache NodeIds, not geometry
91    /// - On Move/Up/Cancel: resolve fresh HitTargets from current scene
92    /// - Handler closures are preserved (same Rc), so internal state survives
93    hit_path_tracker: HitPathTracker,
94    /// Tracks which nodes the pointer is currently hovering over.
95    /// Used to synthesize Enter/Exit events when the hover set changes.
96    hovered_nodes: Vec<NodeId>,
97    /// Persistent clipboard for desktop (Linux X11 requires clipboard to stay alive)
98    #[cfg(all(
99        feature = "clipboard-native",
100        not(target_arch = "wasm32"),
101        not(target_os = "android"),
102        not(target_os = "ios")
103    ))]
104    clipboard: Option<arboard::Clipboard>,
105    /// Dev options for debugging and performance monitoring
106    dev_options: DevOptions,
107    dev_overlay_controls: Vec<DevOverlayControl>,
108    dev_overlay_text: String,
109    dev_overlay_last_refresh: Option<Instant>,
110    dev_overlay_viewport: Option<Size>,
111    fps_monitor: fps_monitor::FpsMonitor,
112    frame_scheduler: FrameScheduler,
113}
114
115fn update_stage_telemetry_threshold_ms() -> Option<f64> {
116    static THRESHOLD_MS: std::sync::OnceLock<Option<f64>> = std::sync::OnceLock::new();
117    *THRESHOLD_MS.get_or_init(|| {
118        std::env::var("CRANPOSE_UPDATE_STAGE_TELEMETRY_MS")
119            .ok()
120            .and_then(|value| value.parse::<f64>().ok())
121            .filter(|value| value.is_finite() && *value >= 0.0)
122    })
123}
124
125#[derive(Clone, Copy, Debug)]
126struct UpdateStageTelemetry {
127    started_at: Instant,
128    after_frame_callbacks: Instant,
129    after_ui_drain: Instant,
130    after_reconcile: Instant,
131    after_process_frame: Instant,
132    should_render: bool,
133    reconcile_attempted: bool,
134    reconcile_changed: bool,
135}
136
137fn log_update_stage_telemetry(telemetry: UpdateStageTelemetry) {
138    let Some(threshold_ms) = update_stage_telemetry_threshold_ms() else {
139        return;
140    };
141    let total_ms = telemetry
142        .after_process_frame
143        .duration_since(telemetry.started_at)
144        .as_secs_f64()
145        * 1000.0;
146    if total_ms < threshold_ms {
147        return;
148    }
149
150    let frame_callbacks_ms = telemetry
151        .after_frame_callbacks
152        .duration_since(telemetry.started_at)
153        .as_secs_f64()
154        * 1000.0;
155    let ui_drain_ms = telemetry
156        .after_ui_drain
157        .duration_since(telemetry.after_frame_callbacks)
158        .as_secs_f64()
159        * 1000.0;
160    let reconcile_ms = telemetry
161        .after_reconcile
162        .duration_since(telemetry.after_ui_drain)
163        .as_secs_f64()
164        * 1000.0;
165    let process_frame_ms = telemetry
166        .after_process_frame
167        .duration_since(telemetry.after_reconcile)
168        .as_secs_f64()
169        * 1000.0;
170    eprintln!(
171        "[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={}",
172        telemetry.should_render,
173        telemetry.reconcile_attempted,
174        telemetry.reconcile_changed
175    );
176}
177
178#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
179pub enum FramePacingMode {
180    /// Pace frames to the display refresh interval. The production default:
181    /// animations advance once per vsync instead of re-rendering uncapped.
182    #[default]
183    Vsync,
184    Hard60,
185    Hard120,
186    /// Render as fast as possible. For perf harnesses and robot drivers that
187    /// measure work throughput; saturates the GPU if used in a real app.
188    NoVsync,
189}
190
191impl FramePacingMode {
192    pub const ALL: [Self; 4] = [Self::Vsync, Self::Hard60, Self::Hard120, Self::NoVsync];
193
194    pub fn label(self) -> &'static str {
195        match self {
196            Self::Vsync => "VSync",
197            Self::Hard60 => "60fps",
198            Self::Hard120 => "120fps",
199            Self::NoVsync => "NoVSync",
200        }
201    }
202
203    pub fn target_fps(self) -> Option<u32> {
204        match self {
205            Self::Hard60 => Some(60),
206            Self::Hard120 => Some(120),
207            Self::Vsync | Self::NoVsync => None,
208        }
209    }
210}
211
212#[derive(Clone, Copy, Debug, PartialEq)]
213pub struct FrameSchedule {
214    pub needs_update: bool,
215    pub needs_frame: bool,
216    pub next_deadline: Option<web_time::Instant>,
217}
218
219#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
220pub struct FrameUpdateResult {
221    pub visual_changed: bool,
222    pub structure_changed: bool,
223}
224
225pub trait PlatformFrameDriver {
226    fn request_frame(&self);
227    fn request_wake_at(&self, deadline: web_time::Instant);
228    fn clear_wake(&self);
229}
230
231#[derive(Debug)]
232pub struct FrameScheduler {
233    update_pending: AtomicBool,
234    frame_pending: AtomicBool,
235    next_deadline: Mutex<Option<web_time::Instant>>,
236}
237
238impl Default for FrameScheduler {
239    fn default() -> Self {
240        Self {
241            update_pending: AtomicBool::new(false),
242            frame_pending: AtomicBool::new(false),
243            next_deadline: Mutex::new(None),
244        }
245    }
246}
247
248impl FrameScheduler {
249    fn lock_deadline(&self) -> MutexGuard<'_, Option<web_time::Instant>> {
250        self.next_deadline
251            .lock()
252            .unwrap_or_else(|poisoned| poisoned.into_inner())
253    }
254
255    pub fn record(&self, schedule: FrameSchedule) {
256        self.update_pending
257            .store(schedule.needs_update, Ordering::SeqCst);
258        self.frame_pending
259            .store(schedule.needs_frame, Ordering::SeqCst);
260        let mut next_deadline = self.lock_deadline();
261        *next_deadline = if schedule.needs_update {
262            None
263        } else {
264            schedule.next_deadline
265        };
266    }
267
268    pub fn schedule<D>(&self, schedule: FrameSchedule, driver: &D)
269    where
270        D: PlatformFrameDriver + ?Sized,
271    {
272        self.record(schedule);
273        schedule.apply_to(driver);
274    }
275
276    pub fn snapshot(&self) -> FrameSchedule {
277        FrameSchedule {
278            needs_update: self.update_pending.load(Ordering::SeqCst),
279            needs_frame: self.frame_pending.load(Ordering::SeqCst),
280            next_deadline: *self.lock_deadline(),
281        }
282    }
283}
284
285impl FrameSchedule {
286    pub fn apply_to<D>(self, driver: &D)
287    where
288        D: PlatformFrameDriver + ?Sized,
289    {
290        if self.needs_frame {
291            driver.clear_wake();
292            driver.request_frame();
293        } else if self.needs_update {
294            driver.request_wake_at(web_time::Instant::now());
295        } else if let Some(deadline) = self.next_deadline {
296            driver.request_wake_at(deadline);
297        } else {
298            driver.clear_wake();
299        }
300    }
301}
302
303#[derive(Clone, Copy, Debug)]
304struct DevOverlayControl {
305    bounds: Rect,
306    mode: FramePacingMode,
307}
308
309/// Development options for debugging and performance monitoring.
310///
311/// These are rendered directly by the renderer (not via composition)
312/// to avoid affecting performance measurements.
313#[derive(Clone, Debug, Default)]
314pub struct DevOptions {
315    /// Show FPS counter overlay
316    pub fps_counter: bool,
317    /// Show recomposition count
318    pub recomposition_counter: bool,
319    /// Show layout timing breakdown
320    pub layout_timing: bool,
321    pub frame_pacing_controls: bool,
322    pub frame_pacing_mode: FramePacingMode,
323}
324
325#[cfg(any(test, feature = "test-support"))]
326#[doc(hidden)]
327#[derive(Clone, Copy, Debug)]
328pub struct RuntimeLeakDebugStats {
329    pub applier_stats: MemoryApplierDebugStats,
330    pub live_node_heap_bytes: usize,
331    pub recycled_node_heap_bytes: usize,
332    pub slot_table_heap_bytes: usize,
333    pub pass_stats: CompositionPassDebugStats,
334    pub slot_stats: SlotTableDebugStats,
335    pub observer_stats: SnapshotStateObserverDebugStats,
336    pub runtime_stats: RuntimeDebugStats,
337    pub state_arena_stats: StateArenaDebugStats,
338    pub recompose_scope_stats: RecomposeScopeRegistryDebugStats,
339    pub snapshot_v2_stats: SnapshotV2DebugStats,
340    pub snapshot_pinning_stats: SnapshotPinningDebugStats,
341}
342
343impl<R> AppShell<R>
344where
345    R: Renderer,
346    R::Error: Debug,
347{
348    pub fn new(renderer: R, root_key: Key, content: impl FnMut() + 'static) -> Self {
349        Self::new_with_size(renderer, root_key, content, (800, 600), (800.0, 600.0))
350    }
351
352    pub fn new_with_size(
353        renderer: R,
354        root_key: Key,
355        content: impl FnMut() + 'static,
356        buffer_size: (u32, u32),
357        viewport: (f32, f32),
358    ) -> Self {
359        Self::new_with_size_and_density(renderer, root_key, content, buffer_size, viewport, 1.0)
360    }
361
362    pub fn new_with_size_and_density(
363        mut renderer: R,
364        root_key: Key,
365        content: impl FnMut() + 'static,
366        buffer_size: (u32, u32),
367        viewport: (f32, f32),
368        density: f32,
369    ) -> Self {
370        let app_context = cranpose_ui::AppContext::new_with_density(density);
371        let runtime = StdRuntime::new();
372        let mut composition = Composition::with_runtime(MemoryApplier::new(), runtime.runtime());
373        let mut build: Box<dyn FnMut()> = Box::new(content);
374        renderer.attach_app_context_services(&app_context);
375        app_context.enter(|| {
376            if let Err(err) = composition.render_stable(root_key, &mut *build) {
377                log::error!("initial render failed: {err}");
378            }
379        });
380        renderer.scene_mut().clear();
381        let mut shell = Self {
382            app_context,
383            runtime,
384            composition,
385            content: build,
386            renderer,
387            cursor: (0.0, 0.0),
388            viewport,
389            buffer_size,
390            start_time: Instant::now(),
391            last_frame_time_nanos: 0,
392            layout_tree: None,
393            semantics_tree: None,
394            semantics_enabled: false,
395            layout_requested: true,
396            force_layout_pass: true,
397            scene_dirty: true,
398            scoped_layout_scene_nodes: Vec::new(),
399            is_dirty: true,
400            buttons_pressed: PointerButtons::NONE,
401            hit_path_tracker: HitPathTracker::new(),
402            hovered_nodes: Vec::new(),
403            #[cfg(all(
404                feature = "clipboard-native",
405                not(target_arch = "wasm32"),
406                not(target_os = "android"),
407                not(target_os = "ios")
408            ))]
409            clipboard: arboard::Clipboard::new().ok(),
410            dev_options: DevOptions::default(),
411            dev_overlay_controls: Vec::new(),
412            dev_overlay_text: String::new(),
413            dev_overlay_last_refresh: None,
414            dev_overlay_viewport: None,
415            fps_monitor: fps_monitor::FpsMonitor::new(),
416            frame_scheduler: FrameScheduler::default(),
417        };
418        shell.process_frame();
419        shell
420    }
421
422    /// Set development options for debugging and performance monitoring.
423    ///
424    /// The FPS counter and other overlays are rendered directly by the renderer
425    /// (not via composition) to avoid affecting performance measurements.
426    pub fn set_dev_options(&mut self, options: DevOptions) {
427        self.dev_options = options;
428        self.invalidate_dev_overlay_text();
429        let app_context = Rc::clone(&self.app_context);
430        app_context.enter(request_render_invalidation);
431        self.mark_dirty();
432    }
433
434    /// Get a reference to the current dev options.
435    pub fn dev_options(&self) -> &DevOptions {
436        &self.dev_options
437    }
438
439    pub fn frame_pacing_mode(&self) -> FramePacingMode {
440        self.dev_options.frame_pacing_mode
441    }
442
443    pub fn current_fps(&self) -> f32 {
444        self.fps_monitor.current_fps()
445    }
446
447    pub fn fps_stats(&self) -> FpsStats {
448        self.fps_monitor.stats()
449    }
450
451    pub fn reset_fps_stats(&mut self) {
452        self.fps_monitor.reset_stats();
453        self.invalidate_dev_overlay_text();
454    }
455
456    pub fn record_presented_frame(
457        &mut self,
458        frame_started_at: Instant,
459        frame_finished_at: Instant,
460    ) {
461        self.fps_monitor
462            .record_frame_work(frame_started_at, frame_finished_at);
463    }
464
465    #[cfg(any(test, feature = "test-support"))]
466    #[doc(hidden)]
467    pub fn record_presented_frame_for_test(
468        &mut self,
469        frame_started_nanos: u64,
470        frame_finished_nanos: u64,
471    ) {
472        let started = self.start_time + std::time::Duration::from_nanos(frame_started_nanos);
473        let finished = self.start_time + std::time::Duration::from_nanos(frame_finished_nanos);
474        self.record_presented_frame(started, finished);
475    }
476
477    pub fn set_frame_pacing_mode(&mut self, mode: FramePacingMode) {
478        if self.dev_options.frame_pacing_mode == mode {
479            return;
480        }
481        self.dev_options.frame_pacing_mode = mode;
482        self.invalidate_dev_overlay_text();
483        let app_context = Rc::clone(&self.app_context);
484        app_context.enter(request_render_invalidation);
485        self.mark_dirty();
486    }
487
488    pub fn handle_dev_overlay_click(&mut self, x: f32, y: f32) -> Option<FramePacingMode> {
489        if !self.dev_options.frame_pacing_controls {
490            return None;
491        }
492        let mode = self
493            .dev_overlay_controls
494            .iter()
495            .find(|control| control.bounds.contains(x, y))
496            .map(|control| control.mode)?;
497        self.set_frame_pacing_mode(mode);
498        Some(mode)
499    }
500
501    fn invalidate_dev_overlay_text(&mut self) {
502        self.dev_overlay_text.clear();
503        self.dev_overlay_last_refresh = None;
504        self.dev_overlay_viewport = None;
505    }
506
507    pub fn set_viewport(&mut self, width: f32, height: f32) {
508        self.viewport = (width, height);
509        self.request_forced_layout_pass();
510        self.mark_dirty();
511        self.process_frame();
512    }
513
514    pub fn viewport_size(&self) -> (f32, f32) {
515        self.viewport
516    }
517
518    pub fn set_buffer_size(&mut self, width: u32, height: u32) {
519        self.buffer_size = (width, height);
520    }
521
522    pub fn buffer_size(&self) -> (u32, u32) {
523        self.buffer_size
524    }
525
526    pub fn scene(&self) -> &R::Scene {
527        self.renderer.scene()
528    }
529
530    pub fn renderer(&mut self) -> &mut R {
531        &mut self.renderer
532    }
533
534    #[cfg(not(target_arch = "wasm32"))]
535    pub fn set_frame_waker(&mut self, waker: impl Fn() + Send + Sync + 'static) {
536        self.runtime.set_frame_waker(waker);
537    }
538
539    #[cfg(target_arch = "wasm32")]
540    pub fn set_frame_waker(&mut self, waker: impl Fn() + 'static) {
541        self.runtime.set_frame_waker(waker);
542    }
543
544    pub fn clear_frame_waker(&mut self) {
545        self.runtime.clear_frame_waker();
546    }
547
548    pub fn should_render(&self) -> bool {
549        let app_context = Rc::clone(&self.app_context);
550        app_context.enter(|| {
551            if self.layout_requested
552                || self.scene_dirty
553                || peek_render_invalidation()
554                || peek_pointer_invalidation()
555                || peek_focus_invalidation()
556                || peek_layout_invalidation()
557            {
558                return true;
559            }
560            self.composition.should_render()
561        })
562    }
563
564    fn needs_ui_update_in_context(&self) -> bool {
565        if self.is_dirty
566            || self.layout_requested
567            || self.scene_dirty
568            || peek_render_invalidation()
569            || peek_pointer_invalidation()
570            || peek_focus_invalidation()
571            || peek_layout_invalidation()
572            || cranpose_ui::has_pending_layout_repasses()
573            || cranpose_ui::has_pending_draw_repasses()
574            || has_pending_pointer_repasses()
575            || has_pending_focus_invalidations()
576        {
577            return true;
578        }
579
580        self.composition.should_render()
581    }
582
583    pub fn needs_update(&self) -> bool {
584        let app_context = Rc::clone(&self.app_context);
585        app_context.enter(|| self.needs_ui_update_in_context())
586    }
587
588    /// Returns true if the shell needs to redraw (dirty flag, layout dirty, active animations).
589    /// Note: Cursor blink is now timer-based and uses WaitUntil scheduling, not continuous redraw.
590    pub fn needs_redraw(&self) -> bool {
591        let app_context = Rc::clone(&self.app_context);
592        app_context
593            .enter(|| self.needs_ui_update_in_context() || self.renderer.needs_frame_warmup())
594    }
595
596    /// Marks the shell as dirty, indicating a redraw is needed.
597    pub fn mark_dirty(&mut self) {
598        self.is_dirty = true;
599    }
600
601    pub fn request_root_render(&mut self) {
602        self.composition.request_root_render();
603        self.request_forced_layout_pass();
604        let app_context = Rc::clone(&self.app_context);
605        app_context.enter(request_render_invalidation);
606        self.mark_dirty();
607    }
608
609    pub fn set_density(&mut self, density: f32) {
610        let app_context = Rc::clone(&self.app_context);
611        let changed = app_context.enter(|| {
612            let previous = cranpose_ui::current_density().to_bits();
613            cranpose_ui::set_density(density);
614            previous != cranpose_ui::current_density().to_bits()
615        });
616        if changed {
617            self.request_forced_layout_pass();
618            self.mark_dirty();
619        }
620    }
621
622    #[cfg(any(test, feature = "test-support"))]
623    #[doc(hidden)]
624    pub fn debug_current_density(&self) -> f32 {
625        let app_context = Rc::clone(&self.app_context);
626        app_context.enter(cranpose_ui::current_density)
627    }
628
629    #[cfg(any(test, feature = "test-support"))]
630    #[doc(hidden)]
631    pub fn debug_enter_app_context<T>(&self, block: impl FnOnce() -> T) -> T {
632        let app_context = Rc::clone(&self.app_context);
633        app_context.enter(block)
634    }
635
636    fn request_layout_pass(&mut self) {
637        self.layout_requested = true;
638    }
639
640    fn request_forced_layout_pass(&mut self) {
641        self.layout_requested = true;
642        self.force_layout_pass = true;
643    }
644
645    fn composition_tree_needs_layout(&mut self) -> bool {
646        let Some(root) = self.composition.root() else {
647            return true;
648        };
649        let mut applier = self.composition.applier_mut();
650        cranpose_ui::tree_needs_layout(&mut *applier, root).unwrap_or_else(|err| {
651            log::warn!(
652                "Cannot check layout dirty status for root #{}: {}",
653                root,
654                err
655            );
656            true
657        })
658    }
659
660    /// Returns true if there are active animations or pending recompositions.
661    pub fn has_active_animations(&self) -> bool {
662        self.composition.should_render()
663    }
664
665    pub fn has_active_pointer_gesture(&self) -> bool {
666        self.buttons_pressed != PointerButtons::NONE
667            && self.hit_path_tracker.has_path(PointerId::PRIMARY)
668    }
669
670    /// Returns the next scheduled event time for cursor blink.
671    /// Use this for `ControlFlow::WaitUntil` scheduling.
672    pub fn next_event_time(&self) -> Option<web_time::Instant> {
673        let app_context = Rc::clone(&self.app_context);
674        app_context.enter(cranpose_ui::next_cursor_blink_time)
675    }
676
677    fn compute_frame_schedule(&self) -> FrameSchedule {
678        let needs_update = self.needs_update();
679        let needs_frame = needs_update
680            || self.has_active_animations()
681            || self.has_active_pointer_gesture()
682            || self.renderer.needs_frame_warmup();
683        FrameSchedule {
684            needs_update,
685            needs_frame,
686            next_deadline: self.next_event_time(),
687        }
688    }
689
690    pub fn frame_schedule(&self) -> FrameSchedule {
691        let schedule = self.compute_frame_schedule();
692        self.frame_scheduler.record(schedule);
693        schedule
694    }
695
696    pub fn schedule_platform_frame<D>(&self, driver: &D) -> FrameSchedule
697    where
698        D: PlatformFrameDriver + ?Sized,
699    {
700        let schedule = self.compute_frame_schedule();
701        self.frame_scheduler.schedule(schedule, driver);
702        schedule
703    }
704
705    pub fn frame_scheduler_snapshot(&self) -> FrameSchedule {
706        self.frame_scheduler.snapshot()
707    }
708
709    fn frame_time_nanos_at(&self, now: Instant) -> u64 {
710        now.checked_duration_since(self.start_time)
711            .unwrap_or_default()
712            .as_nanos()
713            .min(u128::from(u64::MAX)) as u64
714    }
715
716    pub fn update_after_frame_interval(
717        &mut self,
718        frame_interval: std::time::Duration,
719    ) -> FrameUpdateResult {
720        let wall_frame_time = self.frame_time_nanos_at(Instant::now());
721        let base_frame_time = self.last_frame_time_nanos.max(wall_frame_time);
722        let frame_time = base_frame_time
723            .saturating_add(frame_interval.as_nanos().min(u128::from(u64::MAX)) as u64);
724        self.update_at_frame_time_nanos(frame_time)
725    }
726
727    pub fn update_at_frame_time_nanos(&mut self, frame_time: u64) -> FrameUpdateResult {
728        let app_context = Rc::clone(&self.app_context);
729        app_context.enter(|| {
730            let update_started_at = Instant::now();
731            let frame_time = frame_time.max(self.last_frame_time_nanos);
732            self.last_frame_time_nanos = frame_time;
733            let runtime_handle = self.runtime.runtime_handle();
734            runtime_handle.with_deferred_state_releases(|| {
735                self.runtime.drain_frame_callbacks(frame_time);
736                let after_frame_callbacks = Instant::now();
737                runtime_handle.drain_ui();
738                let after_ui_drain = Instant::now();
739                let should_render = self.composition.should_render();
740                let mut reconcile_attempted = false;
741                let mut reconcile_changed = false;
742                if should_render {
743                    log::trace!(
744                        target: "cranpose::input",
745                        "update begin: should_render=true layout_requested={} scene_dirty={} is_dirty={}",
746                        self.layout_requested,
747                        self.scene_dirty,
748                        self.is_dirty
749                    );
750                }
751                if should_render {
752                    let Some(root_key) = self.composition.root_key() else {
753                        let result = self.process_frame_in_context(reconcile_changed);
754                        let after_process_frame = Instant::now();
755                        log_update_stage_telemetry(UpdateStageTelemetry {
756                            started_at: update_started_at,
757                            after_frame_callbacks,
758                            after_ui_drain,
759                            after_reconcile: after_ui_drain,
760                            after_process_frame,
761                            should_render,
762                            reconcile_attempted,
763                            reconcile_changed,
764                        });
765                        self.is_dirty = false;
766                        return result;
767                    };
768                    reconcile_attempted = true;
769                    match self.composition.reconcile(root_key, &mut *self.content) {
770                        Ok(changed) => {
771                            reconcile_changed = changed;
772                            log::trace!(
773                                target: "cranpose::input",
774                                "reconcile changed={changed}"
775                            );
776                            if changed {
777                                self.fps_monitor.record_recomposition();
778                                if self.composition_tree_needs_layout() {
779                                    self.request_layout_pass();
780                                }
781                                request_render_invalidation();
782                            }
783                        }
784                        Err(NodeError::Missing { id }) => {
785                            log::debug!("Recomposition skipped: node {} no longer exists", id);
786                            self.request_layout_pass();
787                            request_render_invalidation();
788                        }
789                        Err(err) => {
790                            log::error!("recomposition failed: {err}");
791                            self.request_layout_pass();
792                            request_render_invalidation();
793                        }
794                    }
795                }
796                let after_reconcile = Instant::now();
797                let result = self.process_frame_in_context(reconcile_changed);
798                let after_process_frame = Instant::now();
799                log_update_stage_telemetry(UpdateStageTelemetry {
800                    started_at: update_started_at,
801                    after_frame_callbacks,
802                    after_ui_drain,
803                    after_reconcile,
804                    after_process_frame,
805                    should_render,
806                    reconcile_attempted,
807                    reconcile_changed,
808                });
809                self.is_dirty = false;
810                result
811            })
812        })
813    }
814
815    pub fn update(&mut self) -> FrameUpdateResult {
816        let frame_time = self.frame_time_nanos_at(Instant::now());
817        self.update_at_frame_time_nanos(frame_time)
818    }
819}
820
821impl<R> Drop for AppShell<R>
822where
823    R: Renderer,
824{
825    fn drop(&mut self) {
826        self.runtime.clear_frame_waker();
827    }
828}
829
830pub fn default_root_key() -> Key {
831    location_key(file!(), line!(), column!())
832}
833
834#[cfg(test)]
835mod frame_pacing_tests {
836    use super::{FramePacingMode, FrameSchedule, FrameScheduler, PlatformFrameDriver};
837    use std::cell::RefCell;
838    use std::panic::{catch_unwind, AssertUnwindSafe};
839    use std::time::Duration;
840    use web_time::Instant;
841
842    #[derive(Clone, Copy, Debug, PartialEq)]
843    enum DriverCall {
844        RequestFrame,
845        RequestWakeAt(Instant),
846        ClearWake,
847    }
848
849    #[derive(Default)]
850    struct RecordingFrameDriver {
851        calls: RefCell<Vec<DriverCall>>,
852    }
853
854    impl RecordingFrameDriver {
855        fn calls(&self) -> Vec<DriverCall> {
856            self.calls.borrow().clone()
857        }
858    }
859
860    impl PlatformFrameDriver for RecordingFrameDriver {
861        fn request_frame(&self) {
862            self.calls.borrow_mut().push(DriverCall::RequestFrame);
863        }
864
865        fn request_wake_at(&self, deadline: Instant) {
866            self.calls
867                .borrow_mut()
868                .push(DriverCall::RequestWakeAt(deadline));
869        }
870
871        fn clear_wake(&self) {
872            self.calls.borrow_mut().push(DriverCall::ClearWake);
873        }
874    }
875
876    #[test]
877    fn frame_pacing_labels_match_overlay_modes() {
878        assert_eq!(FramePacingMode::Vsync.label(), "VSync");
879        assert_eq!(FramePacingMode::Hard60.label(), "60fps");
880        assert_eq!(FramePacingMode::Hard120.label(), "120fps");
881        assert_eq!(FramePacingMode::NoVsync.label(), "NoVSync");
882    }
883
884    #[test]
885    fn only_hard_modes_have_fixed_targets() {
886        assert_eq!(FramePacingMode::Vsync.target_fps(), None);
887        assert_eq!(FramePacingMode::Hard60.target_fps(), Some(60));
888        assert_eq!(FramePacingMode::Hard120.target_fps(), Some(120));
889        assert_eq!(FramePacingMode::NoVsync.target_fps(), None);
890    }
891
892    #[test]
893    fn frame_schedule_requests_immediate_frame_and_clears_deadline() {
894        let driver = RecordingFrameDriver::default();
895        let deadline = Instant::now() + Duration::from_millis(25);
896
897        FrameSchedule {
898            needs_update: true,
899            needs_frame: true,
900            next_deadline: Some(deadline),
901        }
902        .apply_to(&driver);
903
904        assert_eq!(
905            driver.calls(),
906            vec![DriverCall::ClearWake, DriverCall::RequestFrame]
907        );
908    }
909
910    #[test]
911    fn frame_schedule_requests_deadline_when_idle_until_timer() {
912        let driver = RecordingFrameDriver::default();
913        let deadline = Instant::now() + Duration::from_millis(25);
914
915        FrameSchedule {
916            needs_update: false,
917            needs_frame: false,
918            next_deadline: Some(deadline),
919        }
920        .apply_to(&driver);
921
922        assert_eq!(driver.calls(), vec![DriverCall::RequestWakeAt(deadline)]);
923    }
924
925    #[test]
926    fn frame_schedule_wakes_without_requesting_frame_for_update_only_work() {
927        let driver = RecordingFrameDriver::default();
928        let before = Instant::now();
929
930        FrameSchedule {
931            needs_update: true,
932            needs_frame: false,
933            next_deadline: None,
934        }
935        .apply_to(&driver);
936
937        let calls = driver.calls();
938        assert_eq!(calls.len(), 1);
939        match calls[0] {
940            DriverCall::RequestWakeAt(deadline) => {
941                assert!(deadline >= before);
942            }
943            other => panic!("update-only work must wake without requesting a frame: {other:?}"),
944        }
945    }
946
947    #[test]
948    fn frame_schedule_clears_wake_when_fully_idle() {
949        let driver = RecordingFrameDriver::default();
950
951        FrameSchedule {
952            needs_update: false,
953            needs_frame: false,
954            next_deadline: None,
955        }
956        .apply_to(&driver);
957
958        assert_eq!(driver.calls(), vec![DriverCall::ClearWake]);
959    }
960
961    #[test]
962    fn frame_scheduler_records_latest_schedule_and_applies_driver() {
963        let scheduler = FrameScheduler::default();
964        let driver = RecordingFrameDriver::default();
965        let deadline = Instant::now() + Duration::from_millis(25);
966
967        scheduler.schedule(
968            FrameSchedule {
969                needs_update: false,
970                needs_frame: false,
971                next_deadline: Some(deadline),
972            },
973            &driver,
974        );
975
976        assert_eq!(
977            scheduler.snapshot(),
978            FrameSchedule {
979                needs_update: false,
980                needs_frame: false,
981                next_deadline: Some(deadline),
982            }
983        );
984        assert_eq!(driver.calls(), vec![DriverCall::RequestWakeAt(deadline)]);
985    }
986
987    #[test]
988    fn frame_scheduler_clears_deadline_for_immediate_frame() {
989        let scheduler = FrameScheduler::default();
990        let driver = RecordingFrameDriver::default();
991        let deadline = Instant::now() + Duration::from_millis(25);
992
993        scheduler.schedule(
994            FrameSchedule {
995                needs_update: true,
996                needs_frame: true,
997                next_deadline: Some(deadline),
998            },
999            &driver,
1000        );
1001
1002        assert_eq!(
1003            scheduler.snapshot(),
1004            FrameSchedule {
1005                needs_update: true,
1006                needs_frame: true,
1007                next_deadline: None,
1008            }
1009        );
1010        assert_eq!(
1011            driver.calls(),
1012            vec![DriverCall::ClearWake, DriverCall::RequestFrame]
1013        );
1014    }
1015
1016    #[test]
1017    fn frame_scheduler_recovers_poisoned_deadline_lock() {
1018        let scheduler = FrameScheduler::default();
1019        let deadline = Instant::now() + Duration::from_millis(25);
1020
1021        let _ = catch_unwind(AssertUnwindSafe(|| {
1022            let _guard = scheduler.lock_deadline();
1023            panic!("poison frame scheduler deadline lock");
1024        }));
1025
1026        scheduler.record(FrameSchedule {
1027            needs_update: false,
1028            needs_frame: false,
1029            next_deadline: Some(deadline),
1030        });
1031
1032        assert_eq!(
1033            scheduler.snapshot(),
1034            FrameSchedule {
1035                needs_update: false,
1036                needs_frame: false,
1037                next_deadline: Some(deadline),
1038            }
1039        );
1040    }
1041}
1042
1043#[cfg(test)]
1044#[path = "tests/app_shell_tests.rs"]
1045mod tests;