Skip to main content

cranpose_app_shell/
lib.rs

1#![deny(unsafe_code)]
2#![allow(clippy::type_complexity)]
3
4mod fps_monitor;
5mod hit_path_tracker;
6mod shell_debug;
7mod shell_frame;
8mod shell_input;
9#[cfg(test)]
10use shell_frame::build_draw_refresh_scope;
11
12pub use fps_monitor::FpsStats;
13
14use std::fmt::{Debug, Write};
15use std::rc::Rc;
16use std::sync::{
17    atomic::{AtomicBool, Ordering},
18    Mutex, MutexGuard,
19};
20// Use web_time for cross-platform time support (native + WASM) - compatible with winit
21use web_time::Instant;
22
23use cranpose_core::{
24    enter_event_handler_scope, location_key, run_in_mutable_snapshot, Applier, Composition, Key,
25    MemoryApplier, NodeError, NodeId,
26};
27use cranpose_foundation::{PointerButton, PointerButtons, PointerEvent, PointerEventKind};
28use cranpose_render_common::{HitTestTarget, RenderScene, Renderer};
29use cranpose_runtime_std::StdRuntime;
30use cranpose_ui::{
31    clear_transient_scroll_motion_contexts, format_layout_tree, format_render_scene,
32    format_screen_summary, has_pending_focus_invalidations, has_pending_pointer_repasses,
33    peek_focus_invalidation, peek_layout_invalidation, peek_pointer_invalidation,
34    peek_render_invalidation, process_focus_invalidations, process_pointer_repasses,
35    request_render_invalidation, take_draw_repass_nodes, take_focus_invalidation,
36    take_layout_invalidation, take_pointer_invalidation, take_render_invalidation,
37    HeadlessRenderer, LayoutBox, LayoutNode, LayoutTree, MeasureLayoutOptions, SemanticsTree,
38    SubcomposeLayoutNode,
39};
40use cranpose_ui_graphics::{Point, Rect, Size};
41use hit_path_tracker::{HitPathTracker, PointerId};
42use std::collections::HashSet;
43
44// Re-export key event types for use by cranpose
45pub use cranpose_ui::{KeyCode, KeyEvent, KeyEventType, Modifiers};
46// Re-export the pointer device source so platform backends can stamp it.
47pub use cranpose_foundation::PointerSource;
48
49/// Bridges the in-tree selection menu's clipboard actions to the desktop OS
50/// clipboard (`arboard`). Holds a persistent clipboard handle (Linux X11 loses
51/// clipboard contents when the last owning handle drops), shared behind an
52/// `Rc<RefCell<..>>` so it stays alive for the app-context's lifetime.
53#[cfg(all(
54    feature = "clipboard-native",
55    not(target_arch = "wasm32"),
56    not(target_os = "android"),
57    not(target_os = "ios")
58))]
59struct ShellClipboard {
60    inner: std::rc::Rc<std::cell::RefCell<Option<arboard::Clipboard>>>,
61}
62
63#[cfg(all(
64    feature = "clipboard-native",
65    not(target_arch = "wasm32"),
66    not(target_os = "android"),
67    not(target_os = "ios")
68))]
69impl cranpose_ui::clipboard_session::PlatformClipboard for ShellClipboard {
70    fn write_text(&self, text: &str) {
71        if let Some(clipboard) = self.inner.borrow_mut().as_mut() {
72            let _ = clipboard.set_text(text);
73        }
74    }
75
76    fn read_text(&self) -> Option<String> {
77        self.inner
78            .borrow_mut()
79            .as_mut()
80            .and_then(|clipboard| clipboard.get_text().ok())
81    }
82}
83// Re-export the platform soft-keyboard hook so runtimes only depend on the shell
84pub use cranpose_ui::PlatformTextInputHandler;
85// Re-export the IME editable-state snapshot for platform text-input bridges
86pub use cranpose_ui::ImeEditorState;
87
88#[cfg(any(test, feature = "test-support"))]
89use cranpose_core::{
90    debug_recompose_scope_registry_stats, MemoryApplierDebugStats,
91    RecomposeScopeRegistryDebugStats, SlotTableDebugStats,
92};
93#[cfg(any(test, feature = "test-support"))]
94use cranpose_core::{
95    runtime::{RuntimeDebugStats, StateArenaDebugStats},
96    snapshot_pinning::{debug_snapshot_pinning_stats, SnapshotPinningDebugStats},
97    snapshot_state_observer::SnapshotStateObserverDebugStats,
98    snapshot_v2::{debug_snapshot_v2_stats, SnapshotV2DebugStats},
99    CompositionPassDebugStats, SlotId,
100};
101
102pub struct AppShell<R>
103where
104    R: Renderer,
105{
106    app_context: Rc<cranpose_ui::AppContext>,
107    runtime: StdRuntime,
108    composition: Composition<MemoryApplier>,
109    content: Box<dyn FnMut()>,
110    renderer: R,
111    cursor: (f32, f32),
112    viewport: (f32, f32),
113    buffer_size: (u32, u32),
114    start_time: Instant,
115    last_frame_time_nanos: u64,
116    layout_tree: Option<LayoutTree>,
117    semantics_tree: Option<SemanticsTree>,
118    semantics_enabled: bool,
119    layout_requested: bool,
120    force_layout_pass: bool,
121    scene_dirty: bool,
122    scoped_layout_scene_nodes: Vec<NodeId>,
123    is_dirty: bool,
124    /// Tracks which mouse buttons are currently pressed
125    buttons_pressed: PointerButtons,
126    /// Device source (touch/mouse/stylus) of the most recent pointer sample,
127    /// set by the platform before dispatching and stamped onto every
128    /// `PointerEvent` the shell constructs. The pointer model is stateful
129    /// (`set_cursor` then `pointer_pressed`), so a single per-shell cell mirrors
130    /// the existing cursor/buttons state without churning every method signature.
131    pointer_source: PointerSource,
132    /// Tracks which nodes were hit on PointerDown (by stable NodeId).
133    ///
134    /// This follows Jetpack Compose's HitPathTracker pattern:
135    /// - On Down: cache NodeIds, not geometry
136    /// - On Move/Up/Cancel: resolve fresh HitTargets from current scene
137    /// - Handler closures are preserved (same Rc), so internal state survives
138    hit_path_tracker: HitPathTracker,
139    /// Tracks which nodes the pointer is currently hovering over.
140    /// Used to synthesize Enter/Exit events when the hover set changes.
141    hovered_nodes: Vec<NodeId>,
142    /// Persistent clipboard for desktop (Linux X11 requires clipboard to stay alive)
143    #[cfg(all(feature = "clipboard-native", target_os = "linux"))]
144    clipboard: Option<arboard::Clipboard>,
145    /// Dev options for debugging and performance monitoring
146    dev_options: DevOptions,
147    dev_overlay_controls: Vec<DevOverlayControl>,
148    dev_overlay_text: String,
149    dev_overlay_last_refresh: Option<Instant>,
150    dev_overlay_viewport: Option<Size>,
151    fps_monitor: fps_monitor::FpsMonitor,
152    frame_scheduler: FrameScheduler,
153}
154
155#[derive(Clone, Copy, Debug, PartialEq, Eq)]
156/// Platform and animation-clock timestamps for one pointer sample.
157pub struct PointerEventTime {
158    /// Timestamp supplied by the platform, in its millisecond clock domain.
159    pub platform_time_ms: Option<i64>,
160    /// Timestamp in the animation frame-clock domain.
161    pub animation_time_nanos: u64,
162}
163
164fn update_stage_telemetry_threshold_ms() -> Option<f64> {
165    static THRESHOLD_MS: std::sync::OnceLock<Option<f64>> = std::sync::OnceLock::new();
166    *THRESHOLD_MS.get_or_init(|| {
167        std::env::var("CRANPOSE_UPDATE_STAGE_TELEMETRY_MS")
168            .ok()
169            .and_then(|value| value.parse::<f64>().ok())
170            .filter(|value| value.is_finite() && *value >= 0.0)
171    })
172}
173
174#[derive(Clone, Copy, Debug)]
175struct UpdateStageTelemetry {
176    started_at: Instant,
177    after_frame_callbacks: Instant,
178    after_ui_drain: Instant,
179    after_reconcile: Instant,
180    after_process_frame: Instant,
181    should_render: bool,
182    reconcile_attempted: bool,
183    reconcile_changed: bool,
184}
185
186fn log_update_stage_telemetry(telemetry: UpdateStageTelemetry) {
187    let Some(threshold_ms) = update_stage_telemetry_threshold_ms() else {
188        return;
189    };
190    let total_ms = telemetry
191        .after_process_frame
192        .duration_since(telemetry.started_at)
193        .as_secs_f64()
194        * 1000.0;
195    if total_ms < threshold_ms {
196        return;
197    }
198
199    let frame_callbacks_ms = telemetry
200        .after_frame_callbacks
201        .duration_since(telemetry.started_at)
202        .as_secs_f64()
203        * 1000.0;
204    let ui_drain_ms = telemetry
205        .after_ui_drain
206        .duration_since(telemetry.after_frame_callbacks)
207        .as_secs_f64()
208        * 1000.0;
209    let reconcile_ms = telemetry
210        .after_reconcile
211        .duration_since(telemetry.after_ui_drain)
212        .as_secs_f64()
213        * 1000.0;
214    let process_frame_ms = telemetry
215        .after_process_frame
216        .duration_since(telemetry.after_reconcile)
217        .as_secs_f64()
218        * 1000.0;
219    eprintln!(
220        "[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={}",
221        telemetry.should_render,
222        telemetry.reconcile_attempted,
223        telemetry.reconcile_changed
224    );
225}
226
227#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
228pub enum FramePacingMode {
229    /// Pace frames to the display refresh interval. The production default:
230    /// animations advance once per vsync instead of re-rendering uncapped.
231    #[default]
232    Vsync,
233    Hard60,
234    Hard120,
235    /// Render as fast as possible. For perf harnesses and robot drivers that
236    /// measure work throughput; saturates the GPU if used in a real app.
237    NoVsync,
238}
239
240impl FramePacingMode {
241    pub const ALL: [Self; 4] = [Self::Vsync, Self::Hard60, Self::Hard120, Self::NoVsync];
242
243    pub fn label(self) -> &'static str {
244        match self {
245            Self::Vsync => "VSync",
246            Self::Hard60 => "60fps",
247            Self::Hard120 => "120fps",
248            Self::NoVsync => "NoVSync",
249        }
250    }
251
252    pub fn target_fps(self) -> Option<u32> {
253        match self {
254            Self::Hard60 => Some(60),
255            Self::Hard120 => Some(120),
256            Self::Vsync | Self::NoVsync => None,
257        }
258    }
259}
260
261#[derive(Clone, Copy, Debug, PartialEq)]
262pub struct FrameSchedule {
263    pub needs_update: bool,
264    pub needs_frame: bool,
265    pub next_deadline: Option<web_time::Instant>,
266}
267
268#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
269pub struct FrameUpdateResult {
270    pub visual_changed: bool,
271    pub structure_changed: bool,
272}
273
274pub trait PlatformFrameDriver {
275    fn request_frame(&self);
276    fn request_wake_at(&self, deadline: web_time::Instant);
277    fn clear_wake(&self);
278}
279
280#[derive(Debug)]
281pub struct FrameScheduler {
282    update_pending: AtomicBool,
283    frame_pending: AtomicBool,
284    next_deadline: Mutex<Option<web_time::Instant>>,
285}
286
287impl Default for FrameScheduler {
288    fn default() -> Self {
289        Self {
290            update_pending: AtomicBool::new(false),
291            frame_pending: AtomicBool::new(false),
292            next_deadline: Mutex::new(None),
293        }
294    }
295}
296
297impl FrameScheduler {
298    fn lock_deadline(&self) -> MutexGuard<'_, Option<web_time::Instant>> {
299        self.next_deadline
300            .lock()
301            .unwrap_or_else(|poisoned| poisoned.into_inner())
302    }
303
304    pub fn record(&self, schedule: FrameSchedule) {
305        self.update_pending
306            .store(schedule.needs_update, Ordering::SeqCst);
307        self.frame_pending
308            .store(schedule.needs_frame, Ordering::SeqCst);
309        let mut next_deadline = self.lock_deadline();
310        *next_deadline = if schedule.needs_update {
311            None
312        } else {
313            schedule.next_deadline
314        };
315    }
316
317    pub fn schedule<D>(&self, schedule: FrameSchedule, driver: &D)
318    where
319        D: PlatformFrameDriver + ?Sized,
320    {
321        self.record(schedule);
322        schedule.apply_to(driver);
323    }
324
325    pub fn snapshot(&self) -> FrameSchedule {
326        FrameSchedule {
327            needs_update: self.update_pending.load(Ordering::SeqCst),
328            needs_frame: self.frame_pending.load(Ordering::SeqCst),
329            next_deadline: *self.lock_deadline(),
330        }
331    }
332}
333
334impl FrameSchedule {
335    pub fn apply_to<D>(self, driver: &D)
336    where
337        D: PlatformFrameDriver + ?Sized,
338    {
339        if self.needs_frame {
340            driver.clear_wake();
341            driver.request_frame();
342        } else if self.needs_update {
343            driver.request_wake_at(web_time::Instant::now());
344        } else if let Some(deadline) = self.next_deadline {
345            driver.request_wake_at(deadline);
346        } else {
347            driver.clear_wake();
348        }
349    }
350}
351
352#[derive(Clone, Copy, Debug)]
353struct DevOverlayControl {
354    bounds: Rect,
355    mode: FramePacingMode,
356}
357
358/// Development options for debugging and performance monitoring.
359///
360/// These are rendered directly by the renderer (not via composition)
361/// to avoid affecting performance measurements.
362#[derive(Clone, Debug, Default)]
363pub struct DevOptions {
364    /// Show FPS counter overlay
365    pub fps_counter: bool,
366    /// Show recomposition count
367    pub recomposition_counter: bool,
368    /// Show layout timing breakdown
369    pub layout_timing: bool,
370    pub frame_pacing_controls: bool,
371    pub frame_pacing_mode: FramePacingMode,
372}
373
374#[cfg(any(test, feature = "test-support"))]
375#[doc(hidden)]
376#[derive(Clone, Copy, Debug)]
377pub struct RuntimeLeakDebugStats {
378    pub applier_stats: MemoryApplierDebugStats,
379    pub live_node_heap_bytes: usize,
380    pub recycled_node_heap_bytes: usize,
381    pub slot_table_heap_bytes: usize,
382    pub pass_stats: CompositionPassDebugStats,
383    pub slot_stats: SlotTableDebugStats,
384    pub observer_stats: SnapshotStateObserverDebugStats,
385    pub runtime_stats: RuntimeDebugStats,
386    pub state_arena_stats: StateArenaDebugStats,
387    pub recompose_scope_stats: RecomposeScopeRegistryDebugStats,
388    pub snapshot_v2_stats: SnapshotV2DebugStats,
389    pub snapshot_pinning_stats: SnapshotPinningDebugStats,
390}
391
392impl<R> AppShell<R>
393where
394    R: Renderer,
395    R::Error: Debug,
396{
397    pub fn new(renderer: R, root_key: Key, content: impl FnMut() + 'static) -> Self {
398        Self::new_with_size(renderer, root_key, content, (800, 600), (800.0, 600.0))
399    }
400
401    pub fn new_with_size(
402        renderer: R,
403        root_key: Key,
404        content: impl FnMut() + 'static,
405        buffer_size: (u32, u32),
406        viewport: (f32, f32),
407    ) -> Self {
408        Self::new_with_size_and_density(renderer, root_key, content, buffer_size, viewport, 1.0)
409    }
410
411    pub fn new_with_size_and_density(
412        mut renderer: R,
413        root_key: Key,
414        content: impl FnMut() + 'static,
415        buffer_size: (u32, u32),
416        viewport: (f32, f32),
417        density: f32,
418    ) -> Self {
419        let app_context = cranpose_ui::AppContext::new_with_density(density);
420        let runtime = StdRuntime::new();
421        let mut composition = Composition::with_runtime(MemoryApplier::new(), runtime.runtime());
422        // Install the top-level overlay layer once, at the root, so every app
423        // gets `Popup`/selection-handle/context-menu support for free and the
424        // overlay is composed (and thus painted and hit-tested) last. The app's
425        // content is called through a shared handle so this wrapper can be
426        // re-created cheaply on every recomposition without moving `content`.
427        let app_content = Rc::new(std::cell::RefCell::new(content));
428        let mut build: Box<dyn FnMut()> = Box::new(move || {
429            let app_content = Rc::clone(&app_content);
430            cranpose_ui::widgets::PopupHost(move || {
431                (app_content.borrow_mut())();
432            });
433        });
434        renderer.attach_app_context_services(&app_context);
435        app_context.enter(|| {
436            // Route the selection menu's Copy/Cut/Paste through the OS clipboard
437            // on desktop; other platforms fall back to the in-process clipboard.
438            #[cfg(all(
439                feature = "clipboard-native",
440                not(target_arch = "wasm32"),
441                not(target_os = "android"),
442                not(target_os = "ios")
443            ))]
444            {
445                let clipboard =
446                    std::rc::Rc::new(std::cell::RefCell::new(arboard::Clipboard::new().ok()));
447                cranpose_ui::clipboard_session::set_platform_clipboard(std::rc::Rc::new(
448                    ShellClipboard { inner: clipboard },
449                ));
450            }
451            if let Err(err) = composition.render_stable(root_key, &mut *build) {
452                log::error!("initial render failed: {err}");
453            }
454        });
455        renderer.scene_mut().clear();
456        let mut shell = Self {
457            app_context,
458            runtime,
459            composition,
460            content: build,
461            renderer,
462            cursor: (0.0, 0.0),
463            viewport,
464            buffer_size,
465            start_time: Instant::now(),
466            last_frame_time_nanos: 0,
467            layout_tree: None,
468            semantics_tree: None,
469            semantics_enabled: false,
470            layout_requested: true,
471            force_layout_pass: true,
472            scene_dirty: true,
473            scoped_layout_scene_nodes: Vec::new(),
474            is_dirty: true,
475            buttons_pressed: PointerButtons::NONE,
476            pointer_source: PointerSource::Unknown,
477            hit_path_tracker: HitPathTracker::new(),
478            hovered_nodes: Vec::new(),
479            #[cfg(all(feature = "clipboard-native", target_os = "linux"))]
480            clipboard: arboard::Clipboard::new().ok(),
481            dev_options: DevOptions::default(),
482            dev_overlay_controls: Vec::new(),
483            dev_overlay_text: String::new(),
484            dev_overlay_last_refresh: None,
485            dev_overlay_viewport: None,
486            fps_monitor: fps_monitor::FpsMonitor::new(),
487            frame_scheduler: FrameScheduler::default(),
488        };
489        shell.process_frame();
490        shell
491    }
492
493    /// The shell's [`AppContext`](cranpose_ui::AppContext). Platform backends
494    /// use it to register per-context services (such as the OS clipboard) that
495    /// need UIKit/JNI access the shell itself does not have: enter the context
496    /// and call the relevant `set_platform_*` installer.
497    pub fn app_context(&self) -> &Rc<cranpose_ui::AppContext> {
498        &self.app_context
499    }
500
501    /// Set development options for debugging and performance monitoring.
502    ///
503    /// The FPS counter and other overlays are rendered directly by the renderer
504    /// (not via composition) to avoid affecting performance measurements.
505    pub fn set_dev_options(&mut self, options: DevOptions) {
506        self.dev_options = options;
507        self.invalidate_dev_overlay_text();
508        let app_context = Rc::clone(&self.app_context);
509        app_context.enter(request_render_invalidation);
510        self.mark_dirty();
511    }
512
513    /// Get a reference to the current dev options.
514    pub fn dev_options(&self) -> &DevOptions {
515        &self.dev_options
516    }
517
518    pub fn frame_pacing_mode(&self) -> FramePacingMode {
519        self.dev_options.frame_pacing_mode
520    }
521
522    pub fn current_fps(&self) -> f32 {
523        self.fps_monitor.current_fps()
524    }
525
526    pub fn fps_stats(&self) -> FpsStats {
527        self.fps_monitor.stats()
528    }
529
530    pub fn reset_fps_stats(&mut self) {
531        self.fps_monitor.reset_stats();
532        self.invalidate_dev_overlay_text();
533    }
534
535    pub fn record_presented_frame(
536        &mut self,
537        frame_started_at: Instant,
538        frame_finished_at: Instant,
539    ) {
540        self.fps_monitor
541            .record_frame_work(frame_started_at, frame_finished_at);
542    }
543
544    #[cfg(any(test, feature = "test-support"))]
545    #[doc(hidden)]
546    pub fn record_presented_frame_for_test(
547        &mut self,
548        frame_started_nanos: u64,
549        frame_finished_nanos: u64,
550    ) {
551        let started = self.start_time + std::time::Duration::from_nanos(frame_started_nanos);
552        let finished = self.start_time + std::time::Duration::from_nanos(frame_finished_nanos);
553        self.record_presented_frame(started, finished);
554    }
555
556    pub fn set_frame_pacing_mode(&mut self, mode: FramePacingMode) {
557        if self.dev_options.frame_pacing_mode == mode {
558            return;
559        }
560        self.dev_options.frame_pacing_mode = mode;
561        self.invalidate_dev_overlay_text();
562        let app_context = Rc::clone(&self.app_context);
563        app_context.enter(request_render_invalidation);
564        self.mark_dirty();
565    }
566
567    pub fn handle_dev_overlay_click(&mut self, x: f32, y: f32) -> Option<FramePacingMode> {
568        if !self.dev_options.frame_pacing_controls {
569            return None;
570        }
571        let mode = self
572            .dev_overlay_controls
573            .iter()
574            .find(|control| control.bounds.contains(x, y))
575            .map(|control| control.mode)?;
576        self.set_frame_pacing_mode(mode);
577        Some(mode)
578    }
579
580    fn invalidate_dev_overlay_text(&mut self) {
581        self.dev_overlay_text.clear();
582        self.dev_overlay_last_refresh = None;
583        self.dev_overlay_viewport = None;
584    }
585
586    pub fn set_viewport(&mut self, width: f32, height: f32) {
587        self.viewport = (width, height);
588        self.request_forced_layout_pass();
589        self.mark_dirty();
590        self.process_frame();
591    }
592
593    pub fn viewport_size(&self) -> (f32, f32) {
594        self.viewport
595    }
596
597    pub fn set_buffer_size(&mut self, width: u32, height: u32) {
598        self.buffer_size = (width, height);
599    }
600
601    pub fn buffer_size(&self) -> (u32, u32) {
602        self.buffer_size
603    }
604
605    pub fn scene(&self) -> &R::Scene {
606        self.renderer.scene()
607    }
608
609    pub fn renderer(&mut self) -> &mut R {
610        &mut self.renderer
611    }
612
613    #[cfg(not(target_arch = "wasm32"))]
614    pub fn set_frame_waker(&mut self, waker: impl Fn() + Send + Sync + 'static) {
615        self.runtime.set_frame_waker(waker);
616    }
617
618    #[cfg(target_arch = "wasm32")]
619    pub fn set_frame_waker(&mut self, waker: impl Fn() + 'static) {
620        self.runtime.set_frame_waker(waker);
621    }
622
623    pub fn clear_frame_waker(&mut self) {
624        self.runtime.clear_frame_waker();
625    }
626
627    pub fn should_render(&self) -> bool {
628        let app_context = Rc::clone(&self.app_context);
629        app_context.enter(|| {
630            if self.layout_requested
631                || self.scene_dirty
632                || peek_render_invalidation()
633                || peek_pointer_invalidation()
634                || peek_focus_invalidation()
635                || peek_layout_invalidation()
636            {
637                return true;
638            }
639            self.composition.should_render()
640        })
641    }
642
643    fn needs_ui_update_in_context(&self) -> bool {
644        if self.is_dirty
645            || self.layout_requested
646            || self.scene_dirty
647            || peek_render_invalidation()
648            || peek_pointer_invalidation()
649            || peek_focus_invalidation()
650            || peek_layout_invalidation()
651            || cranpose_ui::has_pending_layout_repasses()
652            || cranpose_ui::has_pending_measure_repasses()
653            || cranpose_ui::has_pending_draw_repasses()
654            || has_pending_pointer_repasses()
655            || has_pending_focus_invalidations()
656        {
657            return true;
658        }
659
660        self.composition.runtime_handle().has_pending_ui() || self.composition.should_render()
661    }
662
663    pub fn needs_update(&self) -> bool {
664        let app_context = Rc::clone(&self.app_context);
665        app_context.enter(|| self.needs_ui_update_in_context())
666    }
667
668    /// Returns true if the shell needs to redraw (dirty flag, layout dirty, active animations).
669    /// Note: Cursor blink is now timer-based and uses WaitUntil scheduling, not continuous redraw.
670    pub fn needs_redraw(&self) -> bool {
671        let app_context = Rc::clone(&self.app_context);
672        app_context
673            .enter(|| self.is_dirty || self.should_render() || self.renderer.needs_frame_warmup())
674    }
675
676    /// Marks the shell as dirty, indicating a redraw is needed.
677    pub fn mark_dirty(&mut self) {
678        self.is_dirty = true;
679    }
680
681    pub fn request_root_render(&mut self) {
682        self.composition.request_root_render();
683        self.request_forced_layout_pass();
684        let app_context = Rc::clone(&self.app_context);
685        app_context.enter(request_render_invalidation);
686        self.mark_dirty();
687    }
688
689    pub fn set_density(&mut self, density: f32) {
690        let app_context = Rc::clone(&self.app_context);
691        let changed = app_context.enter(|| {
692            let previous = cranpose_ui::current_density().to_bits();
693            cranpose_ui::set_density(density);
694            previous != cranpose_ui::current_density().to_bits()
695        });
696        if changed {
697            self.request_forced_layout_pass();
698            self.mark_dirty();
699        }
700    }
701
702    #[cfg(any(test, feature = "test-support"))]
703    #[doc(hidden)]
704    pub fn debug_current_density(&self) -> f32 {
705        let app_context = Rc::clone(&self.app_context);
706        app_context.enter(cranpose_ui::current_density)
707    }
708
709    #[cfg(any(test, feature = "test-support"))]
710    #[doc(hidden)]
711    pub fn debug_enter_app_context<T>(&self, block: impl FnOnce() -> T) -> T {
712        let app_context = Rc::clone(&self.app_context);
713        app_context.enter(block)
714    }
715
716    fn request_layout_pass(&mut self) {
717        self.layout_requested = true;
718    }
719
720    fn request_forced_layout_pass(&mut self) {
721        self.layout_requested = true;
722        self.force_layout_pass = true;
723    }
724
725    fn composition_tree_needs_layout(&mut self) -> bool {
726        let Some(root) = self.composition.root() else {
727            return true;
728        };
729        let mut applier = self.composition.applier_mut();
730        cranpose_ui::tree_needs_layout(&mut *applier, root).unwrap_or_else(|err| {
731            log::warn!(
732                "Cannot check layout dirty status for root #{}: {}",
733                root,
734                err
735            );
736            true
737        })
738    }
739
740    /// Returns true if there are active animations or pending recompositions.
741    pub fn has_active_animations(&self) -> bool {
742        self.composition.should_render()
743    }
744
745    pub fn has_active_pointer_gesture(&self) -> bool {
746        self.buttons_pressed != PointerButtons::NONE
747            && self.hit_path_tracker.has_path(PointerId::PRIMARY)
748    }
749
750    /// Returns the next scheduled event time for cursor blink.
751    /// Use this for `ControlFlow::WaitUntil` scheduling.
752    pub fn next_event_time(&self) -> Option<web_time::Instant> {
753        let app_context = Rc::clone(&self.app_context);
754        app_context.enter(cranpose_ui::next_cursor_blink_time)
755    }
756
757    fn compute_frame_schedule(&self) -> FrameSchedule {
758        let needs_update = self.needs_update();
759        let needs_frame = self.is_dirty
760            || self.should_render()
761            || self.has_active_pointer_gesture()
762            || self.renderer.needs_frame_warmup();
763        FrameSchedule {
764            needs_update,
765            needs_frame,
766            next_deadline: self.next_event_time(),
767        }
768    }
769
770    pub fn frame_schedule(&self) -> FrameSchedule {
771        let schedule = self.compute_frame_schedule();
772        self.frame_scheduler.record(schedule);
773        schedule
774    }
775
776    pub fn schedule_platform_frame<D>(&self, driver: &D) -> FrameSchedule
777    where
778        D: PlatformFrameDriver + ?Sized,
779    {
780        let schedule = self.compute_frame_schedule();
781        self.frame_scheduler.schedule(schedule, driver);
782        schedule
783    }
784
785    pub fn frame_scheduler_snapshot(&self) -> FrameSchedule {
786        self.frame_scheduler.snapshot()
787    }
788
789    fn frame_time_nanos_at(&self, now: Instant) -> u64 {
790        now.checked_duration_since(self.start_time)
791            .unwrap_or_default()
792            .as_nanos()
793            .min(u128::from(u64::MAX)) as u64
794    }
795
796    /// Timestamp a live input sample against the current animation clock.
797    pub fn realtime_pointer_event_time(&self, platform_time_ms: Option<i64>) -> PointerEventTime {
798        PointerEventTime {
799            platform_time_ms,
800            animation_time_nanos: self
801                .frame_time_nanos_at(Instant::now())
802                .max(self.last_frame_time_nanos),
803        }
804    }
805
806    /// Timestamp deterministic input at the most recently processed frame.
807    pub fn exact_pointer_event_time(&self, platform_time_ms: Option<i64>) -> PointerEventTime {
808        PointerEventTime {
809            platform_time_ms,
810            animation_time_nanos: self.last_frame_time_nanos,
811        }
812    }
813
814    pub fn update_after_frame_interval(
815        &mut self,
816        frame_interval: std::time::Duration,
817    ) -> FrameUpdateResult {
818        let wall_frame_time = self.frame_time_nanos_at(Instant::now());
819        let base_frame_time = self.last_frame_time_nanos.max(wall_frame_time);
820        let frame_time = base_frame_time
821            .saturating_add(frame_interval.as_nanos().min(u128::from(u64::MAX)) as u64);
822        self.update_at_frame_time_nanos(frame_time)
823    }
824
825    /// Advance the frame clock by EXACTLY `frame_interval` past the last
826    /// frame — no wall anchoring — and run one update there. Robot keyframe
827    /// captures ride this to sample animations deterministically: while the
828    /// advanced clock is ahead of wall time, interleaved wall-clocked
829    /// updates clamp to it (dt 0) instead of fast-forwarding animations.
830    pub fn update_after_exact_interval(
831        &mut self,
832        frame_interval: std::time::Duration,
833    ) -> FrameUpdateResult {
834        let frame_time = self
835            .last_frame_time_nanos
836            .saturating_add(frame_interval.as_nanos().min(u128::from(u64::MAX)) as u64);
837        self.update_at_frame_time_nanos(frame_time)
838    }
839
840    pub fn update_at_frame_time_nanos(&mut self, frame_time: u64) -> FrameUpdateResult {
841        let app_context = Rc::clone(&self.app_context);
842        app_context.enter(|| {
843            let update_started_at = Instant::now();
844            let frame_time = frame_time.max(self.last_frame_time_nanos);
845            self.last_frame_time_nanos = frame_time;
846            let runtime_handle = self.runtime.runtime_handle();
847            runtime_handle.with_deferred_state_releases(|| {
848                self.runtime.drain_frame_callbacks(frame_time);
849                let after_frame_callbacks = Instant::now();
850                runtime_handle.drain_ui();
851                let after_ui_drain = Instant::now();
852                let should_render = self.composition.should_render();
853                let mut reconcile_attempted = false;
854                let mut reconcile_changed = false;
855                if should_render {
856                    log::trace!(
857                        target: "cranpose::input",
858                        "update begin: should_render=true layout_requested={} scene_dirty={} is_dirty={}",
859                        self.layout_requested,
860                        self.scene_dirty,
861                        self.is_dirty
862                    );
863                }
864                if should_render {
865                    let Some(root_key) = self.composition.root_key() else {
866                        let result = self.process_frame_in_context(reconcile_changed);
867                        let after_process_frame = Instant::now();
868                        log_update_stage_telemetry(UpdateStageTelemetry {
869                            started_at: update_started_at,
870                            after_frame_callbacks,
871                            after_ui_drain,
872                            after_reconcile: after_ui_drain,
873                            after_process_frame,
874                            should_render,
875                            reconcile_attempted,
876                            reconcile_changed,
877                        });
878                        self.is_dirty = false;
879                        return result;
880                    };
881                    reconcile_attempted = true;
882                    match self.composition.reconcile(root_key, &mut *self.content) {
883                        Ok(changed) => {
884                            reconcile_changed = changed;
885                            log::trace!(
886                                target: "cranpose::input",
887                                "reconcile changed={changed}"
888                            );
889                            if changed {
890                                self.fps_monitor.record_recomposition();
891                                if self.composition_tree_needs_layout() {
892                                    self.request_layout_pass();
893                                }
894                                request_render_invalidation();
895                            }
896                        }
897                        Err(NodeError::Missing { id }) => {
898                            log::debug!("Recomposition skipped: node {} no longer exists", id);
899                            self.request_layout_pass();
900                            request_render_invalidation();
901                        }
902                        Err(err) => {
903                            log::error!("recomposition failed: {err}");
904                            self.request_layout_pass();
905                            request_render_invalidation();
906                        }
907                    }
908                }
909                let after_reconcile = Instant::now();
910                let result = self.process_frame_in_context(reconcile_changed);
911                let after_process_frame = Instant::now();
912                log_update_stage_telemetry(UpdateStageTelemetry {
913                    started_at: update_started_at,
914                    after_frame_callbacks,
915                    after_ui_drain,
916                    after_reconcile,
917                    after_process_frame,
918                    should_render,
919                    reconcile_attempted,
920                    reconcile_changed,
921                });
922                self.is_dirty = false;
923                result
924            })
925        })
926    }
927
928    pub fn update(&mut self) -> FrameUpdateResult {
929        let frame_time = self.frame_time_nanos_at(Instant::now());
930        self.update_at_frame_time_nanos(frame_time)
931    }
932}
933
934impl<R> Drop for AppShell<R>
935where
936    R: Renderer,
937{
938    fn drop(&mut self) {
939        self.runtime.clear_frame_waker();
940    }
941}
942
943pub fn default_root_key() -> Key {
944    location_key(file!(), line!(), column!())
945}
946
947#[cfg(test)]
948mod frame_pacing_tests {
949    use super::{FramePacingMode, FrameSchedule, FrameScheduler, PlatformFrameDriver};
950    use std::cell::RefCell;
951    use std::panic::{catch_unwind, AssertUnwindSafe};
952    use std::time::Duration;
953    use web_time::Instant;
954
955    #[derive(Clone, Copy, Debug, PartialEq)]
956    enum DriverCall {
957        RequestFrame,
958        RequestWakeAt(Instant),
959        ClearWake,
960    }
961
962    #[derive(Default)]
963    struct RecordingFrameDriver {
964        calls: RefCell<Vec<DriverCall>>,
965    }
966
967    impl RecordingFrameDriver {
968        fn calls(&self) -> Vec<DriverCall> {
969            self.calls.borrow().clone()
970        }
971    }
972
973    impl PlatformFrameDriver for RecordingFrameDriver {
974        fn request_frame(&self) {
975            self.calls.borrow_mut().push(DriverCall::RequestFrame);
976        }
977
978        fn request_wake_at(&self, deadline: Instant) {
979            self.calls
980                .borrow_mut()
981                .push(DriverCall::RequestWakeAt(deadline));
982        }
983
984        fn clear_wake(&self) {
985            self.calls.borrow_mut().push(DriverCall::ClearWake);
986        }
987    }
988
989    #[test]
990    fn frame_pacing_labels_match_overlay_modes() {
991        assert_eq!(FramePacingMode::Vsync.label(), "VSync");
992        assert_eq!(FramePacingMode::Hard60.label(), "60fps");
993        assert_eq!(FramePacingMode::Hard120.label(), "120fps");
994        assert_eq!(FramePacingMode::NoVsync.label(), "NoVSync");
995    }
996
997    #[test]
998    fn only_hard_modes_have_fixed_targets() {
999        assert_eq!(FramePacingMode::Vsync.target_fps(), None);
1000        assert_eq!(FramePacingMode::Hard60.target_fps(), Some(60));
1001        assert_eq!(FramePacingMode::Hard120.target_fps(), Some(120));
1002        assert_eq!(FramePacingMode::NoVsync.target_fps(), None);
1003    }
1004
1005    #[test]
1006    fn frame_schedule_requests_immediate_frame_and_clears_deadline() {
1007        let driver = RecordingFrameDriver::default();
1008        let deadline = Instant::now() + Duration::from_millis(25);
1009
1010        FrameSchedule {
1011            needs_update: true,
1012            needs_frame: true,
1013            next_deadline: Some(deadline),
1014        }
1015        .apply_to(&driver);
1016
1017        assert_eq!(
1018            driver.calls(),
1019            vec![DriverCall::ClearWake, DriverCall::RequestFrame]
1020        );
1021    }
1022
1023    #[test]
1024    fn frame_schedule_requests_deadline_when_idle_until_timer() {
1025        let driver = RecordingFrameDriver::default();
1026        let deadline = Instant::now() + Duration::from_millis(25);
1027
1028        FrameSchedule {
1029            needs_update: false,
1030            needs_frame: false,
1031            next_deadline: Some(deadline),
1032        }
1033        .apply_to(&driver);
1034
1035        assert_eq!(driver.calls(), vec![DriverCall::RequestWakeAt(deadline)]);
1036    }
1037
1038    #[test]
1039    fn frame_schedule_wakes_without_requesting_frame_for_update_only_work() {
1040        let driver = RecordingFrameDriver::default();
1041        let before = Instant::now();
1042
1043        FrameSchedule {
1044            needs_update: true,
1045            needs_frame: false,
1046            next_deadline: None,
1047        }
1048        .apply_to(&driver);
1049
1050        let calls = driver.calls();
1051        assert_eq!(calls.len(), 1);
1052        match calls[0] {
1053            DriverCall::RequestWakeAt(deadline) => {
1054                assert!(deadline >= before);
1055            }
1056            other => panic!("update-only work must wake without requesting a frame: {other:?}"),
1057        }
1058    }
1059
1060    #[test]
1061    fn frame_schedule_clears_wake_when_fully_idle() {
1062        let driver = RecordingFrameDriver::default();
1063
1064        FrameSchedule {
1065            needs_update: false,
1066            needs_frame: false,
1067            next_deadline: None,
1068        }
1069        .apply_to(&driver);
1070
1071        assert_eq!(driver.calls(), vec![DriverCall::ClearWake]);
1072    }
1073
1074    #[test]
1075    fn frame_scheduler_records_latest_schedule_and_applies_driver() {
1076        let scheduler = FrameScheduler::default();
1077        let driver = RecordingFrameDriver::default();
1078        let deadline = Instant::now() + Duration::from_millis(25);
1079
1080        scheduler.schedule(
1081            FrameSchedule {
1082                needs_update: false,
1083                needs_frame: false,
1084                next_deadline: Some(deadline),
1085            },
1086            &driver,
1087        );
1088
1089        assert_eq!(
1090            scheduler.snapshot(),
1091            FrameSchedule {
1092                needs_update: false,
1093                needs_frame: false,
1094                next_deadline: Some(deadline),
1095            }
1096        );
1097        assert_eq!(driver.calls(), vec![DriverCall::RequestWakeAt(deadline)]);
1098    }
1099
1100    #[test]
1101    fn frame_scheduler_clears_deadline_for_immediate_frame() {
1102        let scheduler = FrameScheduler::default();
1103        let driver = RecordingFrameDriver::default();
1104        let deadline = Instant::now() + Duration::from_millis(25);
1105
1106        scheduler.schedule(
1107            FrameSchedule {
1108                needs_update: true,
1109                needs_frame: true,
1110                next_deadline: Some(deadline),
1111            },
1112            &driver,
1113        );
1114
1115        assert_eq!(
1116            scheduler.snapshot(),
1117            FrameSchedule {
1118                needs_update: true,
1119                needs_frame: true,
1120                next_deadline: None,
1121            }
1122        );
1123        assert_eq!(
1124            driver.calls(),
1125            vec![DriverCall::ClearWake, DriverCall::RequestFrame]
1126        );
1127    }
1128
1129    #[test]
1130    fn frame_scheduler_recovers_poisoned_deadline_lock() {
1131        let scheduler = FrameScheduler::default();
1132        let deadline = Instant::now() + Duration::from_millis(25);
1133
1134        let _ = catch_unwind(AssertUnwindSafe(|| {
1135            let _guard = scheduler.lock_deadline();
1136            panic!("poison frame scheduler deadline lock");
1137        }));
1138
1139        scheduler.record(FrameSchedule {
1140            needs_update: false,
1141            needs_frame: false,
1142            next_deadline: Some(deadline),
1143        });
1144
1145        assert_eq!(
1146            scheduler.snapshot(),
1147            FrameSchedule {
1148                needs_update: false,
1149                needs_frame: false,
1150                next_deadline: Some(deadline),
1151            }
1152        );
1153    }
1154}
1155
1156#[cfg(test)]
1157#[path = "tests/app_shell_tests.rs"]
1158mod tests;