cranpose-app-shell 0.1.9

Application orchestration shell for Cranpose
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
#![deny(unsafe_code)]
#![allow(clippy::type_complexity)]

mod fps_monitor;
mod hit_path_tracker;
mod shell_debug;
mod shell_frame;
mod shell_input;
#[cfg(test)]
use shell_frame::build_draw_refresh_scope;

pub use fps_monitor::FpsStats;

use std::fmt::{Debug, Write};
use std::rc::Rc;
use std::sync::{
    atomic::{AtomicBool, Ordering},
    Mutex, MutexGuard,
};
// Use web_time for cross-platform time support (native + WASM) - compatible with winit
use web_time::Instant;

use cranpose_core::{
    enter_event_handler_scope, location_key, run_in_mutable_snapshot, Applier, Composition, Key,
    MemoryApplier, NodeError, NodeId,
};
use cranpose_foundation::{PointerButton, PointerButtons, PointerEvent, PointerEventKind};
use cranpose_render_common::{HitTestTarget, RenderScene, Renderer};
use cranpose_runtime_std::StdRuntime;
use cranpose_ui::{
    format_layout_tree, format_render_scene, format_screen_summary,
    has_pending_focus_invalidations, has_pending_pointer_repasses, peek_focus_invalidation,
    peek_layout_invalidation, peek_pointer_invalidation, peek_render_invalidation,
    process_focus_invalidations, process_pointer_repasses, request_render_invalidation,
    take_draw_repass_nodes, take_focus_invalidation, take_layout_invalidation,
    take_pointer_invalidation, take_render_invalidation, HeadlessRenderer, LayoutBox, LayoutNode,
    LayoutTree, MeasureLayoutOptions, SemanticsTree, SubcomposeLayoutNode,
};
use cranpose_ui_graphics::{Point, Rect, Size};
use hit_path_tracker::{HitPathTracker, PointerId};
use std::collections::HashSet;

// Re-export key event types for use by cranpose
pub use cranpose_ui::{KeyCode, KeyEvent, KeyEventType, Modifiers};

#[cfg(any(test, feature = "test-support"))]
use cranpose_core::{
    debug_recompose_scope_registry_stats, MemoryApplierDebugStats,
    RecomposeScopeRegistryDebugStats, SlotTableDebugStats,
};
#[cfg(any(test, feature = "test-support"))]
use cranpose_core::{
    runtime::{RuntimeDebugStats, StateArenaDebugStats},
    snapshot_pinning::{debug_snapshot_pinning_stats, SnapshotPinningDebugStats},
    snapshot_state_observer::SnapshotStateObserverDebugStats,
    snapshot_v2::{debug_snapshot_v2_stats, SnapshotV2DebugStats},
    CompositionPassDebugStats, SlotId,
};

pub struct AppShell<R>
where
    R: Renderer,
{
    app_context: Rc<cranpose_ui::AppContext>,
    runtime: StdRuntime,
    composition: Composition<MemoryApplier>,
    content: Box<dyn FnMut()>,
    renderer: R,
    cursor: (f32, f32),
    viewport: (f32, f32),
    buffer_size: (u32, u32),
    start_time: Instant,
    last_frame_time_nanos: u64,
    layout_tree: Option<LayoutTree>,
    semantics_tree: Option<SemanticsTree>,
    semantics_enabled: bool,
    layout_requested: bool,
    force_layout_pass: bool,
    scene_dirty: bool,
    is_dirty: bool,
    /// Tracks which mouse buttons are currently pressed
    buttons_pressed: PointerButtons,
    /// Tracks which nodes were hit on PointerDown (by stable NodeId).
    ///
    /// This follows Jetpack Compose's HitPathTracker pattern:
    /// - On Down: cache NodeIds, not geometry
    /// - On Move/Up/Cancel: resolve fresh HitTargets from current scene
    /// - Handler closures are preserved (same Rc), so internal state survives
    hit_path_tracker: HitPathTracker,
    /// Tracks which nodes the pointer is currently hovering over.
    /// Used to synthesize Enter/Exit events when the hover set changes.
    hovered_nodes: Vec<NodeId>,
    /// Persistent clipboard for desktop (Linux X11 requires clipboard to stay alive)
    #[cfg(all(
        feature = "clipboard-native",
        not(target_arch = "wasm32"),
        not(target_os = "android"),
        not(target_os = "ios")
    ))]
    clipboard: Option<arboard::Clipboard>,
    /// Dev options for debugging and performance monitoring
    dev_options: DevOptions,
    dev_overlay_controls: Vec<DevOverlayControl>,
    fps_monitor: fps_monitor::FpsMonitor,
    frame_scheduler: FrameScheduler,
}

