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_draw_repasses()
646            || has_pending_pointer_repasses()
647            || has_pending_focus_invalidations()
648        {
649            return true;
650        }
651
652        self.composition.should_render()
653    }
654
655    pub fn needs_update(&self) -> bool {
656        let app_context = Rc::clone(&self.app_context);
657        app_context.enter(|| self.needs_ui_update_in_context())
658    }
659
660    /// Returns true if the shell needs to redraw (dirty flag, layout dirty, active animations).
661    /// Note: Cursor blink is now timer-based and uses WaitUntil scheduling, not continuous redraw.
662    pub fn needs_redraw(&self) -> bool {
663        let app_context = Rc::clone(&self.app_context);
664        app_context
665            .enter(|| self.needs_ui_update_in_context() || self.renderer.needs_frame_warmup())
666    }
667
668    /// Marks the shell as dirty, indicating a redraw is needed.
669    pub fn mark_dirty(&mut self) {
670        self.is_dirty = true;
671    }
672
673    pub fn request_root_render(&mut self) {
674        self.composition.request_root_render();
675        self.request_forced_layout_pass();
676        let app_context = Rc::clone(&self.app_context);
677        app_context.enter(request_render_invalidation);
678        self.mark_dirty();
679    }
680
681    pub fn set_density(&mut self, density: f32) {
682        let app_context = Rc::clone(&self.app_context);
683        let changed = app_context.enter(|| {
684            let previous = cranpose_ui::current_density().to_bits();
685            cranpose_ui::set_density(density);
686            previous != cranpose_ui::current_density().to_bits()
687        });
688        if changed {
689            self.request_forced_layout_pass();
690            self.mark_dirty();
691        }
692    }
693
694    #[cfg(any(test, feature = "test-support"))]
695    #[doc(hidden)]
696    pub fn debug_current_density(&self) -> f32 {
697        let app_context = Rc::clone(&self.app_context);
698        app_context.enter(cranpose_ui::current_density)
699    }
700
701    #[cfg(any(test, feature = "test-support"))]
702    #[doc(hidden)]
703    pub fn debug_enter_app_context<T>(&self, block: impl FnOnce() -> T) -> T {
704        let app_context = Rc::clone(&self.app_context);
705        app_context.enter(block)
706    }
707
708    fn request_layout_pass(&mut self) {
709        self.layout_requested = true;
710    }
711
712    fn request_forced_layout_pass(&mut self) {
713        self.layout_requested = true;
714        self.force_layout_pass = true;
715    }
716
717    fn composition_tree_needs_layout(&mut self) -> bool {
718        let Some(root) = self.composition.root() else {
719            return true;
720        };
721        let mut applier = self.composition.applier_mut();
722        cranpose_ui::tree_needs_layout(&mut *applier, root).unwrap_or_else(|err| {
723            log::warn!(
724                "Cannot check layout dirty status for root #{}: {}",
725                root,
726                err
727            );
728            true
729        })
730    }
731
732    /// Returns true if there are active animations or pending recompositions.
733    pub fn has_active_animations(&self) -> bool {
734        self.composition.should_render()
735    }
736
737    pub fn has_active_pointer_gesture(&self) -> bool {
738        self.buttons_pressed != PointerButtons::NONE
739            && self.hit_path_tracker.has_path(PointerId::PRIMARY)
740    }
741
742    /// Returns the next scheduled event time for cursor blink.
743    /// Use this for `ControlFlow::WaitUntil` scheduling.
744    pub fn next_event_time(&self) -> Option<web_time::Instant> {
745        let app_context = Rc::clone(&self.app_context);
746        app_context.enter(cranpose_ui::next_cursor_blink_time)
747    }
748
749    fn compute_frame_schedule(&self) -> FrameSchedule {
750        let needs_update = self.needs_update();
751        let needs_frame = needs_update
752            || self.has_active_animations()
753            || self.has_active_pointer_gesture()
754            || self.renderer.needs_frame_warmup();
755        FrameSchedule {
756            needs_update,
757            needs_frame,
758            next_deadline: self.next_event_time(),
759        }
760    }
761
762    pub fn frame_schedule(&self) -> FrameSchedule {
763        let schedule = self.compute_frame_schedule();
764        self.frame_scheduler.record(schedule);
765        schedule
766    }
767
768    pub fn schedule_platform_frame<D>(&self, driver: &D) -> FrameSchedule
769    where
770        D: PlatformFrameDriver + ?Sized,
771    {
772        let schedule = self.compute_frame_schedule();
773        self.frame_scheduler.schedule(schedule, driver);
774        schedule
775    }
776
777    pub fn frame_scheduler_snapshot(&self) -> FrameSchedule {
778        self.frame_scheduler.snapshot()
779    }
780
781    fn frame_time_nanos_at(&self, now: Instant) -> u64 {
782        now.checked_duration_since(self.start_time)
783            .unwrap_or_default()
784            .as_nanos()
785            .min(u128::from(u64::MAX)) as u64
786    }
787
788    pub fn update_after_frame_interval(
789        &mut self,
790        frame_interval: std::time::Duration,
791    ) -> FrameUpdateResult {
792        let wall_frame_time = self.frame_time_nanos_at(Instant::now());
793        let base_frame_time = self.last_frame_time_nanos.max(wall_frame_time);
794        let frame_time = base_frame_time
795            .saturating_add(frame_interval.as_nanos().min(u128::from(u64::MAX)) as u64);
796        self.update_at_frame_time_nanos(frame_time)
797    }
798
799    pub fn update_at_frame_time_nanos(&mut self, frame_time: u64) -> FrameUpdateResult {
800        let app_context = Rc::clone(&self.app_context);
801        app_context.enter(|| {
802            let update_started_at = Instant::now();
803            let frame_time = frame_time.max(self.last_frame_time_nanos);
804            self.last_frame_time_nanos = frame_time;
805            let runtime_handle = self.runtime.runtime_handle();
806            runtime_handle.with_deferred_state_releases(|| {
807                self.runtime.drain_frame_callbacks(frame_time);
808                let after_frame_callbacks = Instant::now();
809                runtime_handle.drain_ui();
810                let after_ui_drain = Instant::now();
811                let should_render = self.composition.should_render();
812                let mut reconcile_attempted = false;
813                let mut reconcile_changed = false;
814                if should_render {
815                    log::trace!(
816                        target: "cranpose::input",
817                        "update begin: should_render=true layout_requested={} scene_dirty={} is_dirty={}",
818                        self.layout_requested,
819                        self.scene_dirty,
820                        self.is_dirty
821                    );
822                }
823                if should_render {
824                    let Some(root_key) = self.composition.root_key() else {
825                        let result = self.process_frame_in_context(reconcile_changed);
826                        let after_process_frame = Instant::now();
827                        log_update_stage_telemetry(UpdateStageTelemetry {
828                            started_at: update_started_at,
829                            after_frame_callbacks,
830                            after_ui_drain,
831                            after_reconcile: after_ui_drain,
832                            after_process_frame,
833                            should_render,
834                            reconcile_attempted,
835                            reconcile_changed,
836                        });
837                        self.is_dirty = false;
838                        return result;
839                    };
840                    reconcile_attempted = true;
841                    match self.composition.reconcile(root_key, &mut *self.content) {
842                        Ok(changed) => {
843                            reconcile_changed = changed;
844                            log::trace!(
845                                target: "cranpose::input",
846                                "reconcile changed={changed}"
847                            );
848                            if changed {
849                                self.fps_monitor.record_recomposition();
850                                if self.composition_tree_needs_layout() {
851                                    self.request_layout_pass();
852                                }
853                                request_render_invalidation();
854                            }
855                        }
856                        Err(NodeError::Missing { id }) => {
857                            log::debug!("Recomposition skipped: node {} no longer exists", id);
858                            self.request_layout_pass();
859                            request_render_invalidation();
860                        }
861                        Err(err) => {
862                            log::error!("recomposition failed: {err}");
863                            self.request_layout_pass();
864                            request_render_invalidation();
865                        }
866                    }
867                }
868                let after_reconcile = Instant::now();
869                let result = self.process_frame_in_context(reconcile_changed);
870                let after_process_frame = Instant::now();
871                log_update_stage_telemetry(UpdateStageTelemetry {
872                    started_at: update_started_at,
873                    after_frame_callbacks,
874                    after_ui_drain,
875                    after_reconcile,
876                    after_process_frame,
877                    should_render,
878                    reconcile_attempted,
879                    reconcile_changed,
880                });
881                self.is_dirty = false;
882                result
883            })
884        })
885    }
886
887    pub fn update(&mut self) -> FrameUpdateResult {
888        let frame_time = self.frame_time_nanos_at(Instant::now());
889        self.update_at_frame_time_nanos(frame_time)
890    }
891}
892
893impl<R> Drop for AppShell<R>
894where
895    R: Renderer,
896{
897    fn drop(&mut self) {
898        self.runtime.clear_frame_waker();
899    }
900}
901
902pub fn default_root_key() -> Key {
903    location_key(file!(), line!(), column!())
904}
905
906#[cfg(test)]
907mod frame_pacing_tests {
908    use super::{FramePacingMode, FrameSchedule, FrameScheduler, PlatformFrameDriver};
909    use std::cell::RefCell;
910    use std::panic::{catch_unwind, AssertUnwindSafe};
911    use std::time::Duration;
912    use web_time::Instant;
913
914    #[derive(Clone, Copy, Debug, PartialEq)]
915    enum DriverCall {
916        RequestFrame,
917        RequestWakeAt(Instant),
918        ClearWake,
919    }
920
921    #[derive(Default)]
922    struct RecordingFrameDriver {
923        calls: RefCell<Vec<DriverCall>>,
924    }
925
926    impl RecordingFrameDriver {
927        fn calls(&self) -> Vec<DriverCall> {
928            self.calls.borrow().clone()
929        }
930    }
931
932    impl PlatformFrameDriver for RecordingFrameDriver {
933        fn request_frame(&self) {
934            self.calls.borrow_mut().push(DriverCall::RequestFrame);
935        }
936
937        fn request_wake_at(&self, deadline: Instant) {
938            self.calls
939                .borrow_mut()
940                .push(DriverCall::RequestWakeAt(deadline));
941        }
942
943        fn clear_wake(&self) {
944            self.calls.borrow_mut().push(DriverCall::ClearWake);
945        }
946    }
947
948    #[test]
949    fn frame_pacing_labels_match_overlay_modes() {
950        assert_eq!(FramePacingMode::Vsync.label(), "VSync");
951        assert_eq!(FramePacingMode::Hard60.label(), "60fps");
952        assert_eq!(FramePacingMode::Hard120.label(), "120fps");
953        assert_eq!(FramePacingMode::NoVsync.label(), "NoVSync");
954    }
955
956    #[test]
957    fn only_hard_modes_have_fixed_targets() {
958        assert_eq!(FramePacingMode::Vsync.target_fps(), None);
959        assert_eq!(FramePacingMode::Hard60.target_fps(), Some(60));
960        assert_eq!(FramePacingMode::Hard120.target_fps(), Some(120));
961        assert_eq!(FramePacingMode::NoVsync.target_fps(), None);
962    }
963
964    #[test]
965    fn frame_schedule_requests_immediate_frame_and_clears_deadline() {
966        let driver = RecordingFrameDriver::default();
967        let deadline = Instant::now() + Duration::from_millis(25);
968
969        FrameSchedule {
970            needs_update: true,
971            needs_frame: true,
972            next_deadline: Some(deadline),
973        }
974        .apply_to(&driver);
975
976        assert_eq!(
977            driver.calls(),
978            vec![DriverCall::ClearWake, DriverCall::RequestFrame]
979        );
980    }
981
982    #[test]
983    fn frame_schedule_requests_deadline_when_idle_until_timer() {
984        let driver = RecordingFrameDriver::default();
985        let deadline = Instant::now() + Duration::from_millis(25);
986
987        FrameSchedule {
988            needs_update: false,
989            needs_frame: false,
990            next_deadline: Some(deadline),
991        }
992        .apply_to(&driver);
993
994        assert_eq!(driver.calls(), vec![DriverCall::RequestWakeAt(deadline)]);
995    }
996
997    #[test]
998    fn frame_schedule_wakes_without_requesting_frame_for_update_only_work() {
999        let driver = RecordingFrameDriver::default();
1000        let before = Instant::now();
1001
1002        FrameSchedule {
1003            needs_update: true,
1004            needs_frame: false,
1005            next_deadline: None,
1006        }
1007        .apply_to(&driver);
1008
1009        let calls = driver.calls();
1010        assert_eq!(calls.len(), 1);
1011        match calls[0] {
1012            DriverCall::RequestWakeAt(deadline) => {
1013                assert!(deadline >= before);
1014            }
1015            other => panic!("update-only work must wake without requesting a frame: {other:?}"),
1016        }
1017    }
1018
1019    #[test]
1020    fn frame_schedule_clears_wake_when_fully_idle() {
1021        let driver = RecordingFrameDriver::default();
1022
1023        FrameSchedule {
1024            needs_update: false,
1025            needs_frame: false,
1026            next_deadline: None,
1027        }
1028        .apply_to(&driver);
1029
1030        assert_eq!(driver.calls(), vec![DriverCall::ClearWake]);
1031    }
1032
1033    #[test]
1034    fn frame_scheduler_records_latest_schedule_and_applies_driver() {
1035        let scheduler = FrameScheduler::default();
1036        let driver = RecordingFrameDriver::default();
1037        let deadline = Instant::now() + Duration::from_millis(25);
1038
1039        scheduler.schedule(
1040            FrameSchedule {
1041                needs_update: false,
1042                needs_frame: false,
1043                next_deadline: Some(deadline),
1044            },
1045            &driver,
1046        );
1047
1048        assert_eq!(
1049            scheduler.snapshot(),
1050            FrameSchedule {
1051                needs_update: false,
1052                needs_frame: false,
1053                next_deadline: Some(deadline),
1054            }
1055        );
1056        assert_eq!(driver.calls(), vec![DriverCall::RequestWakeAt(deadline)]);
1057    }
1058
1059    #[test]
1060    fn frame_scheduler_clears_deadline_for_immediate_frame() {
1061        let scheduler = FrameScheduler::default();
1062        let driver = RecordingFrameDriver::default();
1063        let deadline = Instant::now() + Duration::from_millis(25);
1064
1065        scheduler.schedule(
1066            FrameSchedule {
1067                needs_update: true,
1068                needs_frame: true,
1069                next_deadline: Some(deadline),
1070            },
1071            &driver,
1072        );
1073
1074        assert_eq!(
1075            scheduler.snapshot(),
1076            FrameSchedule {
1077                needs_update: true,
1078                needs_frame: true,
1079                next_deadline: None,
1080            }
1081        );
1082        assert_eq!(
1083            driver.calls(),
1084            vec![DriverCall::ClearWake, DriverCall::RequestFrame]
1085        );
1086    }
1087
1088    #[test]
1089    fn frame_scheduler_recovers_poisoned_deadline_lock() {
1090        let scheduler = FrameScheduler::default();
1091        let deadline = Instant::now() + Duration::from_millis(25);
1092
1093        let _ = catch_unwind(AssertUnwindSafe(|| {
1094            let _guard = scheduler.lock_deadline();
1095            panic!("poison frame scheduler deadline lock");
1096        }));
1097
1098        scheduler.record(FrameSchedule {
1099            needs_update: false,
1100            needs_frame: false,
1101            next_deadline: Some(deadline),
1102        });
1103
1104        assert_eq!(
1105            scheduler.snapshot(),
1106            FrameSchedule {
1107                needs_update: false,
1108                needs_frame: false,
1109                next_deadline: Some(deadline),
1110            }
1111        );
1112    }
1113}
1114
1115#[cfg(test)]
1116#[path = "tests/app_shell_tests.rs"]
1117mod tests;