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    /// Set development options for debugging and performance monitoring.
495    ///
496    /// The FPS counter and other overlays are rendered directly by the renderer
497    /// (not via composition) to avoid affecting performance measurements.
498    pub fn set_dev_options(&mut self, options: DevOptions) {
499        self.dev_options = options;
500        self.invalidate_dev_overlay_text();
501        let app_context = Rc::clone(&self.app_context);
502        app_context.enter(request_render_invalidation);
503        self.mark_dirty();
504    }
505
506    /// Get a reference to the current dev options.
507    pub fn dev_options(&self) -> &DevOptions {
508        &self.dev_options
509    }
510
511    pub fn frame_pacing_mode(&self) -> FramePacingMode {
512        self.dev_options.frame_pacing_mode
513    }
514
515    pub fn current_fps(&self) -> f32 {
516        self.fps_monitor.current_fps()
517    }
518
519    pub fn fps_stats(&self) -> FpsStats {
520        self.fps_monitor.stats()
521    }
522
523    pub fn reset_fps_stats(&mut self) {
524        self.fps_monitor.reset_stats();
525        self.invalidate_dev_overlay_text();
526    }
527
528    pub fn record_presented_frame(
529        &mut self,
530        frame_started_at: Instant,
531        frame_finished_at: Instant,
532    ) {
533        self.fps_monitor
534            .record_frame_work(frame_started_at, frame_finished_at);
535    }
536
537    #[cfg(any(test, feature = "test-support"))]
538    #[doc(hidden)]
539    pub fn record_presented_frame_for_test(
540        &mut self,
541        frame_started_nanos: u64,
542        frame_finished_nanos: u64,
543    ) {
544        let started = self.start_time + std::time::Duration::from_nanos(frame_started_nanos);
545        let finished = self.start_time + std::time::Duration::from_nanos(frame_finished_nanos);
546        self.record_presented_frame(started, finished);
547    }
548
549    pub fn set_frame_pacing_mode(&mut self, mode: FramePacingMode) {
550        if self.dev_options.frame_pacing_mode == mode {
551            return;
552        }
553        self.dev_options.frame_pacing_mode = mode;
554        self.invalidate_dev_overlay_text();
555        let app_context = Rc::clone(&self.app_context);
556        app_context.enter(request_render_invalidation);
557        self.mark_dirty();
558    }
559
560    pub fn handle_dev_overlay_click(&mut self, x: f32, y: f32) -> Option<FramePacingMode> {
561        if !self.dev_options.frame_pacing_controls {
562            return None;
563        }
564        let mode = self
565            .dev_overlay_controls
566            .iter()
567            .find(|control| control.bounds.contains(x, y))
568            .map(|control| control.mode)?;
569        self.set_frame_pacing_mode(mode);
570        Some(mode)
571    }
572
573    fn invalidate_dev_overlay_text(&mut self) {
574        self.dev_overlay_text.clear();
575        self.dev_overlay_last_refresh = None;
576        self.dev_overlay_viewport = None;
577    }
578
579    pub fn set_viewport(&mut self, width: f32, height: f32) {
580        self.viewport = (width, height);
581        self.request_forced_layout_pass();
582        self.mark_dirty();
583        self.process_frame();
584    }
585
586    pub fn viewport_size(&self) -> (f32, f32) {
587        self.viewport
588    }
589
590    pub fn set_buffer_size(&mut self, width: u32, height: u32) {
591        self.buffer_size = (width, height);
592    }
593
594    pub fn buffer_size(&self) -> (u32, u32) {
595        self.buffer_size
596    }
597
598    pub fn scene(&self) -> &R::Scene {
599        self.renderer.scene()
600    }
601
602    pub fn renderer(&mut self) -> &mut R {
603        &mut self.renderer
604    }
605
606    #[cfg(not(target_arch = "wasm32"))]
607    pub fn set_frame_waker(&mut self, waker: impl Fn() + Send + Sync + 'static) {
608        self.runtime.set_frame_waker(waker);
609    }
610
611    #[cfg(target_arch = "wasm32")]
612    pub fn set_frame_waker(&mut self, waker: impl Fn() + 'static) {
613        self.runtime.set_frame_waker(waker);
614    }
615
616    pub fn clear_frame_waker(&mut self) {
617        self.runtime.clear_frame_waker();
618    }
619
620    pub fn should_render(&self) -> bool {
621        let app_context = Rc::clone(&self.app_context);
622        app_context.enter(|| {
623            if self.layout_requested
624                || self.scene_dirty
625                || peek_render_invalidation()
626                || peek_pointer_invalidation()
627                || peek_focus_invalidation()
628                || peek_layout_invalidation()
629            {
630                return true;
631            }
632            self.composition.should_render()
633        })
634    }
635
636    fn needs_ui_update_in_context(&self) -> bool {
637        if self.is_dirty
638            || self.layout_requested
639            || self.scene_dirty
640            || peek_render_invalidation()
641            || peek_pointer_invalidation()
642            || peek_focus_invalidation()
643            || peek_layout_invalidation()
644            || cranpose_ui::has_pending_layout_repasses()
645            || cranpose_ui::has_pending_measure_repasses()
646            || cranpose_ui::has_pending_draw_repasses()
647            || has_pending_pointer_repasses()
648            || has_pending_focus_invalidations()
649        {
650            return true;
651        }
652
653        self.composition.should_render()
654    }
655
656    pub fn needs_update(&self) -> bool {
657        let app_context = Rc::clone(&self.app_context);
658        app_context.enter(|| self.needs_ui_update_in_context())
659    }
660
661    /// Returns true if the shell needs to redraw (dirty flag, layout dirty, active animations).
662    /// Note: Cursor blink is now timer-based and uses WaitUntil scheduling, not continuous redraw.
663    pub fn needs_redraw(&self) -> bool {
664        let app_context = Rc::clone(&self.app_context);
665        app_context
666            .enter(|| self.needs_ui_update_in_context() || self.renderer.needs_frame_warmup())
667    }
668
669    /// Marks the shell as dirty, indicating a redraw is needed.
670    pub fn mark_dirty(&mut self) {
671        self.is_dirty = true;
672    }
673
674    pub fn request_root_render(&mut self) {
675        self.composition.request_root_render();
676        self.request_forced_layout_pass();
677        let app_context = Rc::clone(&self.app_context);
678        app_context.enter(request_render_invalidation);
679        self.mark_dirty();
680    }
681
682    pub fn set_density(&mut self, density: f32) {
683        let app_context = Rc::clone(&self.app_context);
684        let changed = app_context.enter(|| {
685            let previous = cranpose_ui::current_density().to_bits();
686            cranpose_ui::set_density(density);
687            previous != cranpose_ui::current_density().to_bits()
688        });
689        if changed {
690            self.request_forced_layout_pass();
691            self.mark_dirty();
692        }
693    }
694
695    #[cfg(any(test, feature = "test-support"))]
696    #[doc(hidden)]
697    pub fn debug_current_density(&self) -> f32 {
698        let app_context = Rc::clone(&self.app_context);
699        app_context.enter(cranpose_ui::current_density)
700    }
701
702    #[cfg(any(test, feature = "test-support"))]
703    #[doc(hidden)]
704    pub fn debug_enter_app_context<T>(&self, block: impl FnOnce() -> T) -> T {
705        let app_context = Rc::clone(&self.app_context);
706        app_context.enter(block)
707    }
708
709    fn request_layout_pass(&mut self) {
710        self.layout_requested = true;
711    }
712
713    fn request_forced_layout_pass(&mut self) {
714        self.layout_requested = true;
715        self.force_layout_pass = true;
716    }
717
718    fn composition_tree_needs_layout(&mut self) -> bool {
719        let Some(root) = self.composition.root() else {
720            return true;
721        };
722        let mut applier = self.composition.applier_mut();
723        cranpose_ui::tree_needs_layout(&mut *applier, root).unwrap_or_else(|err| {
724            log::warn!(
725                "Cannot check layout dirty status for root #{}: {}",
726                root,
727                err
728            );
729            true
730        })
731    }
732
733    /// Returns true if there are active animations or pending recompositions.
734    pub fn has_active_animations(&self) -> bool {
735        self.composition.should_render()
736    }
737
738    pub fn has_active_pointer_gesture(&self) -> bool {
739        self.buttons_pressed != PointerButtons::NONE
740            && self.hit_path_tracker.has_path(PointerId::PRIMARY)
741    }
742
743    /// Returns the next scheduled event time for cursor blink.
744    /// Use this for `ControlFlow::WaitUntil` scheduling.
745    pub fn next_event_time(&self) -> Option<web_time::Instant> {
746        let app_context = Rc::clone(&self.app_context);
747        app_context.enter(cranpose_ui::next_cursor_blink_time)
748    }
749
750    fn compute_frame_schedule(&self) -> FrameSchedule {
751        let needs_update = self.needs_update();
752        let needs_frame = needs_update
753            || self.has_active_animations()
754            || self.has_active_pointer_gesture()
755            || self.renderer.needs_frame_warmup();
756        FrameSchedule {
757            needs_update,
758            needs_frame,
759            next_deadline: self.next_event_time(),
760        }
761    }
762
763    pub fn frame_schedule(&self) -> FrameSchedule {
764        let schedule = self.compute_frame_schedule();
765        self.frame_scheduler.record(schedule);
766        schedule
767    }
768
769    pub fn schedule_platform_frame<D>(&self, driver: &D) -> FrameSchedule
770    where
771        D: PlatformFrameDriver + ?Sized,
772    {
773        let schedule = self.compute_frame_schedule();
774        self.frame_scheduler.schedule(schedule, driver);
775        schedule
776    }
777
778    pub fn frame_scheduler_snapshot(&self) -> FrameSchedule {
779        self.frame_scheduler.snapshot()
780    }
781
782    fn frame_time_nanos_at(&self, now: Instant) -> u64 {
783        now.checked_duration_since(self.start_time)
784            .unwrap_or_default()
785            .as_nanos()
786            .min(u128::from(u64::MAX)) as u64
787    }
788
789    pub fn update_after_frame_interval(
790        &mut self,
791        frame_interval: std::time::Duration,
792    ) -> FrameUpdateResult {
793        let wall_frame_time = self.frame_time_nanos_at(Instant::now());
794        let base_frame_time = self.last_frame_time_nanos.max(wall_frame_time);
795        let frame_time = base_frame_time
796            .saturating_add(frame_interval.as_nanos().min(u128::from(u64::MAX)) as u64);
797        self.update_at_frame_time_nanos(frame_time)
798    }
799
800    pub fn update_at_frame_time_nanos(&mut self, frame_time: u64) -> FrameUpdateResult {
801        let app_context = Rc::clone(&self.app_context);
802        app_context.enter(|| {
803            let update_started_at = Instant::now();
804            let frame_time = frame_time.max(self.last_frame_time_nanos);
805            self.last_frame_time_nanos = frame_time;
806            let runtime_handle = self.runtime.runtime_handle();
807            runtime_handle.with_deferred_state_releases(|| {
808                self.runtime.drain_frame_callbacks(frame_time);
809                let after_frame_callbacks = Instant::now();
810                runtime_handle.drain_ui();
811                let after_ui_drain = Instant::now();
812                let should_render = self.composition.should_render();
813                let mut reconcile_attempted = false;
814                let mut reconcile_changed = false;
815                if should_render {
816                    log::trace!(
817                        target: "cranpose::input",
818                        "update begin: should_render=true layout_requested={} scene_dirty={} is_dirty={}",
819                        self.layout_requested,
820                        self.scene_dirty,
821                        self.is_dirty
822                    );
823                }
824                if should_render {
825                    let Some(root_key) = self.composition.root_key() else {
826                        let result = self.process_frame_in_context(reconcile_changed);
827                        let after_process_frame = Instant::now();
828                        log_update_stage_telemetry(UpdateStageTelemetry {
829                            started_at: update_started_at,
830                            after_frame_callbacks,
831                            after_ui_drain,
832                            after_reconcile: after_ui_drain,
833                            after_process_frame,
834                            should_render,
835                            reconcile_attempted,
836                            reconcile_changed,
837                        });
838                        self.is_dirty = false;
839                        return result;
840                    };
841                    reconcile_attempted = true;
842                    match self.composition.reconcile(root_key, &mut *self.content) {
843                        Ok(changed) => {
844                            reconcile_changed = changed;
845                            log::trace!(
846                                target: "cranpose::input",
847                                "reconcile changed={changed}"
848                            );
849                            if changed {
850                                self.fps_monitor.record_recomposition();
851                                if self.composition_tree_needs_layout() {
852                                    self.request_layout_pass();
853                                }
854                                request_render_invalidation();
855                            }
856                        }
857                        Err(NodeError::Missing { id }) => {
858                            log::debug!("Recomposition skipped: node {} no longer exists", id);
859                            self.request_layout_pass();
860                            request_render_invalidation();
861                        }
862                        Err(err) => {
863                            log::error!("recomposition failed: {err}");
864                            self.request_layout_pass();
865                            request_render_invalidation();
866                        }
867                    }
868                }
869                let after_reconcile = Instant::now();
870                let result = self.process_frame_in_context(reconcile_changed);
871                let after_process_frame = Instant::now();
872                log_update_stage_telemetry(UpdateStageTelemetry {
873                    started_at: update_started_at,
874                    after_frame_callbacks,
875                    after_ui_drain,
876                    after_reconcile,
877                    after_process_frame,
878                    should_render,
879                    reconcile_attempted,
880                    reconcile_changed,
881                });
882                self.is_dirty = false;
883                result
884            })
885        })
886    }
887
888    pub fn update(&mut self) -> FrameUpdateResult {
889        let frame_time = self.frame_time_nanos_at(Instant::now());
890        self.update_at_frame_time_nanos(frame_time)
891    }
892}
893
894impl<R> Drop for AppShell<R>
895where
896    R: Renderer,
897{
898    fn drop(&mut self) {
899        self.runtime.clear_frame_waker();
900    }
901}
902
903pub fn default_root_key() -> Key {
904    location_key(file!(), line!(), column!())
905}
906
907#[cfg(test)]
908mod frame_pacing_tests {
909    use super::{FramePacingMode, FrameSchedule, FrameScheduler, PlatformFrameDriver};
910    use std::cell::RefCell;
911    use std::panic::{catch_unwind, AssertUnwindSafe};
912    use std::time::Duration;
913    use web_time::Instant;
914
915    #[derive(Clone, Copy, Debug, PartialEq)]
916    enum DriverCall {
917        RequestFrame,
918        RequestWakeAt(Instant),
919        ClearWake,
920    }
921
922    #[derive(Default)]
923    struct RecordingFrameDriver {
924        calls: RefCell<Vec<DriverCall>>,
925    }
926
927    impl RecordingFrameDriver {
928        fn calls(&self) -> Vec<DriverCall> {
929            self.calls.borrow().clone()
930        }
931    }
932
933    impl PlatformFrameDriver for RecordingFrameDriver {
934        fn request_frame(&self) {
935            self.calls.borrow_mut().push(DriverCall::RequestFrame);
936        }
937
938        fn request_wake_at(&self, deadline: Instant) {
939            self.calls
940                .borrow_mut()
941                .push(DriverCall::RequestWakeAt(deadline));
942        }
943
944        fn clear_wake(&self) {
945            self.calls.borrow_mut().push(DriverCall::ClearWake);
946        }
947    }
948
949    #[test]
950    fn frame_pacing_labels_match_overlay_modes() {
951        assert_eq!(FramePacingMode::Vsync.label(), "VSync");
952        assert_eq!(FramePacingMode::Hard60.label(), "60fps");
953        assert_eq!(FramePacingMode::Hard120.label(), "120fps");
954        assert_eq!(FramePacingMode::NoVsync.label(), "NoVSync");
955    }
956
957    #[test]
958    fn only_hard_modes_have_fixed_targets() {
959        assert_eq!(FramePacingMode::Vsync.target_fps(), None);
960        assert_eq!(FramePacingMode::Hard60.target_fps(), Some(60));
961        assert_eq!(FramePacingMode::Hard120.target_fps(), Some(120));
962        assert_eq!(FramePacingMode::NoVsync.target_fps(), None);
963    }
964
965    #[test]
966    fn frame_schedule_requests_immediate_frame_and_clears_deadline() {
967        let driver = RecordingFrameDriver::default();
968        let deadline = Instant::now() + Duration::from_millis(25);
969
970        FrameSchedule {
971            needs_update: true,
972            needs_frame: true,
973            next_deadline: Some(deadline),
974        }
975        .apply_to(&driver);
976
977        assert_eq!(
978            driver.calls(),
979            vec![DriverCall::ClearWake, DriverCall::RequestFrame]
980        );
981    }
982
983    #[test]
984    fn frame_schedule_requests_deadline_when_idle_until_timer() {
985        let driver = RecordingFrameDriver::default();
986        let deadline = Instant::now() + Duration::from_millis(25);
987
988        FrameSchedule {
989            needs_update: false,
990            needs_frame: false,
991            next_deadline: Some(deadline),
992        }
993        .apply_to(&driver);
994
995        assert_eq!(driver.calls(), vec![DriverCall::RequestWakeAt(deadline)]);
996    }
997
998    #[test]
999    fn frame_schedule_wakes_without_requesting_frame_for_update_only_work() {
1000        let driver = RecordingFrameDriver::default();
1001        let before = Instant::now();
1002
1003        FrameSchedule {
1004            needs_update: true,
1005            needs_frame: false,
1006            next_deadline: None,
1007        }
1008        .apply_to(&driver);
1009
1010        let calls = driver.calls();
1011        assert_eq!(calls.len(), 1);
1012        match calls[0] {
1013            DriverCall::RequestWakeAt(deadline) => {
1014                assert!(deadline >= before);
1015            }
1016            other => panic!("update-only work must wake without requesting a frame: {other:?}"),
1017        }
1018    }
1019
1020    #[test]
1021    fn frame_schedule_clears_wake_when_fully_idle() {
1022        let driver = RecordingFrameDriver::default();
1023
1024        FrameSchedule {
1025            needs_update: false,
1026            needs_frame: false,
1027            next_deadline: None,
1028        }
1029        .apply_to(&driver);
1030
1031        assert_eq!(driver.calls(), vec![DriverCall::ClearWake]);
1032    }
1033
1034    #[test]
1035    fn frame_scheduler_records_latest_schedule_and_applies_driver() {
1036        let scheduler = FrameScheduler::default();
1037        let driver = RecordingFrameDriver::default();
1038        let deadline = Instant::now() + Duration::from_millis(25);
1039
1040        scheduler.schedule(
1041            FrameSchedule {
1042                needs_update: false,
1043                needs_frame: false,
1044                next_deadline: Some(deadline),
1045            },
1046            &driver,
1047        );
1048
1049        assert_eq!(
1050            scheduler.snapshot(),
1051            FrameSchedule {
1052                needs_update: false,
1053                needs_frame: false,
1054                next_deadline: Some(deadline),
1055            }
1056        );
1057        assert_eq!(driver.calls(), vec![DriverCall::RequestWakeAt(deadline)]);
1058    }
1059
1060    #[test]
1061    fn frame_scheduler_clears_deadline_for_immediate_frame() {
1062        let scheduler = FrameScheduler::default();
1063        let driver = RecordingFrameDriver::default();
1064        let deadline = Instant::now() + Duration::from_millis(25);
1065
1066        scheduler.schedule(
1067            FrameSchedule {
1068                needs_update: true,
1069                needs_frame: true,
1070                next_deadline: Some(deadline),
1071            },
1072            &driver,
1073        );
1074
1075        assert_eq!(
1076            scheduler.snapshot(),
1077            FrameSchedule {
1078                needs_update: true,
1079                needs_frame: true,
1080                next_deadline: None,
1081            }
1082        );
1083        assert_eq!(
1084            driver.calls(),
1085            vec![DriverCall::ClearWake, DriverCall::RequestFrame]
1086        );
1087    }
1088
1089    #[test]
1090    fn frame_scheduler_recovers_poisoned_deadline_lock() {
1091        let scheduler = FrameScheduler::default();
1092        let deadline = Instant::now() + Duration::from_millis(25);
1093
1094        let _ = catch_unwind(AssertUnwindSafe(|| {
1095            let _guard = scheduler.lock_deadline();
1096            panic!("poison frame scheduler deadline lock");
1097        }));
1098
1099        scheduler.record(FrameSchedule {
1100            needs_update: false,
1101            needs_frame: false,
1102            next_deadline: Some(deadline),
1103        });
1104
1105        assert_eq!(
1106            scheduler.snapshot(),
1107            FrameSchedule {
1108                needs_update: false,
1109                needs_frame: false,
1110                next_deadline: Some(deadline),
1111            }
1112        );
1113    }
1114}
1115
1116#[cfg(test)]
1117#[path = "tests/app_shell_tests.rs"]
1118mod tests;