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