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