Skip to main content

cranpose_app_shell/
lib.rs

1#![allow(clippy::type_complexity)]
2
3mod fps_monitor;
4mod hit_path_tracker;
5mod shell_debug;
6mod shell_frame;
7mod shell_input;
8mod wheel;
9use std::{
10    fmt::{Debug, Write},
11    rc::Rc,
12    sync::{
13        Mutex, MutexGuard,
14        atomic::{AtomicBool, Ordering},
15    },
16};
17
18use cranpose_core::{
19    Applier, Composition, Key, MemoryApplier, NodeError, NodeId, collections::map::HashSet,
20    enter_event_handler_scope, location_key, run_in_mutable_snapshot,
21};
22pub use cranpose_foundation::{
23    DEFAULT_ROTARY_SCROLL_FACTOR_DP, Modifiers, PointerSource, RotaryScrollEvent,
24    rotary_scroll_pixels_from_detents,
25};
26use cranpose_foundation::{PointerButton, PointerButtons, PointerEvent, PointerEventKind};
27use cranpose_render_common::{HitTestTarget, RenderScene, Renderer};
28use cranpose_runtime_std::StdRuntime;
29use cranpose_ui::{
30    HeadlessRenderer, LayoutBox, LayoutNode, LayoutTree, MeasureLayoutOptions, SemanticsTree,
31    SubcomposeLayoutNode, clear_transient_scroll_motion_contexts, format_layout_tree,
32    format_render_scene, format_screen_summary, has_pending_focus_invalidations,
33    has_pending_pointer_repasses, has_pending_semantics_invalidations, peek_focus_invalidation,
34    peek_layout_invalidation, peek_pointer_invalidation, peek_render_invalidation,
35    process_focus_invalidations, process_pointer_repasses, process_semantics_invalidations,
36    request_render_invalidation, take_draw_repass_nodes, take_focus_invalidation,
37    take_layout_invalidation, take_pointer_invalidation, take_render_invalidation,
38};
39pub use cranpose_ui::{KeyCode, KeyEvent, KeyEventType};
40use cranpose_ui_graphics::{Point, PointerIcon, Rect, Size};
41pub use fps_monitor::FpsStats;
42use hit_path_tracker::{HitPathTracker, PointerId};
43#[cfg(test)]
44use shell_frame::build_draw_refresh_scope;
45use web_time::Instant;
46pub use wheel::WheelScroll;
47
48#[cfg(all(
49    feature = "clipboard-native",
50    not(target_arch = "wasm32"),
51    not(target_os = "android"),
52    not(target_os = "ios")
53))]
54struct ShellClipboard {
55    inner: std::rc::Rc<std::cell::RefCell<Option<arboard::Clipboard>>>,
56}
57
58#[cfg(all(
59    feature = "clipboard-native",
60    not(target_arch = "wasm32"),
61    not(target_os = "android"),
62    not(target_os = "ios")
63))]
64impl cranpose_ui::clipboard_session::PlatformClipboard for ShellClipboard {
65    fn write_text(&self, text: &str) {
66        if let Some(clipboard) = self.inner.borrow_mut().as_mut() {
67            let _ = clipboard.set_text(text);
68        }
69    }
70
71    fn read_text(&self) -> Option<String> {
72        self.inner
73            .borrow_mut()
74            .as_mut()
75            .and_then(|clipboard| clipboard.get_text().ok())
76    }
77}
78#[cfg(any(test, feature = "test-support"))]
79use cranpose_core::{
80    CompositionPassDebugStats, SlotId,
81    runtime::{RuntimeDebugStats, StateArenaDebugStats},
82    snapshot_pinning::{SnapshotPinningDebugStats, debug_snapshot_pinning_stats},
83    snapshot_state_observer::SnapshotStateObserverDebugStats,
84    snapshot_v2::{SnapshotV2DebugStats, debug_snapshot_v2_stats},
85};
86#[cfg(any(test, feature = "test-support"))]
87use cranpose_core::{
88    MemoryApplierDebugStats, RecomposeScopeRegistryDebugStats, SlotTableDebugStats,
89    debug_recompose_scope_registry_stats,
90};
91pub use cranpose_ui::{ImeEditorState, PlatformTextInputHandler};
92#[cfg(any(test, feature = "test-support"))]
93pub mod accessibility_audit;
94#[cfg(any(test, feature = "test-support"))]
95pub mod placed_semantics;
96
97/// How the platform should vote the display's frame rate on behalf of the app.
98///
99/// Compose apps get 120 Hz gameplay on a 120 Hz panel not by presenting faster
100/// but because HWUI votes a rate on the window while animations and gestures
101/// run, and clears it when they stop. A window that never votes is pinned by
102/// SurfaceFlinger's cadence inference instead — which also throttles the app's
103/// choreographer, so the inference reinforces itself. `Auto` reproduces the
104/// HWUI behaviour; the platform backends read it every frame and vote through
105/// the native window when the desired rate changes.
106#[derive(Debug, Clone, Copy, PartialEq, Default)]
107pub enum FrameRatePreference {
108    /// Ask for the panel's fastest rate while frames are being produced, no
109    /// preference when the scene is still. This is the default, matching what
110    /// Compose/HWUI do for every app without the app's involvement.
111    #[default]
112    Auto,
113    /// Never vote; the OS infers a rate from presentation cadence.
114    NoPreference,
115    /// Always vote exactly this rate in Hz. Values `<= 0` behave like
116    /// [`FrameRatePreference::NoPreference`].
117    Exact(f32),
118}
119
120impl FrameRatePreference {
121    /// The baseline `Auto` votes while animating without interaction — the
122    /// same rate HWUI's NORMAL frame-rate category resolves to on phone
123    /// panels. The quiet vote cannot simply be "no vote": SurfaceFlinger
124    /// infers a non-voting window's rate from whatever cadence it last
125    /// observed and pins it, so an app that ever ran the panel's fast rate
126    /// would stay there forever (measured on a Pixel 9 Pro, both directions).
127    pub const AUTO_QUIET_RATE_HZ: f32 = 60.0;
128
129    /// The rate the platform should vote right now, in Hz, where `0.0` means
130    /// "clear the vote". `producing_frames` is whether the frame loop has a
131    /// frame scheduled, `interacting` whether input arrived within the
132    /// platform's boost hold-off, and `panel_max_hz` the display's fastest
133    /// supported rate when the platform knows it.
134    ///
135    /// While interacting, `Auto` holds the boost even through moments with no
136    /// frame scheduled: a gesture sequence crosses still screens (a tap lands,
137    /// the old scene stops animating, the new one hasn't started), and letting
138    /// each of those instantly clear the vote flapped the display between the
139    /// boost rate and no-vote several times per second on device. This mirrors
140    /// SurfaceFlinger's own touch boost, which also outlives the touch by
141    /// seconds regardless of what the app presents in between.
142    pub fn desired_rate_hz(
143        self,
144        producing_frames: bool,
145        interacting: bool,
146        panel_max_hz: Option<f32>,
147    ) -> f32 {
148        match self {
149            FrameRatePreference::Auto => {
150                if interacting {
151                    panel_max_hz
152                        .filter(|rate| *rate > 0.0)
153                        .unwrap_or(Self::AUTO_QUIET_RATE_HZ)
154                } else if producing_frames {
155                    Self::AUTO_QUIET_RATE_HZ
156                } else {
157                    0.0
158                }
159            }
160            FrameRatePreference::NoPreference => 0.0,
161            FrameRatePreference::Exact(rate) if rate > 0.0 => rate,
162            FrameRatePreference::Exact(_) => 0.0,
163        }
164    }
165}
166
167pub struct AppShell<R>
168where
169    R: Renderer,
170{
171    app_context: Rc<cranpose_ui::AppContext>,
172    runtime: StdRuntime,
173    composition: Composition<MemoryApplier>,
174    content: Box<dyn FnMut()>,
175    renderer: R,
176    cursor: (f32, f32),
177    viewport: (f32, f32),
178    buffer_size: (u32, u32),
179    start_time: Instant,
180    last_frame_time_nanos: u64,
181    layout_tree: Option<LayoutTree>,
182    semantics_tree: Option<SemanticsTree>,
183    semantics_enabled: bool,
184    semantics_snapshot_revision: u64,
185    frame_rate_preference: FrameRatePreference,
186    layout_requested: bool,
187    force_layout_pass: bool,
188    scene_dirty: bool,
189    scoped_layout_scene_nodes: Vec<NodeId>,
190    retained_visual_nodes: HashSet<NodeId>,
191    is_dirty: bool,
192    buttons_pressed: PointerButtons,
193    pointer_source: PointerSource,
194    modifiers: Option<Modifiers>,
195    hit_path_tracker: HitPathTracker,
196    hovered_nodes: Vec<NodeId>,
197    on_rotary_scroll: Option<Rc<dyn Fn(RotaryScrollEvent) -> bool>>,
198    rotary_scroll_factor: f32,
199    #[cfg(all(feature = "clipboard-native", target_os = "linux"))]
200    clipboard: Option<arboard::Clipboard>,
201    dev_options: DevOptions,
202    dev_overlay_controls: Vec<DevOverlayControl>,
203    dev_overlay_text: String,
204    dev_overlay_last_refresh: Option<Instant>,
205    dev_overlay_viewport: Option<Size>,
206    fps_monitor: fps_monitor::FpsMonitor,
207    frame_scheduler: FrameScheduler,
208}
209
210#[derive(Clone, Copy, Debug, PartialEq, Eq)]
211/// Platform and animation-clock timestamps for one pointer sample.
212pub struct PointerEventTime {
213    /// Timestamp supplied by the platform, in its millisecond clock domain.
214    pub platform_time_ms: Option<i64>,
215    /// Timestamp in the animation frame-clock domain.
216    pub animation_time_nanos: u64,
217}
218
219fn update_stage_telemetry_threshold_ms() -> Option<f64> {
220    static THRESHOLD_MS: std::sync::OnceLock<Option<f64>> = std::sync::OnceLock::new();
221    *THRESHOLD_MS.get_or_init(|| {
222        std::env::var("CRANPOSE_UPDATE_STAGE_TELEMETRY_MS")
223            .ok()
224            .and_then(|value| value.parse::<f64>().ok())
225            .filter(|value| value.is_finite() && *value >= 0.0)
226    })
227}
228
229#[derive(Clone, Copy, Debug)]
230struct UpdateStageTelemetry {
231    started_at: Instant,
232    after_frame_callbacks: Instant,
233    after_ui_drain: Instant,
234    after_reconcile: Instant,
235    after_process_frame: Instant,
236    should_render: bool,
237    reconcile_attempted: bool,
238    reconcile_changed: bool,
239}
240
241fn log_update_stage_telemetry(telemetry: UpdateStageTelemetry) {
242    let Some(threshold_ms) = update_stage_telemetry_threshold_ms() else {
243        return;
244    };
245    let total_ms = telemetry
246        .after_process_frame
247        .duration_since(telemetry.started_at)
248        .as_secs_f64()
249        * 1000.0;
250    if total_ms < threshold_ms {
251        return;
252    }
253
254    let frame_callbacks_ms = telemetry
255        .after_frame_callbacks
256        .duration_since(telemetry.started_at)
257        .as_secs_f64()
258        * 1000.0;
259    let ui_drain_ms = telemetry
260        .after_ui_drain
261        .duration_since(telemetry.after_frame_callbacks)
262        .as_secs_f64()
263        * 1000.0;
264    let reconcile_ms = telemetry
265        .after_reconcile
266        .duration_since(telemetry.after_ui_drain)
267        .as_secs_f64()
268        * 1000.0;
269    let process_frame_ms = telemetry
270        .after_process_frame
271        .duration_since(telemetry.after_reconcile)
272        .as_secs_f64()
273        * 1000.0;
274    eprintln!(
275        "[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={}",
276        telemetry.should_render, telemetry.reconcile_attempted, telemetry.reconcile_changed
277    );
278}
279
280#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
281pub enum FramePacingMode {
282    /// Pace frames to the display refresh interval. The production default:
283    /// animations advance once per vsync instead of re-rendering uncapped.
284    #[default]
285    Vsync,
286    Hard60,
287    Hard120,
288    /// Render as fast as possible. For perf harnesses and robot drivers that
289    /// measure work throughput; saturates the GPU if used in a real app.
290    NoVsync,
291}
292
293impl FramePacingMode {
294    pub const ALL: [Self; 4] = [Self::Vsync, Self::Hard60, Self::Hard120, Self::NoVsync];
295
296    pub fn label(self) -> &'static str {
297        match self {
298            Self::Vsync => "VSync",
299            Self::Hard60 => "60fps",
300            Self::Hard120 => "120fps",
301            Self::NoVsync => "NoVSync",
302        }
303    }
304
305    pub fn target_fps(self) -> Option<u32> {
306        match self {
307            Self::Hard60 => Some(60),
308            Self::Hard120 => Some(120),
309            Self::Vsync | Self::NoVsync => None,
310        }
311    }
312}
313
314#[derive(Clone, Copy, Debug, PartialEq)]
315pub struct FrameSchedule {
316    pub needs_update: bool,
317    pub needs_frame: bool,
318    pub next_deadline: Option<web_time::Instant>,
319}
320
321#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
322pub struct FrameUpdateResult {
323    pub visual_changed: bool,
324    pub structure_changed: bool,
325}
326
327pub trait PlatformFrameDriver {
328    fn request_frame(&self);
329    fn request_wake_at(&self, deadline: web_time::Instant);
330    fn clear_wake(&self);
331}
332
333#[derive(Debug)]
334pub struct FrameScheduler {
335    update_pending: AtomicBool,
336    frame_pending: AtomicBool,
337    next_deadline: Mutex<Option<web_time::Instant>>,
338}
339
340impl Default for FrameScheduler {
341    fn default() -> Self {
342        Self {
343            update_pending: AtomicBool::new(false),
344            frame_pending: AtomicBool::new(false),
345            next_deadline: Mutex::new(None),
346        }
347    }
348}
349
350impl FrameScheduler {
351    fn lock_deadline(&self) -> MutexGuard<'_, Option<web_time::Instant>> {
352        self.next_deadline
353            .lock()
354            .unwrap_or_else(|poisoned| poisoned.into_inner())
355    }
356
357    pub fn record(&self, schedule: FrameSchedule) {
358        self.update_pending
359            .store(schedule.needs_update, Ordering::SeqCst);
360        self.frame_pending
361            .store(schedule.needs_frame, Ordering::SeqCst);
362        let mut next_deadline = self.lock_deadline();
363        *next_deadline = if schedule.needs_update {
364            None
365        } else {
366            schedule.next_deadline
367        };
368    }
369
370    pub fn schedule<D>(&self, schedule: FrameSchedule, driver: &D)
371    where
372        D: PlatformFrameDriver + ?Sized,
373    {
374        self.record(schedule);
375        schedule.apply_to(driver);
376    }
377
378    pub fn snapshot(&self) -> FrameSchedule {
379        FrameSchedule {
380            needs_update: self.update_pending.load(Ordering::SeqCst),
381            needs_frame: self.frame_pending.load(Ordering::SeqCst),
382            next_deadline: *self.lock_deadline(),
383        }
384    }
385}
386
387impl FrameSchedule {
388    pub fn apply_to<D>(self, driver: &D)
389    where
390        D: PlatformFrameDriver + ?Sized,
391    {
392        if self.needs_frame {
393            driver.clear_wake();
394            driver.request_frame();
395        } else if self.needs_update {
396            driver.request_wake_at(web_time::Instant::now());
397        } else if let Some(deadline) = self.next_deadline {
398            driver.request_wake_at(deadline);
399        } else {
400            driver.clear_wake();
401        }
402    }
403}
404
405#[derive(Clone, Copy, Debug)]
406struct DevOverlayControl {
407    bounds: Rect,
408    mode: FramePacingMode,
409}
410
411/// Development options for debugging and performance monitoring.
412///
413/// These are rendered directly by the renderer (not via composition)
414/// to avoid affecting performance measurements.
415#[derive(Clone, Debug, Default)]
416pub struct DevOptions {
417    /// Show FPS counter overlay
418    pub fps_counter: bool,
419    /// Show recomposition count
420    pub recomposition_counter: bool,
421    /// Show layout timing breakdown
422    pub layout_timing: bool,
423    pub frame_pacing_controls: bool,
424    pub frame_pacing_mode: FramePacingMode,
425}
426
427#[cfg(any(test, feature = "test-support"))]
428#[doc(hidden)]
429#[derive(Clone, Copy, Debug)]
430pub struct RuntimeLeakDebugStats {
431    pub applier_stats: MemoryApplierDebugStats,
432    pub live_node_heap_bytes: usize,
433    pub recycled_node_heap_bytes: usize,
434    pub slot_table_heap_bytes: usize,
435    pub pass_stats: CompositionPassDebugStats,
436    pub slot_stats: SlotTableDebugStats,
437    pub observer_stats: SnapshotStateObserverDebugStats,
438    pub runtime_stats: RuntimeDebugStats,
439    pub state_arena_stats: StateArenaDebugStats,
440    pub recompose_scope_stats: RecomposeScopeRegistryDebugStats,
441    pub snapshot_v2_stats: SnapshotV2DebugStats,
442    pub snapshot_pinning_stats: SnapshotPinningDebugStats,
443}
444
445impl<R> AppShell<R>
446where
447    R: Renderer,
448    R::Error: Debug,
449{
450    pub fn new(renderer: R, root_key: Key, content: impl FnMut() + 'static) -> Self {
451        Self::new_with_size(renderer, root_key, content, (800, 600), (800.0, 600.0))
452    }
453
454    pub fn new_with_size(
455        renderer: R,
456        root_key: Key,
457        content: impl FnMut() + 'static,
458        buffer_size: (u32, u32),
459        viewport: (f32, f32),
460    ) -> Self {
461        Self::new_with_size_and_density(renderer, root_key, content, buffer_size, viewport, 1.0)
462    }
463
464    pub fn new_with_size_and_density(
465        mut renderer: R,
466        root_key: Key,
467        content: impl FnMut() + 'static,
468        buffer_size: (u32, u32),
469        viewport: (f32, f32),
470        density: f32,
471    ) -> Self {
472        let app_context = cranpose_ui::AppContext::new_with_density(density);
473        let runtime = StdRuntime::new();
474        let mut composition = Composition::with_runtime(MemoryApplier::new(), runtime.runtime());
475        let app_content = Rc::new(std::cell::RefCell::new(content));
476        let mut build: Box<dyn FnMut()> = Box::new(move || {
477            let app_content = Rc::clone(&app_content);
478            cranpose_ui::widgets::PopupHost(move || {
479                (app_content.borrow_mut())();
480            });
481        });
482        renderer.attach_app_context_services(&app_context);
483        app_context.enter(|| {
484            #[cfg(all(
485                feature = "clipboard-native",
486                not(target_arch = "wasm32"),
487                not(target_os = "android"),
488                not(target_os = "ios")
489            ))]
490            {
491                let clipboard =
492                    std::rc::Rc::new(std::cell::RefCell::new(arboard::Clipboard::new().ok()));
493                cranpose_ui::clipboard_session::set_platform_clipboard(std::rc::Rc::new(
494                    ShellClipboard { inner: clipboard },
495                ));
496            }
497            if let Err(err) = composition.render_stable(root_key, &mut *build) {
498                log::error!("initial render failed: {err}");
499            }
500        });
501        renderer.scene_mut().clear();
502        let mut shell = Self {
503            app_context,
504            runtime,
505            composition,
506            content: build,
507            renderer,
508            cursor: (0.0, 0.0),
509            viewport,
510            buffer_size,
511            start_time: Instant::now(),
512            last_frame_time_nanos: 0,
513            layout_tree: None,
514            semantics_tree: None,
515            semantics_enabled: false,
516            semantics_snapshot_revision: 0,
517            frame_rate_preference: FrameRatePreference::default(),
518            layout_requested: true,
519            force_layout_pass: true,
520            scene_dirty: true,
521            scoped_layout_scene_nodes: Vec::new(),
522            retained_visual_nodes: HashSet::new(),
523            is_dirty: true,
524            buttons_pressed: PointerButtons::NONE,
525            pointer_source: PointerSource::Unknown,
526            modifiers: None,
527            hit_path_tracker: HitPathTracker::new(),
528            hovered_nodes: Vec::new(),
529            on_rotary_scroll: None,
530            rotary_scroll_factor: DEFAULT_ROTARY_SCROLL_FACTOR_DP,
531            #[cfg(all(feature = "clipboard-native", target_os = "linux"))]
532            clipboard: arboard::Clipboard::new().ok(),
533            dev_options: DevOptions::default(),
534            dev_overlay_controls: Vec::new(),
535            dev_overlay_text: String::new(),
536            dev_overlay_last_refresh: None,
537            dev_overlay_viewport: None,
538            fps_monitor: fps_monitor::FpsMonitor::new(),
539            frame_scheduler: FrameScheduler::default(),
540        };
541        shell.process_frame();
542        shell
543    }
544
545    /// The shell's [`AppContext`](cranpose_ui::AppContext). Platform backends
546    /// use it to register per-context services (such as the OS clipboard) that
547    /// need UIKit/JNI access the shell itself does not have: enter the context
548    /// and call the relevant `set_platform_*` installer.
549    pub fn app_context(&self) -> &Rc<cranpose_ui::AppContext> {
550        &self.app_context
551    }
552
553    /// Set development options for debugging and performance monitoring.
554    ///
555    /// The FPS counter and other overlays are rendered directly by the renderer
556    /// (not via composition) to avoid affecting performance measurements.
557    pub fn set_dev_options(&mut self, options: DevOptions) {
558        self.dev_options = options;
559        self.invalidate_dev_overlay_text();
560        let app_context = Rc::clone(&self.app_context);
561        app_context.enter(request_render_invalidation);
562        self.mark_dirty();
563    }
564
565    /// Get a reference to the current dev options.
566    pub fn dev_options(&self) -> &DevOptions {
567        &self.dev_options
568    }
569
570    pub fn frame_pacing_mode(&self) -> FramePacingMode {
571        self.dev_options.frame_pacing_mode
572    }
573
574    pub fn current_fps(&self) -> f32 {
575        self.fps_monitor.current_fps()
576    }
577
578    pub fn fps_stats(&self) -> FpsStats {
579        self.fps_monitor.stats()
580    }
581
582    pub fn reset_fps_stats(&mut self) {
583        self.fps_monitor.reset_stats();
584        self.invalidate_dev_overlay_text();
585    }
586
587    pub fn record_presented_frame(
588        &mut self,
589        frame_started_at: Instant,
590        frame_finished_at: Instant,
591    ) {
592        self.fps_monitor
593            .record_frame_work(frame_started_at, frame_finished_at);
594    }
595
596    #[cfg(any(test, feature = "test-support"))]
597    #[doc(hidden)]
598    pub fn record_presented_frame_for_test(
599        &mut self,
600        frame_started_nanos: u64,
601        frame_finished_nanos: u64,
602    ) {
603        let started = self.start_time + std::time::Duration::from_nanos(frame_started_nanos);
604        let finished = self.start_time + std::time::Duration::from_nanos(frame_finished_nanos);
605        self.record_presented_frame(started, finished);
606    }
607
608    pub fn set_frame_pacing_mode(&mut self, mode: FramePacingMode) {
609        if self.dev_options.frame_pacing_mode == mode {
610            return;
611        }
612        self.dev_options.frame_pacing_mode = mode;
613        self.invalidate_dev_overlay_text();
614        let app_context = Rc::clone(&self.app_context);
615        app_context.enter(request_render_invalidation);
616        self.mark_dirty();
617    }
618
619    /// Where the dev overlay draws the control for `mode`, in logical pixels.
620    ///
621    /// The overlay is drawn by the renderer rather than composed, so it has no
622    /// semantics for a test to search. Without this a test that wants to press
623    /// a pacing control has to hard-code a coordinate and silently starts
624    /// passing against empty space the moment the overlay's text changes.
625    pub fn dev_overlay_control_center(&self, mode: FramePacingMode) -> Option<(f32, f32)> {
626        self.dev_overlay_controls
627            .iter()
628            .find(|control| control.mode == mode)
629            .map(|control| {
630                (
631                    control.bounds.x + control.bounds.width * 0.5,
632                    control.bounds.y + control.bounds.height * 0.5,
633                )
634            })
635    }
636
637    pub(crate) fn dev_overlay_press(&mut self, x: f32, y: f32) -> bool {
638        if !self.dev_options.frame_pacing_controls {
639            return false;
640        }
641        let Some(mode) = self
642            .dev_overlay_controls
643            .iter()
644            .find(|control| control.bounds.contains(x, y))
645            .map(|control| control.mode)
646        else {
647            return false;
648        };
649        self.set_frame_pacing_mode(mode);
650        true
651    }
652
653    fn invalidate_dev_overlay_text(&mut self) {
654        self.dev_overlay_text.clear();
655        self.dev_overlay_last_refresh = None;
656        self.dev_overlay_viewport = None;
657    }
658
659    pub fn set_viewport(&mut self, width: f32, height: f32) {
660        self.viewport = (width, height);
661        self.request_forced_layout_pass();
662        self.mark_dirty();
663        self.process_frame();
664    }
665
666    pub fn viewport_size(&self) -> (f32, f32) {
667        self.viewport
668    }
669
670    pub fn set_buffer_size(&mut self, width: u32, height: u32) {
671        self.buffer_size = (width, height);
672    }
673
674    pub fn buffer_size(&self) -> (u32, u32) {
675        self.buffer_size
676    }
677
678    pub fn scene(&self) -> &R::Scene {
679        self.renderer.scene()
680    }
681
682    pub fn renderer(&mut self) -> &mut R {
683        &mut self.renderer
684    }
685
686    #[cfg(not(target_arch = "wasm32"))]
687    pub fn set_frame_waker(&mut self, waker: impl Fn() + Send + Sync + 'static) {
688        self.runtime.set_frame_waker(waker);
689    }
690
691    #[cfg(target_arch = "wasm32")]
692    pub fn set_frame_waker(&mut self, waker: impl Fn() + 'static) {
693        self.runtime.set_frame_waker(waker);
694    }
695
696    pub fn clear_frame_waker(&mut self) {
697        self.runtime.clear_frame_waker();
698    }
699
700    pub fn should_render(&self) -> bool {
701        let app_context = Rc::clone(&self.app_context);
702        app_context.enter(|| {
703            if self.layout_requested
704                || self.scene_dirty
705                || peek_render_invalidation()
706                || peek_pointer_invalidation()
707                || peek_focus_invalidation()
708                || peek_layout_invalidation()
709            {
710                return true;
711            }
712            self.composition.should_render()
713        })
714    }
715
716    fn has_stale_pixels_in_context(&self) -> bool {
717        self.is_dirty
718            || self.layout_requested
719            || self.scene_dirty
720            || peek_render_invalidation()
721            || peek_pointer_invalidation()
722            || peek_focus_invalidation()
723            || peek_layout_invalidation()
724            || cranpose_ui::has_pending_layout_repasses()
725            || cranpose_ui::has_pending_measure_repasses()
726            || cranpose_ui::has_pending_draw_repasses()
727            || has_pending_pointer_repasses()
728            || has_pending_focus_invalidations()
729    }
730
731    fn needs_ui_update_in_context(&self) -> bool {
732        self.has_stale_pixels_in_context()
733            || self.composition.runtime_handle().has_pending_ui()
734            || has_pending_semantics_invalidations()
735            || self.composition.should_render()
736    }
737
738    pub fn needs_update(&self) -> bool {
739        let app_context = Rc::clone(&self.app_context);
740        app_context.enter(|| self.needs_ui_update_in_context())
741    }
742
743    /// Returns true when the runtime holds work for the UI thread: posted tasks,
744    /// continuations from worker threads, or async tasks ready to poll.
745    ///
746    /// This is the part of [`needs_update`](Self::needs_update) that another
747    /// thread is waiting on, told apart from the part that only wants the screen
748    /// redrawn. A platform backend running with no surface uses it to compose
749    /// for work and stay asleep for animation.
750    pub fn has_pending_ui(&self) -> bool {
751        let app_context = Rc::clone(&self.app_context);
752        app_context.enter(|| self.composition.runtime_handle().has_pending_ui())
753    }
754
755    /// Returns true if the shell owes the display a frame: stale pixels, or a
756    /// renderer that has not warmed its swapchain yet.
757    ///
758    /// An app that merely holds an open `next_frame()` await - a game loop, a
759    /// polling effect - keeps [`Self::needs_update`] true forever without
760    /// changing a single pixel. Such an app must still be *ticked* every frame,
761    /// but the frame it produces is byte-identical to the last one, and
762    /// presenting it costs a full swapchain rotation and pins the panel at its
763    /// maximum refresh rate. Callers pair this with
764    /// [`FrameUpdateResult::visual_changed`] from the update they just ran,
765    /// which reports the work that update actually did.
766    /// Note: Cursor blink is now timer-based and uses WaitUntil scheduling, not continuous redraw.
767    pub fn needs_redraw(&self) -> bool {
768        let app_context = Rc::clone(&self.app_context);
769        app_context.enter(|| self.has_stale_pixels_in_context() || self.renderer_warmup_due())
770    }
771
772    /// A renderer warmup is a frame rendered only so caches see their content
773    /// a second time. While a frame callback is armed the app is about to
774    /// produce a frame anyway, and rendering the same scene again first would
775    /// double every animated frame's cost for entries the next frame replaces.
776    fn renderer_warmup_due(&self) -> bool {
777        self.renderer.needs_frame_warmup() && !self.runtime.runtime_handle().has_frame_callbacks()
778    }
779
780    /// Marks the shell as dirty, indicating a redraw is needed.
781    pub fn mark_dirty(&mut self) {
782        self.is_dirty = true;
783    }
784
785    pub fn request_root_render(&mut self) {
786        self.composition.request_root_render();
787        self.request_forced_layout_pass();
788        let app_context = Rc::clone(&self.app_context);
789        app_context.enter(request_render_invalidation);
790        self.mark_dirty();
791    }
792
793    pub fn set_density(&mut self, density: f32) {
794        let app_context = Rc::clone(&self.app_context);
795        let changed = app_context.enter(|| {
796            let previous = cranpose_ui::current_density().to_bits();
797            cranpose_ui::set_density(density);
798            previous != cranpose_ui::current_density().to_bits()
799        });
800        if changed {
801            self.request_forced_layout_pass();
802            self.mark_dirty();
803        }
804    }
805
806    /// Reports the system font scale the platform is showing text at.
807    ///
808    /// Hosts call this at startup and on every configuration change. Sizes in
809    /// `Sp` follow it, sizes in `Dp` do not, which is what lets an app grow its
810    /// text with the user's setting while its layout stays where it was.
811    ///
812    /// This takes the setting as a plain multiplier. A host whose platform
813    /// converts `Sp` through a table of its own — Android 14 and up does — calls
814    /// [`AppShell::set_font_scale_curve`] with what the platform answered
815    /// instead, because the multiplication is not what that platform does.
816    pub fn set_font_scale(&mut self, font_scale: f32) {
817        self.set_font_scale_curve(cranpose_ui::FontScaleCurve::linear(font_scale));
818    }
819
820    /// Reports the system font scale together with the conversion behind it.
821    ///
822    /// See [`cranpose_ui::font_scale`]: above a threshold setting Android
823    /// resolves a size in `Sp` through a piecewise-linear table rather than by
824    /// multiplying, so a host that can read that table hands it over here and
825    /// every `Sp` in the app resolves the way the platform's own text does.
826    pub fn set_font_scale_curve(&mut self, curve: cranpose_ui::FontScaleCurve) {
827        let app_context = Rc::clone(&self.app_context);
828        let changed = app_context.enter(|| {
829            let previous = cranpose_ui::current_font_scale_curve();
830            cranpose_ui::set_font_scale_curve(curve);
831            previous != cranpose_ui::current_font_scale_curve()
832        });
833        if changed {
834            self.request_forced_layout_pass();
835            self.mark_dirty();
836        }
837    }
838
839    #[cfg(any(test, feature = "test-support"))]
840    #[doc(hidden)]
841    pub fn debug_current_density(&self) -> f32 {
842        let app_context = Rc::clone(&self.app_context);
843        app_context.enter(cranpose_ui::current_density)
844    }
845
846    #[cfg(any(test, feature = "test-support"))]
847    #[doc(hidden)]
848    pub fn debug_current_font_scale(&self) -> f32 {
849        let app_context = Rc::clone(&self.app_context);
850        app_context.enter(cranpose_ui::current_font_scale)
851    }
852
853    #[cfg(any(test, feature = "test-support"))]
854    #[doc(hidden)]
855    pub fn debug_current_font_scale_curve(&self) -> cranpose_ui::FontScaleCurve {
856        let app_context = Rc::clone(&self.app_context);
857        app_context.enter(cranpose_ui::current_font_scale_curve)
858    }
859
860    #[cfg(any(test, feature = "test-support"))]
861    #[doc(hidden)]
862    pub fn debug_enter_app_context<T>(&self, block: impl FnOnce() -> T) -> T {
863        let app_context = Rc::clone(&self.app_context);
864        app_context.enter(block)
865    }
866
867    fn request_layout_pass(&mut self) {
868        self.layout_requested = true;
869    }
870
871    fn request_forced_layout_pass(&mut self) {
872        self.layout_requested = true;
873        self.force_layout_pass = true;
874    }
875
876    fn composition_tree_needs_layout(&mut self) -> bool {
877        let Some(root) = self.composition.root() else {
878            return true;
879        };
880        let mut applier = self.composition.applier_mut();
881        cranpose_ui::tree_needs_layout(&mut *applier, root).unwrap_or_else(|err| {
882            log::warn!(
883                "Cannot check layout dirty status for root #{}: {}",
884                root,
885                err
886            );
887            true
888        })
889    }
890
891    /// Returns true if there are active animations or pending recompositions.
892    pub fn has_active_animations(&self) -> bool {
893        self.composition.should_render()
894    }
895
896    pub fn has_transient_frame_callbacks(&self) -> bool {
897        self.composition
898            .runtime_handle()
899            .has_transient_frame_callbacks()
900    }
901
902    pub fn has_active_pointer_gesture(&self) -> bool {
903        self.buttons_pressed != PointerButtons::NONE
904            && self.hit_path_tracker.has_path(PointerId::PRIMARY)
905    }
906
907    /// Returns the next scheduled event time for cursor blink.
908    /// Use this for `ControlFlow::WaitUntil` scheduling.
909    pub fn next_event_time(&self) -> Option<web_time::Instant> {
910        let app_context = Rc::clone(&self.app_context);
911        app_context.enter(cranpose_ui::next_cursor_blink_time)
912    }
913
914    fn compute_frame_schedule(&self) -> FrameSchedule {
915        let needs_update = self.needs_update();
916        let needs_frame = self.is_dirty
917            || self.should_render()
918            || self.has_active_pointer_gesture()
919            || self.renderer_warmup_due();
920        FrameSchedule {
921            needs_update,
922            needs_frame,
923            next_deadline: self.next_event_time(),
924        }
925    }
926
927    pub fn frame_schedule(&self) -> FrameSchedule {
928        let schedule = self.compute_frame_schedule();
929        self.frame_scheduler.record(schedule);
930        schedule
931    }
932
933    pub fn schedule_platform_frame<D>(&self, driver: &D) -> FrameSchedule
934    where
935        D: PlatformFrameDriver + ?Sized,
936    {
937        let schedule = self.compute_frame_schedule();
938        self.frame_scheduler.schedule(schedule, driver);
939        schedule
940    }
941
942    pub fn frame_scheduler_snapshot(&self) -> FrameSchedule {
943        self.frame_scheduler.snapshot()
944    }
945
946    fn frame_time_nanos_at(&self, now: Instant) -> u64 {
947        now.checked_duration_since(self.start_time)
948            .unwrap_or_default()
949            .as_nanos()
950            .min(u128::from(u64::MAX)) as u64
951    }
952
953    /// Timestamp a live input sample against the current animation clock.
954    pub fn realtime_pointer_event_time(&self, platform_time_ms: Option<i64>) -> PointerEventTime {
955        PointerEventTime {
956            platform_time_ms,
957            animation_time_nanos: self
958                .frame_time_nanos_at(Instant::now())
959                .max(self.last_frame_time_nanos),
960        }
961    }
962
963    /// Timestamp deterministic input at the most recently processed frame.
964    pub fn exact_pointer_event_time(&self, platform_time_ms: Option<i64>) -> PointerEventTime {
965        PointerEventTime {
966            platform_time_ms,
967            animation_time_nanos: self.last_frame_time_nanos,
968        }
969    }
970
971    pub fn update_after_frame_interval(
972        &mut self,
973        frame_interval: std::time::Duration,
974    ) -> FrameUpdateResult {
975        let wall_frame_time = self.frame_time_nanos_at(Instant::now());
976        let base_frame_time = self.last_frame_time_nanos.max(wall_frame_time);
977        let frame_time = base_frame_time
978            .saturating_add(frame_interval.as_nanos().min(u128::from(u64::MAX)) as u64);
979        self.update_at_frame_time_nanos(frame_time)
980    }
981
982    /// Advance the frame clock by EXACTLY `frame_interval` past the last
983    /// frame — no wall anchoring — and run one update there. Robot keyframe
984    /// captures ride this to sample animations deterministically: while the
985    /// advanced clock is ahead of wall time, interleaved wall-clocked
986    /// updates clamp to it (dt 0) instead of fast-forwarding animations.
987    pub fn update_after_exact_interval(
988        &mut self,
989        frame_interval: std::time::Duration,
990    ) -> FrameUpdateResult {
991        let frame_time = self
992            .last_frame_time_nanos
993            .saturating_add(frame_interval.as_nanos().min(u128::from(u64::MAX)) as u64);
994        self.update_at_frame_time_nanos(frame_time)
995    }
996
997    pub fn update_at_frame_time_nanos(&mut self, frame_time: u64) -> FrameUpdateResult {
998        let app_context = Rc::clone(&self.app_context);
999        app_context.enter(|| {
1000            let update_started_at = Instant::now();
1001            let frame_time = frame_time.max(self.last_frame_time_nanos);
1002            self.last_frame_time_nanos = frame_time;
1003            let runtime_handle = self.runtime.runtime_handle();
1004            runtime_handle.with_deferred_state_releases(|| {
1005                self.runtime.drain_frame_callbacks(frame_time);
1006                let after_frame_callbacks = Instant::now();
1007                runtime_handle.drain_ui();
1008                let after_ui_drain = Instant::now();
1009                let should_render = self.composition.should_recompose();
1010                let mut reconcile_attempted = false;
1011                let mut reconcile_changed = false;
1012                if should_render {
1013                    log::trace!(
1014                        target: "cranpose::input",
1015                        "update begin: should_render=true layout_requested={} scene_dirty={} is_dirty={}",
1016                        self.layout_requested,
1017                        self.scene_dirty,
1018                        self.is_dirty
1019                    );
1020                }
1021                if should_render {
1022                    let Some(root_key) = self.composition.root_key() else {
1023                        let result = self.process_frame_in_context(reconcile_changed);
1024                        let after_process_frame = Instant::now();
1025                        log_update_stage_telemetry(UpdateStageTelemetry {
1026                            started_at: update_started_at,
1027                            after_frame_callbacks,
1028                            after_ui_drain,
1029                            after_reconcile: after_ui_drain,
1030                            after_process_frame,
1031                            should_render,
1032                            reconcile_attempted,
1033                            reconcile_changed,
1034                        });
1035                        self.is_dirty = false;
1036                        return result;
1037                    };
1038                    reconcile_attempted = true;
1039                    match self.composition.reconcile(root_key, &mut *self.content) {
1040                        Ok(changed) => {
1041                            reconcile_changed = changed;
1042                            log::trace!(
1043                                target: "cranpose::input",
1044                                "reconcile changed={changed}"
1045                            );
1046                            if changed {
1047                                self.fps_monitor.record_recomposition();
1048                                if self.composition_tree_needs_layout() {
1049                                    self.request_layout_pass();
1050                                }
1051                                request_render_invalidation();
1052                            }
1053                        }
1054                        Err(NodeError::Missing { id }) => {
1055                            log::debug!("Recomposition skipped: node {} no longer exists", id);
1056                            self.request_layout_pass();
1057                            request_render_invalidation();
1058                        }
1059                        Err(err) => {
1060                            log::error!("recomposition failed: {err}");
1061                            self.request_layout_pass();
1062                            request_render_invalidation();
1063                        }
1064                    }
1065                }
1066                let after_reconcile = Instant::now();
1067                let result = self.process_frame_in_context(reconcile_changed);
1068                let after_process_frame = Instant::now();
1069                log_update_stage_telemetry(UpdateStageTelemetry {
1070                    started_at: update_started_at,
1071                    after_frame_callbacks,
1072                    after_ui_drain,
1073                    after_reconcile,
1074                    after_process_frame,
1075                    should_render,
1076                    reconcile_attempted,
1077                    reconcile_changed,
1078                });
1079                self.is_dirty = false;
1080                result
1081            })
1082        })
1083    }
1084
1085    pub fn update(&mut self) -> FrameUpdateResult {
1086        let frame_time = self.frame_time_nanos_at(Instant::now());
1087        self.update_at_frame_time_nanos(frame_time)
1088    }
1089}
1090
1091impl<R> Drop for AppShell<R>
1092where
1093    R: Renderer,
1094{
1095    fn drop(&mut self) {
1096        self.runtime.clear_frame_waker();
1097    }
1098}
1099
1100pub fn default_root_key() -> Key {
1101    location_key(file!(), line!(), column!())
1102}
1103
1104#[cfg(test)]
1105mod frame_pacing_tests {
1106    use std::{
1107        cell::RefCell,
1108        panic::{AssertUnwindSafe, catch_unwind},
1109        time::Duration,
1110    };
1111
1112    use web_time::Instant;
1113
1114    use super::{FramePacingMode, FrameSchedule, FrameScheduler, PlatformFrameDriver};
1115
1116    #[derive(Clone, Copy, Debug, PartialEq)]
1117    enum DriverCall {
1118        RequestFrame,
1119        RequestWakeAt(Instant),
1120        ClearWake,
1121    }
1122
1123    #[derive(Default)]
1124    struct RecordingFrameDriver {
1125        calls: RefCell<Vec<DriverCall>>,
1126    }
1127
1128    impl RecordingFrameDriver {
1129        fn calls(&self) -> Vec<DriverCall> {
1130            self.calls.borrow().clone()
1131        }
1132    }
1133
1134    impl PlatformFrameDriver for RecordingFrameDriver {
1135        fn request_frame(&self) {
1136            self.calls.borrow_mut().push(DriverCall::RequestFrame);
1137        }
1138
1139        fn request_wake_at(&self, deadline: Instant) {
1140            self.calls
1141                .borrow_mut()
1142                .push(DriverCall::RequestWakeAt(deadline));
1143        }
1144
1145        fn clear_wake(&self) {
1146            self.calls.borrow_mut().push(DriverCall::ClearWake);
1147        }
1148    }
1149
1150    #[test]
1151    fn frame_pacing_labels_match_overlay_modes() {
1152        assert_eq!(FramePacingMode::Vsync.label(), "VSync");
1153        assert_eq!(FramePacingMode::Hard60.label(), "60fps");
1154        assert_eq!(FramePacingMode::Hard120.label(), "120fps");
1155        assert_eq!(FramePacingMode::NoVsync.label(), "NoVSync");
1156    }
1157
1158    #[test]
1159    fn only_hard_modes_have_fixed_targets() {
1160        assert_eq!(FramePacingMode::Vsync.target_fps(), None);
1161        assert_eq!(FramePacingMode::Hard60.target_fps(), Some(60));
1162        assert_eq!(FramePacingMode::Hard120.target_fps(), Some(120));
1163        assert_eq!(FramePacingMode::NoVsync.target_fps(), None);
1164    }
1165
1166    #[test]
1167    fn frame_schedule_requests_immediate_frame_and_clears_deadline() {
1168        let driver = RecordingFrameDriver::default();
1169        let deadline = Instant::now() + Duration::from_millis(25);
1170
1171        FrameSchedule {
1172            needs_update: true,
1173            needs_frame: true,
1174            next_deadline: Some(deadline),
1175        }
1176        .apply_to(&driver);
1177
1178        assert_eq!(
1179            driver.calls(),
1180            vec![DriverCall::ClearWake, DriverCall::RequestFrame]
1181        );
1182    }
1183
1184    #[test]
1185    fn frame_schedule_requests_deadline_when_idle_until_timer() {
1186        let driver = RecordingFrameDriver::default();
1187        let deadline = Instant::now() + Duration::from_millis(25);
1188
1189        FrameSchedule {
1190            needs_update: false,
1191            needs_frame: false,
1192            next_deadline: Some(deadline),
1193        }
1194        .apply_to(&driver);
1195
1196        assert_eq!(driver.calls(), vec![DriverCall::RequestWakeAt(deadline)]);
1197    }
1198
1199    #[test]
1200    fn frame_schedule_wakes_without_requesting_frame_for_update_only_work() {
1201        let driver = RecordingFrameDriver::default();
1202        let before = Instant::now();
1203
1204        FrameSchedule {
1205            needs_update: true,
1206            needs_frame: false,
1207            next_deadline: None,
1208        }
1209        .apply_to(&driver);
1210
1211        let calls = driver.calls();
1212        assert_eq!(calls.len(), 1);
1213        match calls[0] {
1214            DriverCall::RequestWakeAt(deadline) => {
1215                assert!(deadline >= before);
1216            }
1217            other => panic!("update-only work must wake without requesting a frame: {other:?}"),
1218        }
1219    }
1220
1221    #[test]
1222    fn frame_schedule_clears_wake_when_fully_idle() {
1223        let driver = RecordingFrameDriver::default();
1224
1225        FrameSchedule {
1226            needs_update: false,
1227            needs_frame: false,
1228            next_deadline: None,
1229        }
1230        .apply_to(&driver);
1231
1232        assert_eq!(driver.calls(), vec![DriverCall::ClearWake]);
1233    }
1234
1235    #[test]
1236    fn frame_scheduler_records_latest_schedule_and_applies_driver() {
1237        let scheduler = FrameScheduler::default();
1238        let driver = RecordingFrameDriver::default();
1239        let deadline = Instant::now() + Duration::from_millis(25);
1240
1241        scheduler.schedule(
1242            FrameSchedule {
1243                needs_update: false,
1244                needs_frame: false,
1245                next_deadline: Some(deadline),
1246            },
1247            &driver,
1248        );
1249
1250        assert_eq!(
1251            scheduler.snapshot(),
1252            FrameSchedule {
1253                needs_update: false,
1254                needs_frame: false,
1255                next_deadline: Some(deadline),
1256            }
1257        );
1258        assert_eq!(driver.calls(), vec![DriverCall::RequestWakeAt(deadline)]);
1259    }
1260
1261    #[test]
1262    fn frame_scheduler_clears_deadline_for_immediate_frame() {
1263        let scheduler = FrameScheduler::default();
1264        let driver = RecordingFrameDriver::default();
1265        let deadline = Instant::now() + Duration::from_millis(25);
1266
1267        scheduler.schedule(
1268            FrameSchedule {
1269                needs_update: true,
1270                needs_frame: true,
1271                next_deadline: Some(deadline),
1272            },
1273            &driver,
1274        );
1275
1276        assert_eq!(
1277            scheduler.snapshot(),
1278            FrameSchedule {
1279                needs_update: true,
1280                needs_frame: true,
1281                next_deadline: None,
1282            }
1283        );
1284        assert_eq!(
1285            driver.calls(),
1286            vec![DriverCall::ClearWake, DriverCall::RequestFrame]
1287        );
1288    }
1289
1290    #[test]
1291    fn frame_scheduler_recovers_poisoned_deadline_lock() {
1292        let scheduler = FrameScheduler::default();
1293        let deadline = Instant::now() + Duration::from_millis(25);
1294
1295        let _ = catch_unwind(AssertUnwindSafe(|| {
1296            let _guard = scheduler.lock_deadline();
1297            panic!("poison frame scheduler deadline lock");
1298        }));
1299
1300        scheduler.record(FrameSchedule {
1301            needs_update: false,
1302            needs_frame: false,
1303            next_deadline: Some(deadline),
1304        });
1305
1306        assert_eq!(
1307            scheduler.snapshot(),
1308            FrameSchedule {
1309                needs_update: false,
1310                needs_frame: false,
1311                next_deadline: Some(deadline),
1312            }
1313        );
1314    }
1315}
1316
1317#[cfg(test)]
1318#[path = "tests/app_shell_tests.rs"]
1319mod tests;