Skip to main content

cranpose_app_shell/
lib.rs

1use std::sync::PoisonError;
2mod focus_reveal;
3mod fps_monitor;
4mod frame_rate_boost;
5mod hit_path_tracker;
6pub mod inspector;
7mod modal_focus;
8#[cfg(debug_assertions)]
9mod semantics_check;
10mod shell_debug;
11mod shell_frame;
12mod shell_input;
13mod surface;
14mod wheel;
15use std::{
16    cell::RefCell,
17    fmt::{Debug, Write},
18    rc::Rc,
19    sync::{
20        Mutex, MutexGuard,
21        atomic::{AtomicBool, Ordering},
22    },
23};
24
25use cranpose_core::{
26    Applier, Composition, Key, MemoryApplier, NodeError, NodeId, collections::map::HashSet,
27    enter_event_handler_scope, location_key, run_in_mutable_snapshot,
28};
29pub use cranpose_foundation::{
30    DEFAULT_ROTARY_SCROLL_FACTOR_DP, Modifiers, PointerSource, RotaryScrollEvent,
31    rotary_scroll_pixels_from_detents,
32};
33use cranpose_foundation::{PointerButton, PointerButtons, PointerEvent, PointerEventKind};
34use cranpose_render_common::{HitTestTarget, RenderScene, Renderer};
35use cranpose_runtime_std::StdRuntime;
36use cranpose_ui::{
37    HeadlessRenderer, LayoutBox, LayoutNode, LayoutTree, MeasureLayoutOptions, SemanticsTree,
38    SubcomposeLayoutNode, WindowRootEntry, clear_transient_scroll_motion_contexts,
39    format_layout_tree, format_render_scene, format_screen_summary,
40    has_pending_focus_invalidations, has_pending_pointer_repasses,
41    has_pending_semantics_invalidations, peek_focus_invalidation, peek_layout_invalidation,
42    peek_pointer_invalidation, peek_render_invalidation, process_focus_invalidations,
43    process_pointer_repasses, process_semantics_invalidations, request_render_invalidation,
44    take_draw_repass_nodes, take_focus_invalidation, take_layout_invalidation,
45    take_pointer_invalidation, take_render_invalidation,
46};
47pub use cranpose_ui::{KeyCode, KeyEvent, KeyEventType};
48use cranpose_ui_graphics::{Point, PointerIcon, Rect, Size};
49pub use fps_monitor::FpsStats;
50pub use frame_rate_boost::FrameRateBoost;
51use hit_path_tracker::PointerId;
52#[cfg(test)]
53use shell_frame::build_draw_refresh_scope;
54pub use surface::{RootId, RootSurface, SurfaceMut};
55use surface::{TextInputRouter, TextInputRoutes, partition_nodes_by_surface};
56use web_time::Instant;
57pub use wheel::WheelScroll;
58
59#[cfg(all(
60    feature = "clipboard-native",
61    not(target_arch = "wasm32"),
62    not(target_os = "android"),
63    not(target_os = "ios")
64))]
65struct ShellClipboard {
66    inner: std::rc::Rc<std::cell::RefCell<Option<arboard::Clipboard>>>,
67}
68
69#[cfg(all(
70    feature = "clipboard-native",
71    not(target_arch = "wasm32"),
72    not(target_os = "android"),
73    not(target_os = "ios")
74))]
75impl cranpose_ui::clipboard_session::PlatformClipboard for ShellClipboard {
76    fn write_text(&self, text: &str) {
77        if let Some(clipboard) = self.inner.borrow_mut().as_mut() {
78            let _ = clipboard.set_text(text);
79        }
80    }
81
82    fn read_text(&self) -> Option<String> {
83        self.inner
84            .borrow_mut()
85            .as_mut()
86            .and_then(|clipboard| clipboard.get_text().ok())
87    }
88}
89#[cfg(any(test, feature = "test-support"))]
90use cranpose_core::{
91    CompositionPassDebugStats, SlotId,
92    runtime::{RuntimeDebugStats, StateArenaDebugStats},
93    snapshot_pinning::{SnapshotPinningDebugStats, debug_snapshot_pinning_stats},
94    snapshot_state_observer::SnapshotStateObserverDebugStats,
95    snapshot_v2::{SnapshotV2DebugStats, debug_snapshot_v2_stats},
96};
97#[cfg(any(test, feature = "test-support"))]
98use cranpose_core::{
99    MemoryApplierDebugStats, RecomposeScopeRegistryDebugStats, SlotTableDebugStats,
100    debug_recompose_scope_registry_stats,
101};
102pub use cranpose_ui::{ImeEditorState, PlatformTextInputHandler};
103#[cfg(any(test, feature = "test-support"))]
104pub mod accessibility_audit;
105#[cfg(any(test, feature = "test-support"))]
106pub mod placed_semantics;
107
108/// How the platform should vote the display's frame rate on behalf of the app.
109///
110/// Compose apps get 120 Hz gameplay on a 120 Hz panel not by presenting faster
111/// but because HWUI votes a rate on the window while gestures run, content
112/// moves or the window redraws continuously, and clears it when they stop. A window that never votes is pinned by
113/// SurfaceFlinger's cadence inference instead — which also throttles the app's
114/// choreographer, so the inference reinforces itself. `Auto` reproduces the
115/// HWUI behaviour; the platform backends read it every frame and vote through
116/// the native window when the desired rate changes.
117#[derive(Debug, Clone, Copy, PartialEq, Default)]
118pub enum FrameRatePreference {
119    /// Ask for the panel's fastest rate while [`FrameRateBoost`] holds, a
120    /// quiet rate while frames arrive only intermittently, no preference
121    /// when the scene is still. This is the default, matching what Compose/HWUI do for every
122    /// app without the app's involvement.
123    #[default]
124    Auto,
125    /// Never vote; the OS infers a rate from presentation cadence.
126    NoPreference,
127    /// Always vote exactly this rate in Hz. Values `<= 0` behave like
128    /// [`FrameRatePreference::NoPreference`].
129    Exact(f32),
130}
131
132impl FrameRatePreference {
133    /// The baseline `Auto` votes while frames arrive without a boost — the
134    /// same rate HWUI's NORMAL frame-rate category resolves to on phone
135    /// panels. The quiet vote cannot simply be "no vote": SurfaceFlinger
136    /// infers a non-voting window's rate from whatever cadence it last
137    /// observed and pins it, so an app that ever ran the panel's fast rate
138    /// would stay there forever (measured on a Pixel 9 Pro, both directions).
139    pub const AUTO_QUIET_RATE_HZ: f32 = 60.0;
140
141    /// The rate the platform should vote right now, in Hz, where `0.0` means
142    /// "clear the vote". `producing_frames` is whether the frame loop has a
143    /// frame scheduled, `boosted` what [`FrameRateBoost::boosted`] says, and
144    /// `panel_max_hz` the display's fastest supported rate when the platform
145    /// knows it.
146    ///
147    /// While boosted, `Auto` holds the boost even through moments with no
148    /// frame scheduled: a gesture sequence crosses still screens (a tap lands,
149    /// the old scene stops animating, the new one hasn't started), and letting
150    /// each of those instantly clear the vote flapped the display between the
151    /// boost rate and no-vote several times per second on device. This mirrors
152    /// SurfaceFlinger's own touch boost, which also outlives the touch by
153    /// seconds regardless of what the app presents in between.
154    pub fn desired_rate_hz(
155        self,
156        producing_frames: bool,
157        boosted: bool,
158        panel_max_hz: Option<f32>,
159    ) -> f32 {
160        match self {
161            FrameRatePreference::Auto => {
162                if boosted {
163                    panel_max_hz
164                        .filter(|rate| *rate > 0.0)
165                        .unwrap_or(Self::AUTO_QUIET_RATE_HZ)
166                } else if producing_frames {
167                    Self::AUTO_QUIET_RATE_HZ
168                } else {
169                    0.0
170                }
171            }
172            FrameRatePreference::NoPreference => 0.0,
173            FrameRatePreference::Exact(rate) if rate > 0.0 => rate,
174            FrameRatePreference::Exact(_) => 0.0,
175        }
176    }
177}
178
179pub(crate) struct ShellApp {
180    pub(crate) app_context: Rc<cranpose_ui::AppContext>,
181    pub(crate) runtime: StdRuntime,
182    pub(crate) composition: Composition<MemoryApplier>,
183    pub(crate) content: Box<dyn FnMut()>,
184    pub(crate) start_time: Instant,
185    pub(crate) last_frame_time_nanos: u64,
186    pub(crate) semantics_enabled: bool,
187    pub(crate) semantics_snapshot_revision: u64,
188    pub(crate) revealed_focus: Option<NodeId>,
189    pub(crate) layout_requested: bool,
190    pub(crate) content_moved: bool,
191    pub(crate) force_layout_pass: bool,
192    pub(crate) modifiers: Option<Modifiers>,
193    pub(crate) rotary_scroll_factor: f32,
194    #[cfg(all(feature = "clipboard-native", target_os = "linux"))]
195    pub(crate) clipboard: Option<arboard::Clipboard>,
196    pub(crate) dev_options: DevOptions,
197    pub(crate) inspector_projector: Option<inspector::InspectorProjector>,
198    pub(crate) fps_monitor: fps_monitor::FpsMonitor,
199    pub(crate) text_input_routes: Rc<RefCell<TextInputRoutes>>,
200    pub(crate) text_input_router_installed: bool,
201    pub(crate) window_roots_seen: Option<u64>,
202    /// Frames with a rebuilt scene since draw observations were last pruned.
203    pub(crate) rebuilt_frames_since_observation_prune: u32,
204}
205
206/// The application: one runtime, one composition, and a surface per window
207/// it shows.
208///
209/// Methods that name no root act on the primary surface, so a platform with
210/// one window uses the shell as it always has. A platform showing more
211/// windows reaches the others through [`AppShell::surface`], after giving
212/// each window root a renderer with [`AppShell::add_window_surface`].
213pub struct AppShell<R>
214where
215    R: Renderer,
216{
217    pub(crate) app: ShellApp,
218    pub(crate) surfaces: Vec<RootSurface<R>>,
219}
220
221#[derive(Clone, Copy, Debug, PartialEq, Eq)]
222/// Platform and animation-clock timestamps for one pointer sample.
223pub struct PointerEventTime {
224    /// Timestamp supplied by the platform, in its millisecond clock domain.
225    pub platform_time_ms: Option<i64>,
226    /// Timestamp in the animation frame-clock domain.
227    pub animation_time_nanos: u64,
228}
229
230fn update_stage_telemetry_threshold_ms() -> Option<f64> {
231    static THRESHOLD_MS: std::sync::OnceLock<Option<f64>> = std::sync::OnceLock::new();
232    *THRESHOLD_MS.get_or_init(|| {
233        std::env::var("CRANPOSE_UPDATE_STAGE_TELEMETRY_MS")
234            .ok()
235            .and_then(|value| value.parse::<f64>().ok())
236            .filter(|value| value.is_finite() && *value >= 0.0)
237    })
238}
239
240#[derive(Clone, Copy, Debug)]
241struct UpdateStageTelemetry {
242    started_at: Instant,
243    after_frame_callbacks: Instant,
244    after_ui_drain: Instant,
245    after_reconcile: Instant,
246    after_process_frame: Instant,
247    should_render: bool,
248    reconcile_attempted: bool,
249    reconcile_changed: bool,
250}
251
252fn log_update_stage_telemetry(telemetry: UpdateStageTelemetry) {
253    let Some(threshold_ms) = update_stage_telemetry_threshold_ms() else {
254        return;
255    };
256    let total_ms = telemetry
257        .after_process_frame
258        .duration_since(telemetry.started_at)
259        .as_secs_f64()
260        * 1000.0;
261    if total_ms < threshold_ms {
262        return;
263    }
264
265    let frame_callbacks_ms = telemetry
266        .after_frame_callbacks
267        .duration_since(telemetry.started_at)
268        .as_secs_f64()
269        * 1000.0;
270    let ui_drain_ms = telemetry
271        .after_ui_drain
272        .duration_since(telemetry.after_frame_callbacks)
273        .as_secs_f64()
274        * 1000.0;
275    let reconcile_ms = telemetry
276        .after_reconcile
277        .duration_since(telemetry.after_ui_drain)
278        .as_secs_f64()
279        * 1000.0;
280    let process_frame_ms = telemetry
281        .after_process_frame
282        .duration_since(telemetry.after_reconcile)
283        .as_secs_f64()
284        * 1000.0;
285    eprintln!(
286        "[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={}",
287        telemetry.should_render, telemetry.reconcile_attempted, telemetry.reconcile_changed
288    );
289}
290
291#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
292pub enum FramePacingMode {
293    /// Pace frames to the display refresh interval. The production default:
294    /// animations advance once per vsync instead of re-rendering uncapped.
295    #[default]
296    Vsync,
297    Hard60,
298    Hard120,
299    /// Render as fast as possible. For perf harnesses and robot drivers that
300    /// measure work throughput; saturates the GPU if used in a real app.
301    NoVsync,
302}
303
304impl FramePacingMode {
305    pub const ALL: [Self; 4] = [Self::Vsync, Self::Hard60, Self::Hard120, Self::NoVsync];
306
307    pub fn label(self) -> &'static str {
308        match self {
309            Self::Vsync => "VSync",
310            Self::Hard60 => "60fps",
311            Self::Hard120 => "120fps",
312            Self::NoVsync => "NoVSync",
313        }
314    }
315
316    pub fn target_fps(self) -> Option<u32> {
317        match self {
318            Self::Hard60 => Some(60),
319            Self::Hard120 => Some(120),
320            Self::Vsync | Self::NoVsync => None,
321        }
322    }
323}
324
325#[derive(Clone, Copy, Debug, PartialEq)]
326pub struct FrameSchedule {
327    pub needs_update: bool,
328    pub needs_frame: bool,
329    pub next_deadline: Option<web_time::Instant>,
330}
331
332#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
333pub struct FrameUpdateResult {
334    pub visual_changed: bool,
335    pub structure_changed: bool,
336    /// Whether this frame's layout moved or resized a node: content in
337    /// motion, such as a scroll or a size animation. Compose votes its high
338    /// frame-rate category on exactly these changes, so the platforms boost
339    /// the display rate on them the way they do for input.
340    pub content_moved: bool,
341    /// Whether this frame drew new content rather than presenting the scene
342    /// it had: something drew, moved or changed, so the scene was rebuilt.
343    pub content_redrawn: bool,
344}
345
346pub trait PlatformFrameDriver {
347    fn request_frame(&self);
348    fn request_wake_at(&self, deadline: web_time::Instant);
349    fn clear_wake(&self);
350}
351
352#[derive(Debug)]
353pub struct FrameScheduler {
354    update_pending: AtomicBool,
355    frame_pending: AtomicBool,
356    next_deadline: Mutex<Option<web_time::Instant>>,
357}
358
359impl Default for FrameScheduler {
360    fn default() -> Self {
361        Self {
362            update_pending: AtomicBool::new(false),
363            frame_pending: AtomicBool::new(false),
364            next_deadline: Mutex::new(None),
365        }
366    }
367}
368
369impl FrameScheduler {
370    fn lock_deadline(&self) -> MutexGuard<'_, Option<web_time::Instant>> {
371        self.next_deadline
372            .lock()
373            .unwrap_or_else(PoisonError::into_inner)
374    }
375
376    pub fn record(&self, schedule: FrameSchedule) {
377        self.update_pending
378            .store(schedule.needs_update, Ordering::SeqCst);
379        self.frame_pending
380            .store(schedule.needs_frame, Ordering::SeqCst);
381        let mut next_deadline = self.lock_deadline();
382        *next_deadline = if schedule.needs_update {
383            None
384        } else {
385            schedule.next_deadline
386        };
387    }
388
389    pub fn schedule<D>(&self, schedule: FrameSchedule, driver: &D)
390    where
391        D: PlatformFrameDriver + ?Sized,
392    {
393        self.record(schedule);
394        schedule.apply_to(driver);
395    }
396
397    pub fn snapshot(&self) -> FrameSchedule {
398        FrameSchedule {
399            needs_update: self.update_pending.load(Ordering::SeqCst),
400            needs_frame: self.frame_pending.load(Ordering::SeqCst),
401            next_deadline: *self.lock_deadline(),
402        }
403    }
404}
405
406impl FrameSchedule {
407    pub fn apply_to<D>(self, driver: &D)
408    where
409        D: PlatformFrameDriver + ?Sized,
410    {
411        if self.needs_frame {
412            driver.clear_wake();
413            driver.request_frame();
414        } else if self.needs_update {
415            driver.request_wake_at(web_time::Instant::now());
416        } else if let Some(deadline) = self.next_deadline {
417            driver.request_wake_at(deadline);
418        } else {
419            driver.clear_wake();
420        }
421    }
422}
423
424#[derive(Clone, Copy, Debug)]
425pub(crate) struct DevOverlayControl {
426    bounds: Rect,
427    mode: FramePacingMode,
428}
429
430/// Development options for debugging and performance monitoring.
431///
432/// These are rendered directly by the renderer (not via composition)
433/// to avoid affecting performance measurements.
434#[derive(Clone, Debug, Default)]
435pub struct DevOptions {
436    /// Show FPS counter overlay
437    pub fps_counter: bool,
438    /// Show recomposition count
439    pub recomposition_counter: bool,
440    /// Show layout timing breakdown
441    pub layout_timing: bool,
442    pub frame_pacing_controls: bool,
443    pub frame_pacing_mode: FramePacingMode,
444}
445
446#[cfg(any(test, feature = "test-support"))]
447#[doc(hidden)]
448#[derive(Clone, Copy, Debug)]
449pub struct RuntimeLeakDebugStats {
450    pub applier_stats: MemoryApplierDebugStats,
451    pub live_node_heap_bytes: usize,
452    pub recycled_node_heap_bytes: usize,
453    pub slot_table_heap_bytes: usize,
454    pub pass_stats: CompositionPassDebugStats,
455    pub slot_stats: SlotTableDebugStats,
456    pub observer_stats: SnapshotStateObserverDebugStats,
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    pub fn set_viewport(&mut self, width: f32, height: f32) {
975        self.primary().set_viewport(width, height);
976        self.process_frame();
977    }
978
979    pub fn viewport_size(&self) -> (f32, f32) {
980        self.surfaces[0].viewport
981    }
982
983    /// Tells the shell where the primary window sits on the screen. See
984    /// [`SurfaceMut::set_screen_origin`].
985    pub fn set_screen_origin(&mut self, origin: Option<cranpose_ui_graphics::Point>) {
986        self.surfaces[0].screen_origin = origin;
987    }
988
989    pub fn set_buffer_size(&mut self, width: u32, height: u32) {
990        self.surfaces[0].buffer_size = (width, height);
991    }
992
993    pub fn buffer_size(&self) -> (u32, u32) {
994        self.surfaces[0].buffer_size
995    }
996
997    pub fn scene(&self) -> &R::Scene {
998        self.surfaces[0].renderer.scene()
999    }
1000
1001    pub fn renderer(&mut self) -> &mut R {
1002        &mut self.surfaces[0].renderer
1003    }
1004
1005    #[cfg(not(target_arch = "wasm32"))]
1006    pub fn set_frame_waker(&mut self, waker: impl Fn() + Send + Sync + 'static) {
1007        self.app.runtime.set_frame_waker(waker);
1008    }
1009
1010    #[cfg(target_arch = "wasm32")]
1011    pub fn set_frame_waker(&mut self, waker: impl Fn() + 'static) {
1012        self.app.runtime.set_frame_waker(waker);
1013    }
1014
1015    pub fn clear_frame_waker(&mut self) {
1016        self.app.runtime.clear_frame_waker();
1017    }
1018
1019    pub fn should_render(&self) -> bool {
1020        let app_context = Rc::clone(&self.app.app_context);
1021        app_context.enter(|| {
1022            self.app.wants_frame_in_context()
1023                || self.surfaces.iter().any(|surface| surface.scene_dirty)
1024        })
1025    }
1026
1027    pub fn needs_update(&self) -> bool {
1028        let app_context = Rc::clone(&self.app.app_context);
1029        app_context.enter(|| {
1030            self.app
1031                .needs_ui_update_in_context(self.any_surface_dirty())
1032        })
1033    }
1034
1035    /// Returns whether queued UI, state, layout, semantics, or due cursor work can be processed
1036    /// without advancing the frame clock. Awaiting a display frame alone is false.
1037    pub fn needs_update_without_frame(&self) -> bool {
1038        let app_context = Rc::clone(&self.app.app_context);
1039        app_context.enter(|| {
1040            self.any_surface_dirty()
1041                || self.app.has_stale_work_in_context()
1042                || self.app.composition.should_recompose()
1043                || self.app.composition.runtime_handle().has_pending_ui()
1044                || has_pending_semantics_invalidations()
1045                || cranpose_ui::next_cursor_blink_time().is_some_and(|at| at <= Instant::now())
1046                || self
1047                    .surfaces
1048                    .iter()
1049                    .any(|surface| surface.renderer_warmup_due(&self.app))
1050        })
1051    }
1052
1053    /// Returns true when the runtime holds work for the UI thread: posted tasks,
1054    /// continuations from worker threads, or async tasks ready to poll.
1055    ///
1056    /// This is the part of [`needs_update`](Self::needs_update) that another
1057    /// thread is waiting on, told apart from the part that only wants the screen
1058    /// redrawn. A platform backend running with no surface uses it to compose
1059    /// for work and stay asleep for animation.
1060    pub fn has_pending_ui(&self) -> bool {
1061        let app_context = Rc::clone(&self.app.app_context);
1062        app_context.enter(|| self.app.composition.runtime_handle().has_pending_ui())
1063    }
1064
1065    /// Runs the tasks woken since they last ran, now rather than at the next
1066    /// frame. A coroutine whose `delay` ran out resumes when its timer fires,
1067    /// as Compose's main dispatcher resumes one, and the next frame draws what
1068    /// it changed. Waiting for the frame instead would resume a 16 ms delay
1069    /// only every other frame, whenever the timer fires just after one starts.
1070    /// A platform calls this whenever its loop wakes.
1071    pub fn run_pending_tasks(&mut self) {
1072        let app_context = Rc::clone(&self.app.app_context);
1073        app_context.enter(|| {
1074            let runtime_handle = self.app.composition.runtime_handle();
1075            if runtime_handle.has_pending_ui() {
1076                runtime_handle.with_deferred_state_releases(|| runtime_handle.drain_ui());
1077            }
1078        });
1079    }
1080
1081    /// Returns true if the primary surface owes the display a frame: stale
1082    /// pixels, or a renderer that has not warmed its swapchain yet.
1083    ///
1084    /// An app that merely holds an open `next_frame()` await - a game loop, a
1085    /// polling effect - keeps [`Self::needs_update`] true forever without
1086    /// changing a single pixel. Such an app must still be *ticked* every frame,
1087    /// but the frame it produces is byte-identical to the last one, and
1088    /// presenting it costs a full swapchain rotation and pins the panel at its
1089    /// maximum refresh rate. Callers pair this with
1090    /// [`FrameUpdateResult::visual_changed`] from the update they just ran,
1091    /// which reports the work that update actually did.
1092    /// Note: Cursor blink is now timer-based and uses WaitUntil scheduling, not continuous redraw.
1093    pub fn needs_redraw(&self) -> bool {
1094        let app_context = Rc::clone(&self.app.app_context);
1095        app_context.enter(|| self.surfaces[0].needs_redraw_in_context(&self.app))
1096    }
1097
1098    /// Marks the primary surface as dirty, indicating a redraw is needed.
1099    pub fn mark_dirty(&mut self) {
1100        self.surfaces[0].is_dirty = true;
1101    }
1102
1103    pub fn request_root_render(&mut self) {
1104        self.app.composition.request_root_render();
1105        self.app.request_forced_layout_pass();
1106        let app_context = Rc::clone(&self.app.app_context);
1107        app_context.enter(request_render_invalidation);
1108        self.mark_all_dirty();
1109    }
1110
1111    pub fn set_density(&mut self, density: f32) {
1112        let app_context = Rc::clone(&self.app.app_context);
1113        let changed = app_context.enter(|| {
1114            let previous = cranpose_ui::current_density().to_bits();
1115            cranpose_ui::set_density(density);
1116            previous != cranpose_ui::current_density().to_bits()
1117        });
1118        if changed {
1119            self.request_root_render();
1120        }
1121    }
1122
1123    /// Reports the system font scale the platform is showing text at.
1124    ///
1125    /// Hosts call this at startup and on every configuration change. Sizes in
1126    /// `Sp` follow it, sizes in `Dp` do not, which is what lets an app grow its
1127    /// text with the user's setting while its layout stays where it was.
1128    ///
1129    /// This takes the setting as a plain multiplier. A host whose platform
1130    /// converts `Sp` through a table of its own — Android 14 and up does — calls
1131    /// [`AppShell::set_font_scale_curve`] with what the platform answered
1132    /// instead, because the multiplication is not what that platform does.
1133    pub fn set_font_scale(&mut self, font_scale: f32) {
1134        self.set_font_scale_curve(cranpose_ui::FontScaleCurve::linear(font_scale));
1135    }
1136
1137    /// Reports the system font scale together with the conversion behind it.
1138    ///
1139    /// See [`cranpose_ui::font_scale`]: above a threshold setting Android
1140    /// resolves a size in `Sp` through a piecewise-linear table rather than by
1141    /// multiplying, so a host that can read that table hands it over here and
1142    /// every `Sp` in the app resolves the way the platform's own text does.
1143    pub fn set_font_scale_curve(&mut self, curve: cranpose_ui::FontScaleCurve) {
1144        let app_context = Rc::clone(&self.app.app_context);
1145        let changed = app_context.enter(|| {
1146            let previous = cranpose_ui::current_font_scale_curve();
1147            cranpose_ui::set_font_scale_curve(curve);
1148            previous != cranpose_ui::current_font_scale_curve()
1149        });
1150        if changed {
1151            self.request_root_render();
1152        }
1153    }
1154
1155    #[cfg(any(test, feature = "test-support"))]
1156    #[doc(hidden)]
1157    pub fn debug_current_density(&self) -> f32 {
1158        let app_context = Rc::clone(&self.app.app_context);
1159        app_context.enter(cranpose_ui::current_density)
1160    }
1161
1162    #[cfg(any(test, feature = "test-support"))]
1163    #[doc(hidden)]
1164    pub fn debug_current_font_scale(&self) -> f32 {
1165        let app_context = Rc::clone(&self.app.app_context);
1166        app_context.enter(cranpose_ui::current_font_scale)
1167    }
1168
1169    #[cfg(any(test, feature = "test-support"))]
1170    #[doc(hidden)]
1171    pub fn debug_current_font_scale_curve(&self) -> cranpose_ui::FontScaleCurve {
1172        let app_context = Rc::clone(&self.app.app_context);
1173        app_context.enter(cranpose_ui::current_font_scale_curve)
1174    }
1175
1176    #[cfg(any(test, feature = "test-support"))]
1177    #[doc(hidden)]
1178    pub fn debug_enter_app_context<T>(&self, block: impl FnOnce() -> T) -> T {
1179        let app_context = Rc::clone(&self.app.app_context);
1180        app_context.enter(block)
1181    }
1182
1183    /// Returns true if there are active animations or pending recompositions.
1184    pub fn has_active_animations(&self) -> bool {
1185        self.app.composition.should_render()
1186    }
1187
1188    pub fn has_transient_frame_callbacks(&self) -> bool {
1189        self.app
1190            .composition
1191            .runtime_handle()
1192            .has_transient_frame_callbacks()
1193    }
1194
1195    pub fn has_active_pointer_gesture(&self) -> bool {
1196        self.surfaces[0].has_active_pointer_gesture()
1197    }
1198
1199    /// Primary-surface form of [`SurfaceMut::frame_owed`].
1200    pub fn frame_owed(&self) -> bool {
1201        self.surfaces[0].frame_owed
1202    }
1203
1204    /// Primary-surface form of [`SurfaceMut::take_frame_owed`].
1205    pub fn take_frame_owed(&mut self) -> bool {
1206        std::mem::take(&mut self.surfaces[0].frame_owed)
1207    }
1208
1209    /// Returns the next scheduled event time for cursor blink.
1210    /// Use this for `ControlFlow::WaitUntil` scheduling.
1211    pub fn next_event_time(&self) -> Option<web_time::Instant> {
1212        self.app.next_event_time()
1213    }
1214
1215    fn compute_frame_schedule(&self) -> FrameSchedule {
1216        self.surfaces[0].compute_frame_schedule(&self.app, self.any_surface_dirty())
1217    }
1218
1219    pub fn frame_schedule(&self) -> FrameSchedule {
1220        let schedule = self.compute_frame_schedule();
1221        self.surfaces[0].frame_scheduler.record(schedule);
1222        schedule
1223    }
1224
1225    pub fn schedule_platform_frame<D>(&self, driver: &D) -> FrameSchedule
1226    where
1227        D: PlatformFrameDriver + ?Sized,
1228    {
1229        let schedule = self.compute_frame_schedule();
1230        self.surfaces[0].frame_scheduler.schedule(schedule, driver);
1231        schedule
1232    }
1233
1234    pub fn frame_scheduler_snapshot(&self) -> FrameSchedule {
1235        self.surfaces[0].frame_scheduler.snapshot()
1236    }
1237
1238    /// Timestamp a live input sample against the current animation clock.
1239    pub fn realtime_pointer_event_time(&self, platform_time_ms: Option<i64>) -> PointerEventTime {
1240        self.app.realtime_pointer_event_time(platform_time_ms)
1241    }
1242
1243    /// Timestamp deterministic input at the most recently processed frame.
1244    pub fn exact_pointer_event_time(&self, platform_time_ms: Option<i64>) -> PointerEventTime {
1245        PointerEventTime {
1246            platform_time_ms,
1247            animation_time_nanos: self.app.last_frame_time_nanos,
1248        }
1249    }
1250
1251    pub fn update_after_frame_interval(
1252        &mut self,
1253        frame_interval: std::time::Duration,
1254    ) -> FrameUpdateResult {
1255        let wall_frame_time = self.app.frame_time_nanos_at(Instant::now());
1256        let base_frame_time = self.app.last_frame_time_nanos.max(wall_frame_time);
1257        let frame_time = base_frame_time
1258            .saturating_add(frame_interval.as_nanos().min(u128::from(u64::MAX)) as u64);
1259        self.update_at_frame_time_nanos(frame_time)
1260    }
1261
1262    /// Advance the frame clock by EXACTLY `frame_interval` past the last
1263    /// frame — no wall anchoring — and run one update there. Robot keyframe
1264    /// captures ride this to sample animations deterministically: while the
1265    /// advanced clock is ahead of wall time, interleaved wall-clocked
1266    /// updates clamp to it (dt 0) instead of fast-forwarding animations.
1267    pub fn update_after_exact_interval(
1268        &mut self,
1269        frame_interval: std::time::Duration,
1270    ) -> FrameUpdateResult {
1271        let frame_time = self
1272            .app
1273            .last_frame_time_nanos
1274            .saturating_add(frame_interval.as_nanos().min(u128::from(u64::MAX)) as u64);
1275        self.update_at_frame_time_nanos(frame_time)
1276    }
1277
1278    /// Delivers a display frame at a monotonic platform instant, then runs the
1279    /// continuations it wakes. This is independent of renderer availability.
1280    /// The instant is normalized to the shell's start, sharing the input clock's epoch.
1281    /// Repeated or older frame timestamps do not wake frame awaiters again.
1282    /// Use [`Self::update_without_frame`] to compose and draw the resulting state.
1283    pub fn dispatch_frame_at(&mut self, frame_time: Instant) {
1284        let frame_time = self.app.frame_time_nanos_at(frame_time);
1285        let app_context = Rc::clone(&self.app.app_context);
1286        app_context.enter(|| {
1287            let runtime_handle = self.app.runtime.runtime_handle();
1288            runtime_handle.with_deferred_state_releases(|| {
1289                self.app.last_frame_time_nanos = frame_time.max(self.app.last_frame_time_nanos);
1290                self.app
1291                    .runtime
1292                    .drain_frame_callbacks(self.app.last_frame_time_nanos);
1293                runtime_handle.drain_ui();
1294                self.dispatch_requested_mouse_moves(self.app.last_frame_time_nanos);
1295            });
1296        });
1297    }
1298
1299    /// Processes pending state, input, layout, drawing, and semantics work without
1300    /// waking frame awaiters. Platforms use this for work between display frames.
1301    pub fn update_without_frame(&mut self) -> FrameUpdateResult {
1302        self.update_with_frame_time(None)
1303    }
1304
1305    /// Processes one update at a frame timestamp in nanoseconds since this shell
1306    /// started. Duplicate or older timestamps process UI work without delivering
1307    /// another frame callback.
1308    pub fn update_at_frame_time_nanos(&mut self, frame_time: u64) -> FrameUpdateResult {
1309        self.update_with_frame_time(Some(frame_time))
1310    }
1311
1312    fn update_with_frame_time(&mut self, frame_time: Option<u64>) -> FrameUpdateResult {
1313        let app_context = Rc::clone(&self.app.app_context);
1314        app_context.enter(|| {
1315            let update_started_at = Instant::now();
1316            let runtime_handle = self.app.runtime.runtime_handle();
1317            runtime_handle.with_deferred_state_releases(|| {
1318                if let Some(frame_time) = frame_time {
1319                    self.app.last_frame_time_nanos = frame_time.max(self.app.last_frame_time_nanos);
1320                    self.app.runtime.drain_frame_callbacks(self.app.last_frame_time_nanos);
1321                }
1322                let after_frame_callbacks = Instant::now();
1323                runtime_handle.drain_ui();
1324                self.dispatch_requested_mouse_moves(self.app.last_frame_time_nanos);
1325                let after_ui_drain = Instant::now();
1326                let should_render = self.app.composition.should_recompose();
1327                let mut reconcile_attempted = false;
1328                let mut reconcile_changed = false;
1329                if should_render {
1330                    log::trace!(
1331                        target: "cranpose::input",
1332                        "update begin: should_render=true layout_requested={} scene_dirty={} is_dirty={}",
1333                        self.app.layout_requested,
1334                        self.surfaces[0].scene_dirty,
1335                        self.surfaces[0].is_dirty
1336                    );
1337                    (reconcile_attempted, reconcile_changed) = self.reconcile_in_context();
1338                }
1339                let after_reconcile = Instant::now();
1340                let result = self.process_frame_in_context(reconcile_changed);
1341                let after_process_frame = Instant::now();
1342                log_update_stage_telemetry(UpdateStageTelemetry {
1343                    started_at: update_started_at,
1344                    after_frame_callbacks,
1345                    after_ui_drain,
1346                    after_reconcile,
1347                    after_process_frame,
1348                    should_render,
1349                    reconcile_attempted,
1350                    reconcile_changed,
1351                });
1352                self.clear_surface_dirt();
1353                result
1354            })
1355        })
1356    }
1357
1358    fn dispatch_requested_mouse_moves(&mut self, frame_time: u64) {
1359        use cranpose_ui::mouse_input::MouseInputTarget;
1360        let pending = self.app.app_context.pending_mouse_moves();
1361        for _ in 0..pending {
1362            let Some(request) = self.app.app_context.take_mouse_move() else {
1363                break;
1364            };
1365            let root = match request.target {
1366                MouseInputTarget::Primary => RootId::Primary,
1367                MouseInputTarget::Window(id) => RootId::Window(id),
1368            };
1369            if let Some(mut surface) = self.surface(root) {
1370                surface.set_pointer_source(PointerSource::Mouse);
1371                surface.set_cursor_at_event_time(request.position.x, request.position.y, PointerEventTime {
1372                    platform_time_ms: Some((frame_time / 1_000_000).min(i64::MAX as u64) as i64),
1373                    animation_time_nanos: frame_time,
1374                });
1375            }
1376        }
1377    }
1378
1379    fn reconcile_in_context(&mut self) -> (bool, bool) {
1380        let Some(root_key) = self.app.composition.root_key() else {
1381            return (false, false);
1382        };
1383        match self
1384            .app
1385            .composition
1386            .reconcile(root_key, &mut *self.app.content)
1387        {
1388            Ok(changed) => {
1389                log::trace!(
1390                    target: "cranpose::input",
1391                    "reconcile changed={changed}"
1392                );
1393                if changed {
1394                    self.app.fps_monitor.record_recomposition();
1395                    if self.app.composition_tree_needs_layout() {
1396                        self.app.request_layout_pass();
1397                    }
1398                    request_render_invalidation();
1399                }
1400                (true, changed)
1401            }
1402            Err(NodeError::Missing { id }) => {
1403                log::debug!("Recomposition skipped: node {id} no longer exists");
1404                self.app.request_layout_pass();
1405                request_render_invalidation();
1406                (true, false)
1407            }
1408            Err(err) => {
1409                log::error!("recomposition failed: {err}");
1410                self.app.request_layout_pass();
1411                request_render_invalidation();
1412                (true, false)
1413            }
1414        }
1415    }
1416
1417    pub fn update(&mut self) -> FrameUpdateResult {
1418        let frame_time = self.app.frame_time_nanos_at(Instant::now());
1419        self.update_at_frame_time_nanos(frame_time)
1420    }
1421}
1422
1423impl<R> Drop for AppShell<R>
1424where
1425    R: Renderer,
1426{
1427    fn drop(&mut self) {
1428        self.app.runtime.clear_frame_waker();
1429    }
1430}
1431
1432pub fn default_root_key() -> Key {
1433    location_key(file!(), line!(), column!())
1434}
1435
1436#[cfg(test)]
1437#[path = "tests/app_shell_frame_pacing_tests.rs"]
1438mod frame_pacing_tests;
1439
1440#[cfg(test)]
1441#[path = "tests/app_shell_tests.rs"]
1442mod tests;
1443
1444#[cfg(test)]
1445#[path = "tests/surface_tests.rs"]
1446mod surface_tests;