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