#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub enum FramePacingMode {
    Vsync,
    Hard60,
    Hard120,
    #[default]
    NoVsync,
}

impl FramePacingMode {
    pub const ALL: [Self; 4] = [Self::Vsync, Self::Hard60, Self::Hard120, Self::NoVsync];

    pub fn label(self) -> &'static str {
        match self {
            Self::Vsync => "VSync",
            Self::Hard60 => "60fps",
            Self::Hard120 => "120fps",
            Self::NoVsync => "NoVSync",
        }
    }

    pub fn target_fps(self) -> Option<u32> {
        match self {
            Self::Hard60 => Some(60),
            Self::Hard120 => Some(120),
            Self::Vsync | Self::NoVsync => None,
        }
    }
}

#[derive(Clone, Copy, Debug, PartialEq)]
pub struct FrameSchedule {
    pub needs_frame: bool,
    pub next_deadline: Option<web_time::Instant>,
}

pub trait PlatformFrameDriver {
    fn request_frame(&self);
    fn request_wake_at(&self, deadline: web_time::Instant);
    fn clear_wake(&self);
}

#[derive(Debug)]
pub struct FrameScheduler {
    frame_pending: AtomicBool,
    next_deadline: Mutex<Option<web_time::Instant>>,
}

impl Default for FrameScheduler {
    fn default() -> Self {
        Self {
            frame_pending: AtomicBool::new(false),
            next_deadline: Mutex::new(None),
        }
    }
}

impl FrameScheduler {
    fn lock_deadline(&self) -> MutexGuard<'_, Option<web_time::Instant>> {
        self.next_deadline
            .lock()
            .unwrap_or_else(|poisoned| poisoned.into_inner())
    }

    pub fn record(&self, schedule: FrameSchedule) {
        self.frame_pending
            .store(schedule.needs_frame, Ordering::SeqCst);
        let mut next_deadline = self.lock_deadline();
        *next_deadline = if schedule.needs_frame {
            None
        } else {
            schedule.next_deadline
        };
    }

    pub fn schedule<D>(&self, schedule: FrameSchedule, driver: &D)
    where
        D: PlatformFrameDriver + ?Sized,
    {
        self.record(schedule);
        schedule.apply_to(driver);
    }

    pub fn snapshot(&self) -> FrameSchedule {
        FrameSchedule {
            needs_frame: self.frame_pending.load(Ordering::SeqCst),
            next_deadline: *self.lock_deadline(),
        }
    }
}

impl FrameSchedule {
    pub fn apply_to<D>(self, driver: &D)
    where
        D: PlatformFrameDriver + ?Sized,
    {
        if self.needs_frame {
            driver.clear_wake();
            driver.request_frame();
        } else if let Some(deadline) = self.next_deadline {
            driver.request_wake_at(deadline);
        } else {
            driver.clear_wake();
        }
    }
}

#[derive(Clone, Copy, Debug)]
struct DevOverlayControl {
    bounds: Rect,
    mode: FramePacingMode,
}

/// Development options for debugging and performance monitoring.
///
/// These are rendered directly by the renderer (not via composition)
/// to avoid affecting performance measurements.
#[derive(Clone, Debug, Default)]
pub struct DevOptions {
    /// Show FPS counter overlay
    pub fps_counter: bool,
    /// Show recomposition count
    pub recomposition_counter: bool,
    /// Show layout timing breakdown
    pub layout_timing: bool,
    pub frame_pacing_controls: bool,
    pub frame_pacing_mode: FramePacingMode,
}

#[cfg(any(test, feature = "test-support"))]
#[doc(hidden)]
#[derive(Clone, Copy, Debug)]
pub struct RuntimeLeakDebugStats {
    pub applier_stats: MemoryApplierDebugStats,
    pub live_node_heap_bytes: usize,
    pub recycled_node_heap_bytes: usize,
    pub slot_table_heap_bytes: usize,
    pub pass_stats: CompositionPassDebugStats,
    pub slot_stats: SlotTableDebugStats,
    pub observer_stats: SnapshotStateObserverDebugStats,
    pub runtime_stats: RuntimeDebugStats,
    pub state_arena_stats: StateArenaDebugStats,
    pub recompose_scope_stats: RecomposeScopeRegistryDebugStats,
    pub snapshot_v2_stats: SnapshotV2DebugStats,
    pub snapshot_pinning_stats: SnapshotPinningDebugStats,
}

