Skip to main content

cranpose_app_shell/
lib.rs

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