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