Skip to main content

cranpose_app_shell/
lib.rs

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