impl<R> AppShell<R>
where
    R: Renderer,
    R::Error: Debug,
{
    pub fn new(renderer: R, root_key: Key, content: impl FnMut() + 'static) -> Self {
        Self::new_with_size(renderer, root_key, content, (800, 600), (800.0, 600.0))
    }

    pub fn new_with_size(
        renderer: R,
        root_key: Key,
        content: impl FnMut() + 'static,
        buffer_size: (u32, u32),
        viewport: (f32, f32),
    ) -> Self {
        Self::new_with_size_and_density(renderer, root_key, content, buffer_size, viewport, 1.0)
    }

    pub fn new_with_size_and_density(
        mut renderer: R,
        root_key: Key,
        content: impl FnMut() + 'static,
        buffer_size: (u32, u32),
        viewport: (f32, f32),
        density: f32,
    ) -> Self {
        let app_context = cranpose_ui::AppContext::new_with_density(density);
        let runtime = StdRuntime::new();
        let mut composition = Composition::with_runtime(MemoryApplier::new(), runtime.runtime());
        let mut build: Box<dyn FnMut()> = Box::new(content);
        renderer.attach_app_context_services(&app_context);
        app_context.enter(|| {
            if let Err(err) = composition.render_stable(root_key, &mut *build) {
                log::error!("initial render failed: {err}");
            }
        });
        renderer.scene_mut().clear();
        let mut shell = Self {
            app_context,
            runtime,
            composition,
            content: build,
            renderer,
            cursor: (0.0, 0.0),
            viewport,
            buffer_size,
            start_time: Instant::now(),
            last_frame_time_nanos: 0,
            layout_tree: None,
            semantics_tree: None,
            semantics_enabled: false,
            layout_requested: true,
            force_layout_pass: true,
            scene_dirty: true,
            is_dirty: true,
            buttons_pressed: PointerButtons::NONE,
            hit_path_tracker: HitPathTracker::new(),
            hovered_nodes: Vec::new(),
            #[cfg(all(
                feature = "clipboard-native",
                not(target_arch = "wasm32"),
                not(target_os = "android"),
                not(target_os = "ios")
            ))]
            clipboard: arboard::Clipboard::new().ok(),
            dev_options: DevOptions::default(),
            dev_overlay_controls: Vec::new(),
            fps_monitor: fps_monitor::FpsMonitor::new(),
            frame_scheduler: FrameScheduler::default(),
        };
        shell.process_frame();
        shell
    }

    /// Set development options for debugging and performance monitoring.
    ///
    /// The FPS counter and other overlays are rendered directly by the renderer
    /// (not via composition) to avoid affecting performance measurements.
    pub fn set_dev_options(&mut self, options: DevOptions) {
        self.dev_options = options;
        self.mark_dirty();
    }

    /// Get a reference to the current dev options.
    pub fn dev_options(&self) -> &DevOptions {
        &self.dev_options
    }

    pub fn frame_pacing_mode(&self) -> FramePacingMode {
        self.dev_options.frame_pacing_mode
    }

    pub fn current_fps(&self) -> f32 {
        self.fps_monitor.current_fps()
    }

    pub fn fps_stats(&self) -> FpsStats {
        self.fps_monitor.stats()
    }

    pub fn reset_fps_stats(&mut self) {
        self.fps_monitor.reset_stats();
    }

    pub fn set_frame_pacing_mode(&mut self, mode: FramePacingMode) {
        if self.dev_options.frame_pacing_mode == mode {
            return;
        }
        self.dev_options.frame_pacing_mode = mode;
        let app_context = Rc::clone(&self.app_context);
        app_context.enter(request_render_invalidation);
        self.mark_dirty();
    }

    pub fn handle_dev_overlay_click(&mut self, x: f32, y: f32) -> Option<FramePacingMode> {
        if !self.dev_options.frame_pacing_controls {
            return None;
        }
        let mode = self
            .dev_overlay_controls
            .iter()
            .find(|control| control.bounds.contains(x, y))
            .map(|control| control.mode)?;
        self.set_frame_pacing_mode(mode);
        Some(mode)
    }

    pub fn set_viewport(&mut self, width: f32, height: f32) {
        self.viewport = (width, height);
        self.request_forced_layout_pass();
        self.mark_dirty();
        self.process_frame();
    }

    pub fn viewport_size(&self) -> (f32, f32) {
        self.viewport
    }

    pub fn set_buffer_size(&mut self, width: u32, height: u32) {
        self.buffer_size = (width, height);
    }

    pub fn buffer_size(&self) -> (u32, u32) {
        self.buffer_size
    }

    pub fn scene(&self) -> &R::Scene {
        self.renderer.scene()
    }

    pub fn renderer(&mut self) -> &mut R {
        &mut self.renderer
    }

    #[cfg(not(target_arch = "wasm32"))]
    pub fn set_frame_waker(&mut self, waker: impl Fn() + Send + Sync + 'static) {
        self.runtime.set_frame_waker(waker);
    }

    #[cfg(target_arch = "wasm32")]
    pub fn set_frame_waker(&mut self, waker: impl Fn() + 'static) {
        self.runtime.set_frame_waker(waker);
    }

    pub fn clear_frame_waker(&mut self) {
        self.runtime.clear_frame_waker();
    }

    pub fn should_render(&self) -> bool {
        let app_context = Rc::clone(&self.app_context);
        app_context.enter(|| {
            if self.layout_requested
                || self.scene_dirty
                || peek_render_invalidation()
                || peek_pointer_invalidation()
                || peek_focus_invalidation()
                || peek_layout_invalidation()
            {
                return true;
            }
            self.composition.should_render()
        })
    }

    /// Returns true if the shell needs to redraw (dirty flag, layout dirty, active animations).
    /// Note: Cursor blink is now timer-based and uses WaitUntil scheduling, not continuous redraw.
    pub fn needs_redraw(&self) -> bool {
        let app_context = Rc::clone(&self.app_context);
        app_context.enter(|| {
            if self.is_dirty
                || self.layout_requested
                || self.scene_dirty
                || peek_render_invalidation()
                || peek_pointer_invalidation()
                || peek_focus_invalidation()
                || peek_layout_invalidation()
                || cranpose_ui::has_pending_layout_repasses()
                || cranpose_ui::has_pending_draw_repasses()
                || has_pending_pointer_repasses()
                || has_pending_focus_invalidations()
            {
                return true;
            }

            self.composition.should_render()
        })
    }

    /// Marks the shell as dirty, indicating a redraw is needed.
    pub fn mark_dirty(&mut self) {
        self.is_dirty = true;
    }

    pub fn request_root_render(&mut self) {
        self.composition.request_root_render();
        self.request_forced_layout_pass();
        let app_context = Rc::clone(&self.app_context);
        app_context.enter(request_render_invalidation);
        self.mark_dirty();
    }

    pub fn set_density(&mut self, density: f32) {
        let app_context = Rc::clone(&self.app_context);
        let changed = app_context.enter(|| {
            let previous = cranpose_ui::current_density().to_bits();
            cranpose_ui::set_density(density);
            previous != cranpose_ui::current_density().to_bits()
        });
        if changed {
            self.request_forced_layout_pass();
            self.mark_dirty();
        }
    }

    #[cfg(any(test, feature = "test-support"))]
    #[doc(hidden)]
    pub fn debug_current_density(&self) -> f32 {
        let app_context = Rc::clone(&self.app_context);
        app_context.enter(cranpose_ui::current_density)
    }

    #[cfg(any(test, feature = "test-support"))]
    #[doc(hidden)]
    pub fn debug_enter_app_context<T>(&self, block: impl FnOnce() -> T) -> T {
        let app_context = Rc::clone(&self.app_context);
        app_context.enter(block)
    }

    fn request_layout_pass(&mut self) {
        self.layout_requested = true;
    }

    fn request_forced_layout_pass(&mut self) {
        self.layout_requested = true;
        self.force_layout_pass = true;
    }

    /// Returns true if there are active animations or pending recompositions.
    pub fn has_active_animations(&self) -> bool {
        self.composition.should_render()
    }

    /// Returns the next scheduled event time for cursor blink.
    /// Use this for `ControlFlow::WaitUntil` scheduling.
    pub fn next_event_time(&self) -> Option<web_time::Instant> {
        let app_context = Rc::clone(&self.app_context);
        app_context.enter(cranpose_ui::next_cursor_blink_time)
    }

    fn compute_frame_schedule(&self) -> FrameSchedule {
        FrameSchedule {
            needs_frame: self.needs_redraw() || self.has_active_animations(),
            next_deadline: self.next_event_time(),
        }
    }

    pub fn frame_schedule(&self) -> FrameSchedule {
        let schedule = self.compute_frame_schedule();
        self.frame_scheduler.record(schedule);
        schedule
    }

    pub fn schedule_platform_frame<D>(&self, driver: &D) -> FrameSchedule
    where
        D: PlatformFrameDriver + ?Sized,
    {
        let schedule = self.compute_frame_schedule();
        self.frame_scheduler.schedule(schedule, driver);
        schedule
    }

    pub fn frame_scheduler_snapshot(&self) -> FrameSchedule {
        self.frame_scheduler.snapshot()
    }

    fn frame_time_nanos_at(&self, now: Instant) -> u64 {
        now.checked_duration_since(self.start_time)
            .unwrap_or_default()
            .as_nanos()
            .min(u128::from(u64::MAX)) as u64
    }

    pub fn update_after_frame_interval(&mut self, frame_interval: std::time::Duration) {
        let wall_frame_time = self.frame_time_nanos_at(Instant::now());
        let base_frame_time = self.last_frame_time_nanos.max(wall_frame_time);
        let frame_time = base_frame_time
            .saturating_add(frame_interval.as_nanos().min(u128::from(u64::MAX)) as u64);
        self.update_at_frame_time_nanos(frame_time);
    }

    pub fn update_at_frame_time_nanos(&mut self, frame_time: u64) {
        let app_context = Rc::clone(&self.app_context);
        app_context.enter(|| {
            let frame_time = frame_time.max(self.last_frame_time_nanos);
            self.last_frame_time_nanos = frame_time;
            let runtime_handle = self.runtime.runtime_handle();
            runtime_handle.with_deferred_state_releases(|| {
                self.runtime.drain_frame_callbacks(frame_time);
                runtime_handle.drain_ui();
                let should_render = self.composition.should_render();
                if should_render {
                    log::trace!(
                        target: "cranpose::input",
                        "update begin: should_render=true layout_requested={} scene_dirty={} is_dirty={}",
                        self.layout_requested,
                        self.scene_dirty,
                        self.is_dirty
                    );
                }
                if should_render {
                    let Some(root_key) = self.composition.root_key() else {
                        self.process_frame_in_context();
                        self.is_dirty = false;
                        return;
                    };
                    match self.composition.reconcile(root_key, &mut *self.content) {
                        Ok(changed) => {
                            log::trace!(
                                target: "cranpose::input",
                                "reconcile changed={changed}"
                            );
                            if changed {
                                self.fps_monitor.record_recomposition();
                                self.request_layout_pass();
                                request_render_invalidation();
                            }
                        }
                        Err(NodeError::Missing { id }) => {
                            // Node was removed (likely due to conditional render or tab switch)
                            // This is expected when scopes try to recompose after their nodes are gone
                            log::debug!("Recomposition skipped: node {} no longer exists", id);
                            self.request_layout_pass();
                            request_render_invalidation();
                        }
                        Err(err) => {
                            log::error!("recomposition failed: {err}");
                            self.request_layout_pass();
                            request_render_invalidation();
                        }
                    }
                }
                self.process_frame_in_context();
                // Clear dirty flag after update (frame has been processed)
                self.is_dirty = false;
            });
        });
    }

    pub fn update(&mut self) {
        let frame_time = self.frame_time_nanos_at(Instant::now());
        self.update_at_frame_time_nanos(frame_time);
    }
}

