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