Skip to main content

cranpose_app_shell/
lib.rs

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