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    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    /// The invalidations that mean the pixels on screen are stale.
742    ///
743    /// Every one of these ends in a scene rebuild, so every one of them is a
744    /// reason to put a new frame on the display. Deliberately *excludes*
745    /// [`Composition::should_render`]: an armed frame callback means the
746    /// composition owes the app a tick, which is not the same as owing the
747    /// display a frame, and conflating the two is what made
748    /// [`Self::needs_redraw`] indistinguishable from [`Self::needs_update`].
749    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        // Stale pixels, a queued UI continuation (which wakes an update but
766        // must never schedule a frame - see `needs_redraw`), or a
767        // composition that wants to render.
768        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    /// Returns true when the runtime holds work for the UI thread: posted tasks,
779    /// continuations from worker threads, or async tasks ready to poll.
780    ///
781    /// This is the part of [`needs_update`](Self::needs_update) that another
782    /// thread is waiting on, told apart from the part that only wants the screen
783    /// redrawn. A platform backend running with no surface uses it to compose
784    /// for work and stay asleep for animation.
785    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    /// Returns true if the shell owes the display a frame: stale pixels, or a
791    /// renderer that has not warmed its swapchain yet.
792    ///
793    /// An app that merely holds an open `next_frame()` await - a game loop, a
794    /// polling effect - keeps [`Self::needs_update`] true forever without
795    /// changing a single pixel. Such an app must still be *ticked* every frame,
796    /// but the frame it produces is byte-identical to the last one, and
797    /// presenting it costs a full swapchain rotation and pins the panel at its
798    /// maximum refresh rate. Callers pair this with
799    /// [`FrameUpdateResult::visual_changed`] from the update they just ran,
800    /// which reports the work that update actually did.
801    /// Note: Cursor blink is now timer-based and uses WaitUntil scheduling, not continuous redraw.
802    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    /// Marks the shell as dirty, indicating a redraw is needed.
809    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    #[cfg(any(test, feature = "test-support"))]
835    #[doc(hidden)]
836    pub fn debug_current_density(&self) -> f32 {
837        let app_context = Rc::clone(&self.app_context);
838        app_context.enter(cranpose_ui::current_density)
839    }
840
841    #[cfg(any(test, feature = "test-support"))]
842    #[doc(hidden)]
843    pub fn debug_enter_app_context<T>(&self, block: impl FnOnce() -> T) -> T {
844        let app_context = Rc::clone(&self.app_context);
845        app_context.enter(block)
846    }
847
848    fn request_layout_pass(&mut self) {
849        self.layout_requested = true;
850    }
851
852    fn request_forced_layout_pass(&mut self) {
853        self.layout_requested = true;
854        self.force_layout_pass = true;
855    }
856
857    fn composition_tree_needs_layout(&mut self) -> bool {
858        let Some(root) = self.composition.root() else {
859            return true;
860        };
861        let mut applier = self.composition.applier_mut();
862        cranpose_ui::tree_needs_layout(&mut *applier, root).unwrap_or_else(|err| {
863            log::warn!(
864                "Cannot check layout dirty status for root #{}: {}",
865                root,
866                err
867            );
868            true
869        })
870    }
871
872    /// Returns true if there are active animations or pending recompositions.
873    pub fn has_active_animations(&self) -> bool {
874        self.composition.should_render()
875    }
876
877    pub fn has_active_pointer_gesture(&self) -> bool {
878        self.buttons_pressed != PointerButtons::NONE
879            && self.hit_path_tracker.has_path(PointerId::PRIMARY)
880    }
881
882    /// Returns the next scheduled event time for cursor blink.
883    /// Use this for `ControlFlow::WaitUntil` scheduling.
884    pub fn next_event_time(&self) -> Option<web_time::Instant> {
885        let app_context = Rc::clone(&self.app_context);
886        app_context.enter(cranpose_ui::next_cursor_blink_time)
887    }
888
889    fn compute_frame_schedule(&self) -> FrameSchedule {
890        let needs_update = self.needs_update();
891        let needs_frame = self.is_dirty
892            || self.should_render()
893            || self.has_active_pointer_gesture()
894            || self.renderer.needs_frame_warmup();
895        FrameSchedule {
896            needs_update,
897            needs_frame,
898            next_deadline: self.next_event_time(),
899        }
900    }
901
902    pub fn frame_schedule(&self) -> FrameSchedule {
903        let schedule = self.compute_frame_schedule();
904        self.frame_scheduler.record(schedule);
905        schedule
906    }
907
908    pub fn schedule_platform_frame<D>(&self, driver: &D) -> FrameSchedule
909    where
910        D: PlatformFrameDriver + ?Sized,
911    {
912        let schedule = self.compute_frame_schedule();
913        self.frame_scheduler.schedule(schedule, driver);
914        schedule
915    }
916
917    pub fn frame_scheduler_snapshot(&self) -> FrameSchedule {
918        self.frame_scheduler.snapshot()
919    }
920
921    fn frame_time_nanos_at(&self, now: Instant) -> u64 {
922        now.checked_duration_since(self.start_time)
923            .unwrap_or_default()
924            .as_nanos()
925            .min(u128::from(u64::MAX)) as u64
926    }
927
928    /// Timestamp a live input sample against the current animation clock.
929    pub fn realtime_pointer_event_time(&self, platform_time_ms: Option<i64>) -> PointerEventTime {
930        PointerEventTime {
931            platform_time_ms,
932            animation_time_nanos: self
933                .frame_time_nanos_at(Instant::now())
934                .max(self.last_frame_time_nanos),
935        }
936    }
937
938    /// Timestamp deterministic input at the most recently processed frame.
939    pub fn exact_pointer_event_time(&self, platform_time_ms: Option<i64>) -> PointerEventTime {
940        PointerEventTime {
941            platform_time_ms,
942            animation_time_nanos: self.last_frame_time_nanos,
943        }
944    }
945
946    pub fn update_after_frame_interval(
947        &mut self,
948        frame_interval: std::time::Duration,
949    ) -> FrameUpdateResult {
950        let wall_frame_time = self.frame_time_nanos_at(Instant::now());
951        let base_frame_time = self.last_frame_time_nanos.max(wall_frame_time);
952        let frame_time = base_frame_time
953            .saturating_add(frame_interval.as_nanos().min(u128::from(u64::MAX)) as u64);
954        self.update_at_frame_time_nanos(frame_time)
955    }
956
957    /// Advance the frame clock by EXACTLY `frame_interval` past the last
958    /// frame — no wall anchoring — and run one update there. Robot keyframe
959    /// captures ride this to sample animations deterministically: while the
960    /// advanced clock is ahead of wall time, interleaved wall-clocked
961    /// updates clamp to it (dt 0) instead of fast-forwarding animations.
962    pub fn update_after_exact_interval(
963        &mut self,
964        frame_interval: std::time::Duration,
965    ) -> FrameUpdateResult {
966        let frame_time = self
967            .last_frame_time_nanos
968            .saturating_add(frame_interval.as_nanos().min(u128::from(u64::MAX)) as u64);
969        self.update_at_frame_time_nanos(frame_time)
970    }
971
972    pub fn update_at_frame_time_nanos(&mut self, frame_time: u64) -> FrameUpdateResult {
973        let app_context = Rc::clone(&self.app_context);
974        app_context.enter(|| {
975            let update_started_at = Instant::now();
976            let frame_time = frame_time.max(self.last_frame_time_nanos);
977            self.last_frame_time_nanos = frame_time;
978            let runtime_handle = self.runtime.runtime_handle();
979            runtime_handle.with_deferred_state_releases(|| {
980                self.runtime.drain_frame_callbacks(frame_time);
981                let after_frame_callbacks = Instant::now();
982                runtime_handle.drain_ui();
983                let after_ui_drain = Instant::now();
984                let should_render = self.composition.should_recompose();
985                let mut reconcile_attempted = false;
986                let mut reconcile_changed = false;
987                if should_render {
988                    log::trace!(
989                        target: "cranpose::input",
990                        "update begin: should_render=true layout_requested={} scene_dirty={} is_dirty={}",
991                        self.layout_requested,
992                        self.scene_dirty,
993                        self.is_dirty
994                    );
995                }
996                if should_render {
997                    let Some(root_key) = self.composition.root_key() else {
998                        let result = self.process_frame_in_context(reconcile_changed);
999                        let after_process_frame = Instant::now();
1000                        log_update_stage_telemetry(UpdateStageTelemetry {
1001                            started_at: update_started_at,
1002                            after_frame_callbacks,
1003                            after_ui_drain,
1004                            after_reconcile: after_ui_drain,
1005                            after_process_frame,
1006                            should_render,
1007                            reconcile_attempted,
1008                            reconcile_changed,
1009                        });
1010                        self.is_dirty = false;
1011                        return result;
1012                    };
1013                    reconcile_attempted = true;
1014                    match self.composition.reconcile(root_key, &mut *self.content) {
1015                        Ok(changed) => {
1016                            reconcile_changed = changed;
1017                            log::trace!(
1018                                target: "cranpose::input",
1019                                "reconcile changed={changed}"
1020                            );
1021                            if changed {
1022                                self.fps_monitor.record_recomposition();
1023                                if self.composition_tree_needs_layout() {
1024                                    self.request_layout_pass();
1025                                }
1026                                request_render_invalidation();
1027                            }
1028                        }
1029                        Err(NodeError::Missing { id }) => {
1030                            log::debug!("Recomposition skipped: node {} no longer exists", id);
1031                            self.request_layout_pass();
1032                            request_render_invalidation();
1033                        }
1034                        Err(err) => {
1035                            log::error!("recomposition failed: {err}");
1036                            self.request_layout_pass();
1037                            request_render_invalidation();
1038                        }
1039                    }
1040                }
1041                let after_reconcile = Instant::now();
1042                let result = self.process_frame_in_context(reconcile_changed);
1043                let after_process_frame = Instant::now();
1044                log_update_stage_telemetry(UpdateStageTelemetry {
1045                    started_at: update_started_at,
1046                    after_frame_callbacks,
1047                    after_ui_drain,
1048                    after_reconcile,
1049                    after_process_frame,
1050                    should_render,
1051                    reconcile_attempted,
1052                    reconcile_changed,
1053                });
1054                self.is_dirty = false;
1055                result
1056            })
1057        })
1058    }
1059
1060    pub fn update(&mut self) -> FrameUpdateResult {
1061        let frame_time = self.frame_time_nanos_at(Instant::now());
1062        self.update_at_frame_time_nanos(frame_time)
1063    }
1064}
1065
1066impl<R> Drop for AppShell<R>
1067where
1068    R: Renderer,
1069{
1070    fn drop(&mut self) {
1071        self.runtime.clear_frame_waker();
1072    }
1073}
1074
1075pub fn default_root_key() -> Key {
1076    location_key(file!(), line!(), column!())
1077}
1078
1079#[cfg(test)]
1080mod frame_pacing_tests {
1081    use super::{FramePacingMode, FrameSchedule, FrameScheduler, PlatformFrameDriver};
1082    use std::cell::RefCell;
1083    use std::panic::{catch_unwind, AssertUnwindSafe};
1084    use std::time::Duration;
1085    use web_time::Instant;
1086
1087    #[derive(Clone, Copy, Debug, PartialEq)]
1088    enum DriverCall {
1089        RequestFrame,
1090        RequestWakeAt(Instant),
1091        ClearWake,
1092    }
1093
1094    #[derive(Default)]
1095    struct RecordingFrameDriver {
1096        calls: RefCell<Vec<DriverCall>>,
1097    }
1098
1099    impl RecordingFrameDriver {
1100        fn calls(&self) -> Vec<DriverCall> {
1101            self.calls.borrow().clone()
1102        }
1103    }
1104
1105    impl PlatformFrameDriver for RecordingFrameDriver {
1106        fn request_frame(&self) {
1107            self.calls.borrow_mut().push(DriverCall::RequestFrame);
1108        }
1109
1110        fn request_wake_at(&self, deadline: Instant) {
1111            self.calls
1112                .borrow_mut()
1113                .push(DriverCall::RequestWakeAt(deadline));
1114        }
1115
1116        fn clear_wake(&self) {
1117            self.calls.borrow_mut().push(DriverCall::ClearWake);
1118        }
1119    }
1120
1121    #[test]
1122    fn frame_pacing_labels_match_overlay_modes() {
1123        assert_eq!(FramePacingMode::Vsync.label(), "VSync");
1124        assert_eq!(FramePacingMode::Hard60.label(), "60fps");
1125        assert_eq!(FramePacingMode::Hard120.label(), "120fps");
1126        assert_eq!(FramePacingMode::NoVsync.label(), "NoVSync");
1127    }
1128
1129    #[test]
1130    fn only_hard_modes_have_fixed_targets() {
1131        assert_eq!(FramePacingMode::Vsync.target_fps(), None);
1132        assert_eq!(FramePacingMode::Hard60.target_fps(), Some(60));
1133        assert_eq!(FramePacingMode::Hard120.target_fps(), Some(120));
1134        assert_eq!(FramePacingMode::NoVsync.target_fps(), None);
1135    }
1136
1137    #[test]
1138    fn frame_schedule_requests_immediate_frame_and_clears_deadline() {
1139        let driver = RecordingFrameDriver::default();
1140        let deadline = Instant::now() + Duration::from_millis(25);
1141
1142        FrameSchedule {
1143            needs_update: true,
1144            needs_frame: true,
1145            next_deadline: Some(deadline),
1146        }
1147        .apply_to(&driver);
1148
1149        assert_eq!(
1150            driver.calls(),
1151            vec![DriverCall::ClearWake, DriverCall::RequestFrame]
1152        );
1153    }
1154
1155    #[test]
1156    fn frame_schedule_requests_deadline_when_idle_until_timer() {
1157        let driver = RecordingFrameDriver::default();
1158        let deadline = Instant::now() + Duration::from_millis(25);
1159
1160        FrameSchedule {
1161            needs_update: false,
1162            needs_frame: false,
1163            next_deadline: Some(deadline),
1164        }
1165        .apply_to(&driver);
1166
1167        assert_eq!(driver.calls(), vec![DriverCall::RequestWakeAt(deadline)]);
1168    }
1169
1170    #[test]
1171    fn frame_schedule_wakes_without_requesting_frame_for_update_only_work() {
1172        let driver = RecordingFrameDriver::default();
1173        let before = Instant::now();
1174
1175        FrameSchedule {
1176            needs_update: true,
1177            needs_frame: false,
1178            next_deadline: None,
1179        }
1180        .apply_to(&driver);
1181
1182        let calls = driver.calls();
1183        assert_eq!(calls.len(), 1);
1184        match calls[0] {
1185            DriverCall::RequestWakeAt(deadline) => {
1186                assert!(deadline >= before);
1187            }
1188            other => panic!("update-only work must wake without requesting a frame: {other:?}"),
1189        }
1190    }
1191
1192    #[test]
1193    fn frame_schedule_clears_wake_when_fully_idle() {
1194        let driver = RecordingFrameDriver::default();
1195
1196        FrameSchedule {
1197            needs_update: false,
1198            needs_frame: false,
1199            next_deadline: None,
1200        }
1201        .apply_to(&driver);
1202
1203        assert_eq!(driver.calls(), vec![DriverCall::ClearWake]);
1204    }
1205
1206    #[test]
1207    fn frame_scheduler_records_latest_schedule_and_applies_driver() {
1208        let scheduler = FrameScheduler::default();
1209        let driver = RecordingFrameDriver::default();
1210        let deadline = Instant::now() + Duration::from_millis(25);
1211
1212        scheduler.schedule(
1213            FrameSchedule {
1214                needs_update: false,
1215                needs_frame: false,
1216                next_deadline: Some(deadline),
1217            },
1218            &driver,
1219        );
1220
1221        assert_eq!(
1222            scheduler.snapshot(),
1223            FrameSchedule {
1224                needs_update: false,
1225                needs_frame: false,
1226                next_deadline: Some(deadline),
1227            }
1228        );
1229        assert_eq!(driver.calls(), vec![DriverCall::RequestWakeAt(deadline)]);
1230    }
1231
1232    #[test]
1233    fn frame_scheduler_clears_deadline_for_immediate_frame() {
1234        let scheduler = FrameScheduler::default();
1235        let driver = RecordingFrameDriver::default();
1236        let deadline = Instant::now() + Duration::from_millis(25);
1237
1238        scheduler.schedule(
1239            FrameSchedule {
1240                needs_update: true,
1241                needs_frame: true,
1242                next_deadline: Some(deadline),
1243            },
1244            &driver,
1245        );
1246
1247        assert_eq!(
1248            scheduler.snapshot(),
1249            FrameSchedule {
1250                needs_update: true,
1251                needs_frame: true,
1252                next_deadline: None,
1253            }
1254        );
1255        assert_eq!(
1256            driver.calls(),
1257            vec![DriverCall::ClearWake, DriverCall::RequestFrame]
1258        );
1259    }
1260
1261    #[test]
1262    fn frame_scheduler_recovers_poisoned_deadline_lock() {
1263        let scheduler = FrameScheduler::default();
1264        let deadline = Instant::now() + Duration::from_millis(25);
1265
1266        let _ = catch_unwind(AssertUnwindSafe(|| {
1267            let _guard = scheduler.lock_deadline();
1268            panic!("poison frame scheduler deadline lock");
1269        }));
1270
1271        scheduler.record(FrameSchedule {
1272            needs_update: false,
1273            needs_frame: false,
1274            next_deadline: Some(deadline),
1275        });
1276
1277        assert_eq!(
1278            scheduler.snapshot(),
1279            FrameSchedule {
1280                needs_update: false,
1281                needs_frame: false,
1282                next_deadline: Some(deadline),
1283            }
1284        );
1285    }
1286}
1287
1288#[cfg(test)]
1289#[path = "tests/app_shell_tests.rs"]
1290mod tests;