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