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 pointer device source so platform backends can stamp it.
47pub use cranpose_foundation::PointerSource;
48// Re-export the rotary (Wear OS crown / rotating bezel) event so platform
49// backends can build one and apps can type their window-level handler.
50pub use cranpose_foundation::{
51    rotary_scroll_pixels_from_detents, RotaryScrollEvent, DEFAULT_ROTARY_SCROLL_FACTOR_DP,
52};
53
54/// Bridges the in-tree selection menu's clipboard actions to the desktop OS
55/// clipboard (`arboard`). Holds a persistent clipboard handle (Linux X11 loses
56/// clipboard contents when the last owning handle drops), shared behind an
57/// `Rc<RefCell<..>>` so it stays alive for the app-context's lifetime.
58#[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}
88// Re-export the platform soft-keyboard hook so runtimes only depend on the shell
89pub use cranpose_ui::PlatformTextInputHandler;
90// Re-export the IME editable-state snapshot for platform text-input bridges
91pub 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/// How the platform should vote the display's frame rate on behalf of the app.
108///
109/// Compose apps get 120 Hz gameplay on a 120 Hz panel not by presenting faster
110/// but because HWUI votes a rate on the window while animations and gestures
111/// run, and clears it when they stop. A window that never votes is pinned by
112/// SurfaceFlinger's cadence inference instead — which also throttles the app's
113/// choreographer, so the inference reinforces itself. `Auto` reproduces the
114/// HWUI behaviour; the platform backends read it every frame and vote through
115/// the native window when the desired rate changes.
116#[derive(Debug, Clone, Copy, PartialEq, Default)]
117pub enum FrameRatePreference {
118    /// Ask for the panel's fastest rate while frames are being produced, no
119    /// preference when the scene is still. This is the default, matching what
120    /// Compose/HWUI do for every app without the app's involvement.
121    #[default]
122    Auto,
123    /// Never vote; the OS infers a rate from presentation cadence.
124    NoPreference,
125    /// Always vote exactly this rate in Hz. Values `<= 0` behave like
126    /// [`FrameRatePreference::NoPreference`].
127    Exact(f32),
128}
129
130impl FrameRatePreference {
131    /// The baseline `Auto` votes while animating without interaction — the
132    /// same rate HWUI's NORMAL frame-rate category resolves to on phone
133    /// panels. The quiet vote cannot simply be "no vote": SurfaceFlinger
134    /// infers a non-voting window's rate from whatever cadence it last
135    /// observed and pins it, so an app that ever ran the panel's fast rate
136    /// would stay there forever (measured on a Pixel 9 Pro, both directions).
137    pub const AUTO_QUIET_RATE_HZ: f32 = 60.0;
138
139    /// The rate the platform should vote right now, in Hz, where `0.0` means
140    /// "clear the vote". `producing_frames` is whether the frame loop has a
141    /// frame scheduled, `interacting` whether input arrived within the
142    /// platform's boost hold-off, and `panel_max_hz` the display's fastest
143    /// supported rate when the platform knows it.
144    ///
145    /// While interacting, `Auto` holds the boost even through moments with no
146    /// frame scheduled: a gesture sequence crosses still screens (a tap lands,
147    /// the old scene stops animating, the new one hasn't started), and letting
148    /// each of those instantly clear the vote flapped the display between the
149    /// boost rate and no-vote several times per second on device. This mirrors
150    /// SurfaceFlinger's own touch boost, which also outlives the touch by
151    /// seconds regardless of what the app presents in between.
152    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    /// Monotonic counter that moves whenever the cached layout/semantics
195    /// snapshots are invalidated or semantics tracking is toggled. Accessibility
196    /// bridges compare it against the revision they last projected so a frame
197    /// that changed nothing semantic costs them one integer compare instead of
198    /// a full tree walk. See [`AppShell::semantics_snapshot_revision`].
199    semantics_snapshot_revision: u64,
200    /// The app's display frame-rate preference, applied by platform backends
201    /// that own a native window. See [`FrameRatePreference`].
202    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    /// Tracks which mouse buttons are currently pressed
209    buttons_pressed: PointerButtons,
210    /// Device source (touch/mouse/stylus) of the most recent pointer sample,
211    /// set by the platform before dispatching and stamped onto every
212    /// `PointerEvent` the shell constructs. The pointer model is stateful
213    /// (`set_cursor` then `pointer_pressed`), so a single per-shell cell mirrors
214    /// the existing cursor/buttons state without churning every method signature.
215    pointer_source: PointerSource,
216    /// Tracks which nodes were hit on PointerDown (by stable NodeId).
217    ///
218    /// This follows Jetpack Compose's HitPathTracker pattern:
219    /// - On Down: cache NodeIds, not geometry
220    /// - On Move/Up/Cancel: resolve fresh HitTargets from current scene
221    /// - Handler closures are preserved (same Rc), so internal state survives
222    hit_path_tracker: HitPathTracker,
223    /// Tracks which nodes the pointer is currently hovering over.
224    /// Used to synthesize Enter/Exit events when the hover set changes.
225    hovered_nodes: Vec<NodeId>,
226    /// Window-level rotary (crown/bezel) fallback handler.
227    ///
228    /// Invoked only when no modifier in the routed chain consumed the event, so
229    /// an app that draws everything into one canvas can read raw rotary deltas
230    /// without participating in focus. See
231    /// [`AppShell::set_on_rotary_scroll`](AppShell::set_on_rotary_scroll).
232    on_rotary_scroll: Option<Rc<dyn Fn(RotaryScrollEvent) -> bool>>,
233    /// Pixels per rotary detent used when a platform reports the crown delta in
234    /// detents. Defaults to `DEFAULT_ROTARY_SCROLL_FACTOR_DP * density`.
235    rotary_scroll_factor: f32,
236    /// Persistent clipboard for desktop (Linux X11 requires clipboard to stay alive)
237    #[cfg(all(feature = "clipboard-native", target_os = "linux"))]
238    clipboard: Option<arboard::Clipboard>,
239    /// Dev options for debugging and performance monitoring
240    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)]
250/// Platform and animation-clock timestamps for one pointer sample.
251pub struct PointerEventTime {
252    /// Timestamp supplied by the platform, in its millisecond clock domain.
253    pub platform_time_ms: Option<i64>,
254    /// Timestamp in the animation frame-clock domain.
255    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    /// Pace frames to the display refresh interval. The production default:
324    /// animations advance once per vsync instead of re-rendering uncapped.
325    #[default]
326    Vsync,
327    Hard60,
328    Hard120,
329    /// Render as fast as possible. For perf harnesses and robot drivers that
330    /// measure work throughput; saturates the GPU if used in a real app.
331    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/// Development options for debugging and performance monitoring.
453///
454/// These are rendered directly by the renderer (not via composition)
455/// to avoid affecting performance measurements.
456#[derive(Clone, Debug, Default)]
457pub struct DevOptions {
458    /// Show FPS counter overlay
459    pub fps_counter: bool,
460    /// Show recomposition count
461    pub recomposition_counter: bool,
462    /// Show layout timing breakdown
463    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        // Install the top-level overlay layer once, at the root, so every app
517        // gets `Popup`/selection-handle/context-menu support for free and the
518        // overlay is composed (and thus painted and hit-tested) last. The app's
519        // content is called through a shared handle so this wrapper can be
520        // re-created cheaply on every recomposition without moving `content`.
521        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            // Route the selection menu's Copy/Cut/Paste through the OS clipboard
531            // on desktop; other platforms fall back to the in-process clipboard.
532            #[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    /// The shell's [`AppContext`](cranpose_ui::AppContext). Platform backends
592    /// use it to register per-context services (such as the OS clipboard) that
593    /// need UIKit/JNI access the shell itself does not have: enter the context
594    /// and call the relevant `set_platform_*` installer.
595    pub fn app_context(&self) -> &Rc<cranpose_ui::AppContext> {
596        &self.app_context
597    }
598
599    /// Set development options for debugging and performance monitoring.
600    ///
601    /// The FPS counter and other overlays are rendered directly by the renderer
602    /// (not via composition) to avoid affecting performance measurements.
603    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    /// Get a reference to the current dev options.
612    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    /// Where the dev overlay draws the control for `mode`, in logical pixels.
666    ///
667    /// The overlay is drawn by the renderer rather than composed, so it has no
668    /// semantics for a test to search. Without this a test that wants to press
669    /// a pacing control has to hard-code a coordinate and silently starts
670    /// passing against empty space the moment the overlay's text changes.
671    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    /// Take a press on a dev-overlay pacing control, if it lands on one.
684    ///
685    /// Every pointer press runs through here before the composition sees it, so
686    /// the controls answer to whatever produced the press: a mouse, a finger,
687    /// or a robot injecting one. A platform shell that hit-tested the overlay
688    /// itself would only make the controls work for the one input path it owns
689    /// -- which is how they came to do nothing under a robot at all.
690    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    /// The invalidations that mean the pixels on screen are stale.
770    ///
771    /// Every one of these ends in a scene rebuild, so every one of them is a
772    /// reason to put a new frame on the display. Deliberately *excludes*
773    /// [`Composition::should_render`]: an armed frame callback means the
774    /// composition owes the app a tick, which is not the same as owing the
775    /// display a frame, and conflating the two is what made
776    /// [`Self::needs_redraw`] indistinguishable from [`Self::needs_update`].
777    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        // Stale pixels, a queued UI continuation (which wakes an update but
794        // must never schedule a frame - see `needs_redraw`), or a
795        // composition that wants to render.
796        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    /// Returns true when the runtime holds work for the UI thread: posted tasks,
807    /// continuations from worker threads, or async tasks ready to poll.
808    ///
809    /// This is the part of [`needs_update`](Self::needs_update) that another
810    /// thread is waiting on, told apart from the part that only wants the screen
811    /// redrawn. A platform backend running with no surface uses it to compose
812    /// for work and stay asleep for animation.
813    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    /// Returns true if the shell owes the display a frame: stale pixels, or a
819    /// renderer that has not warmed its swapchain yet.
820    ///
821    /// An app that merely holds an open `next_frame()` await - a game loop, a
822    /// polling effect - keeps [`Self::needs_update`] true forever without
823    /// changing a single pixel. Such an app must still be *ticked* every frame,
824    /// but the frame it produces is byte-identical to the last one, and
825    /// presenting it costs a full swapchain rotation and pins the panel at its
826    /// maximum refresh rate. Callers pair this with
827    /// [`FrameUpdateResult::visual_changed`] from the update they just ran,
828    /// which reports the work that update actually did.
829    /// Note: Cursor blink is now timer-based and uses WaitUntil scheduling, not continuous redraw.
830    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    /// Marks the shell as dirty, indicating a redraw is needed.
837    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    /// Reports the system font scale the platform is showing text at.
863    ///
864    /// Hosts call this at startup and on every configuration change. Sizes in
865    /// `Sp` follow it, sizes in `Dp` do not, which is what lets an app grow its
866    /// text with the user's setting while its layout stays where it was.
867    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    /// Returns true if there are active animations or pending recompositions.
926    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    /// Returns the next scheduled event time for cursor blink.
936    /// Use this for `ControlFlow::WaitUntil` scheduling.
937    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    /// Timestamp a live input sample against the current animation clock.
982    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    /// Timestamp deterministic input at the most recently processed frame.
992    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    /// Advance the frame clock by EXACTLY `frame_interval` past the last
1011    /// frame — no wall anchoring — and run one update there. Robot keyframe
1012    /// captures ride this to sample animations deterministically: while the
1013    /// advanced clock is ahead of wall time, interleaved wall-clocked
1014    /// updates clamp to it (dt 0) instead of fast-forwarding animations.
1015    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;