Skip to main content

cranpose_app_shell/
lib.rs

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