impl<R> Drop for AppShell<R>
where
    R: Renderer,
{
    fn drop(&mut self) {
        self.runtime.clear_frame_waker();
    }
}

pub fn default_root_key() -> Key {
    location_key(file!(), line!(), column!())
}

#[cfg(test)]
mod frame_pacing_tests {
    use super::{FramePacingMode, FrameSchedule, FrameScheduler, PlatformFrameDriver};
    use std::cell::RefCell;
    use std::panic::{catch_unwind, AssertUnwindSafe};
    use std::time::Duration;
    use web_time::Instant;

    #[derive(Clone, Copy, Debug, PartialEq)]
    enum DriverCall {
        RequestFrame,
        RequestWakeAt(Instant),
        ClearWake,
    }

    #[derive(Default)]
    struct RecordingFrameDriver {
        calls: RefCell<Vec<DriverCall>>,
    }

    impl RecordingFrameDriver {
        fn calls(&self) -> Vec<DriverCall> {
            self.calls.borrow().clone()
        }
    }

    impl PlatformFrameDriver for RecordingFrameDriver {
        fn request_frame(&self) {
            self.calls.borrow_mut().push(DriverCall::RequestFrame);
        }

        fn request_wake_at(&self, deadline: Instant) {
            self.calls
                .borrow_mut()
                .push(DriverCall::RequestWakeAt(deadline));
        }

