Skip to main content

cranpose_app_shell/
lib.rs

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