Skip to main content

cranpose_app_shell/
lib.rs

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