        fn clear_wake(&self) {
            self.calls.borrow_mut().push(DriverCall::ClearWake);
        }
    }

    #[test]
    fn frame_pacing_labels_match_overlay_modes() {
        assert_eq!(FramePacingMode::Vsync.label(), "VSync");
        assert_eq!(FramePacingMode::Hard60.label(), "60fps");
        assert_eq!(FramePacingMode::Hard120.label(), "120fps");
        assert_eq!(FramePacingMode::NoVsync.label(), "NoVSync");
    }

    #[test]
    fn only_hard_modes_have_fixed_targets() {
        assert_eq!(FramePacingMode::Vsync.target_fps(), None);
        assert_eq!(FramePacingMode::Hard60.target_fps(), Some(60));
        assert_eq!(FramePacingMode::Hard120.target_fps(), Some(120));
        assert_eq!(FramePacingMode::NoVsync.target_fps(), None);
    }

    #[test]
    fn frame_schedule_requests_immediate_frame_and_clears_deadline() {
        let driver = RecordingFrameDriver::default();
        let deadline = Instant::now() + Duration::from_millis(25);

        FrameSchedule {
            needs_frame: true,
            next_deadline: Some(deadline),
        }
        .apply_to(&driver);

        assert_eq!(
            driver.calls(),
            vec![DriverCall::ClearWake, DriverCall::RequestFrame]
        );
    }

    #[test]
    fn frame_schedule_requests_deadline_when_idle_until_timer() {
        let driver = RecordingFrameDriver::default();
        let deadline = Instant::now() + Duration::from_millis(25);

        FrameSchedule {
            needs_frame: false,
            next_deadline: Some(deadline),
        }
        .apply_to(&driver);

        assert_eq!(driver.calls(), vec![DriverCall::RequestWakeAt(deadline)]);
    }

    #[test]
    fn frame_schedule_clears_wake_when_fully_idle() {
        let driver = RecordingFrameDriver::default();

        FrameSchedule {
            needs_frame: false,
            next_deadline: None,
        }
        .apply_to(&driver);

        assert_eq!(driver.calls(), vec![DriverCall::ClearWake]);
    }

    #[test]
    fn frame_scheduler_records_latest_schedule_and_applies_driver() {
        let scheduler = FrameScheduler::default();
        let driver = RecordingFrameDriver::default();
        let deadline = Instant::now() + Duration::from_millis(25);

        scheduler.schedule(
            FrameSchedule {
                needs_frame: false,
                next_deadline: Some(deadline),
            },
            &driver,
        );

        assert_eq!(
            scheduler.snapshot(),
            FrameSchedule {
                needs_frame: false,
                next_deadline: Some(deadline),
            }
        );
        assert_eq!(driver.calls(), vec![DriverCall::RequestWakeAt(deadline)]);
    }

    #[test]
    fn frame_scheduler_clears_deadline_for_immediate_frame() {
        let scheduler = FrameScheduler::default();
        let driver = RecordingFrameDriver::default();
        let deadline = Instant::now() + Duration::from_millis(25);

        scheduler.schedule(
            FrameSchedule {
                needs_frame: true,
                next_deadline: Some(deadline),
            },
            &driver,
        );

        assert_eq!(
            scheduler.snapshot(),
            FrameSchedule {
                needs_frame: true,
                next_deadline: None,
            }
        );
        assert_eq!(
            driver.calls(),
            vec![DriverCall::ClearWake, DriverCall::RequestFrame]
        );
    }

    #[test]
    fn frame_scheduler_recovers_poisoned_deadline_lock() {
        let scheduler = FrameScheduler::default();
        let deadline = Instant::now() + Duration::from_millis(25);

        let _ = catch_unwind(AssertUnwindSafe(|| {
            let _guard = scheduler.lock_deadline();
            panic!("poison frame scheduler deadline lock");
        }));

        scheduler.record(FrameSchedule {
            needs_frame: false,
            next_deadline: Some(deadline),
        });

        assert_eq!(
            scheduler.snapshot(),
            FrameSchedule {
                needs_frame: false,
                next_deadline: Some(deadline),
            }
        );
    }
}

#[cfg(test)]
#[path = "tests/app_shell_tests.rs"]
mod tests;