euv-core 0.48.1

Core cross-platform runtime for euv featuring arena-based fine-grained reactivity, deterministic layout, flat scene graph, multi-mode rendering, and direct OS platform adapters.
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
use super::*;

/// `CADisplayLink` and `MTLDrawable.addPresentedHandler` telemetry helpers for `IosPresentTelemetry`.
impl IosPresentTelemetry {
    /// Creates an initialized iOS/iPadOS telemetry state with honest simulator observability tagging.
    ///
    /// # Arguments
    ///
    /// - `MobilePresentPath` - Active initial presentation channel.
    /// - `f32` - Active display refresh rate in Hertz (`60.0` or `120.0` ProMotion).
    /// - `bool` - `true` when executing on iOS Simulator where hardware `presentedTime` is unobservable.
    ///
    /// # Returns
    ///
    /// - `Self` - Configured iOS/iPadOS telemetry state.
    #[must_use]
    pub fn for_host(path: MobilePresentPath, refresh_hz: f32, is_simulator: bool) -> Self {
        Self {
            base: MobilePresentTelemetry::for_host(path, refresh_hz, is_simulator),
            display_link_timestamp_ns: 0,
            display_link_target_timestamp_ns: None,
            metal_presented_time_ns: None,
            metal_gpu_exec_us: 0,
            is_simulator,
            direct_gpu_frames: 0,
            gpu_upload_frames: 0,
            software_cg_frames: 0,
        }
    }

    /// Records `CADisplayLink.timestamp` and `CADisplayLink.targetTimestamp` in seconds.
    ///
    /// # Arguments
    ///
    /// - `f64` - Actual `CADisplayLink.timestamp` in seconds.
    /// - `f64` - Target `CADisplayLink.targetTimestamp` in seconds.
    pub fn record_display_link_tick(&mut self, timestamp_secs: f64, target_timestamp_secs: f64) {
        let cb_ns: u64 = ios_cf_time_secs_to_ns(timestamp_secs).unwrap_or(0);
        let target_ns: Option<u64> = ios_cf_time_secs_to_ns(target_timestamp_secs);
        self.set_display_link_timestamp_ns(cb_ns);
        self.set_display_link_target_timestamp_ns(target_ns);
        self.get_mut_base().record_vsync_callback(cb_ns, target_ns);
    }

    /// Records `MTLDrawable.presentedTime` from `addPresentedHandler:`, marking simulator or zero values unobservable.
    ///
    /// # Arguments
    ///
    /// - `f64` - `MTLDrawable.presentedTime` in seconds (`0.0` when unobservable).
    pub fn record_metal_presented_time(&mut self, presented_time_secs: f64) {
        let ns: Option<u64> = if self.get_is_simulator() {
            None
        } else {
            ios_cf_time_secs_to_ns(presented_time_secs)
        };
        self.set_metal_presented_time_ns(ns);
        self.get_mut_base().record_compositor_present_timestamp(ns);
    }

    /// Records a direct Metal drawable presentation (`cpu_mirror_active = false`, `upload_strategy = DirectGpu`).
    ///
    /// # Arguments
    ///
    /// - `&DirectGpuFrameBatch` - Submitted direct Metal primitive batch.
    /// - `u64` - Measured Metal GPU execution duration in microseconds.
    /// - `Option<u64>` - Physical-device `MTLDrawable.presentedTime` in nanoseconds (`None` on simulator).
    pub fn record_direct_metal_present(
        &mut self,
        batch: &DirectGpuFrameBatch,
        gpu_exec_us: u64,
        presented_ns: Option<u64>,
    ) {
        let effective_ns: Option<u64> = if self.get_is_simulator() {
            None
        } else {
            presented_ns.filter(|ns: &u64| *ns > 0)
        };
        self.set_metal_gpu_exec_us(gpu_exec_us);
        self.set_metal_presented_time_ns(effective_ns);
        self.set_direct_gpu_frames(self.get_direct_gpu_frames().saturating_add(1));
        self.get_mut_base().record_presented_frame(
            MobilePresentPath::GpuDirect,
            MobileUploadStrategy::DirectGpu,
            batch.get_instance_upload_bytes() as u64,
            batch.get_primitives().len() as u32,
            batch.get_draw_ranges().len() as u32,
            effective_ns,
        );
    }

    /// Records a Metal texture-upload fallback presentation (`cpu_mirror_active = true`).
    ///
    /// # Arguments
    ///
    /// - `&AdaptiveUploadPlan` - Selected multi-rect, merged-bbox, or full-frame upload plan.
    /// - `Option<u64>` - Physical-device `MTLDrawable.presentedTime` in nanoseconds (`None` on simulator).
    pub fn record_metal_upload_present(
        &mut self,
        plan: &AdaptiveUploadPlan,
        presented_ns: Option<u64>,
    ) {
        let effective_ns: Option<u64> = if self.get_is_simulator() {
            None
        } else {
            presented_ns.filter(|ns: &u64| *ns > 0)
        };
        self.set_metal_presented_time_ns(effective_ns);
        self.set_gpu_upload_frames(self.get_gpu_upload_frames().saturating_add(1));
        self.get_mut_base().record_presented_frame(
            MobilePresentPath::GpuUpload,
            plan.get_strategy(),
            plan.get_total_upload_bytes() as u64,
            0,
            1,
            effective_ns,
        );
    }

    /// Records a CoreGraphics `CGImage` software fallback presentation (`cpu_mirror_active = true`).
    ///
    /// # Arguments
    ///
    /// - `&AdaptiveUploadPlan` - Executed copy plan.
    pub fn record_cg_software_present(&mut self, plan: &AdaptiveUploadPlan) {
        self.set_software_cg_frames(self.get_software_cg_frames().saturating_add(1));
        self.get_mut_base().record_presented_frame(
            MobilePresentPath::Software,
            plan.get_strategy(),
            plan.get_total_upload_bytes() as u64,
            0,
            0,
            None,
        );
    }

    /// Records a Metal device/drawable fault and triggers immediate failover without blank frames.
    ///
    /// # Arguments
    ///
    /// - `MobileSurfaceFault` - Observed Metal surface or device fault.
    /// - `&mut MobileFailoverController` - Active iOS failover controller.
    ///
    /// # Returns
    ///
    /// - `MobileFailoverAction` - Deterministic failover action preserving the last valid frame.
    pub fn record_fault_with_failover(
        &mut self,
        fault: MobileSurfaceFault,
        failover: &mut MobileFailoverController,
    ) -> MobileFailoverAction {
        let prev_prevented: u64 = failover.get_blank_frames_prevented();
        let action: MobileFailoverAction = failover.handle_fault(fault);
        let prevented: bool = failover.get_blank_frames_prevented() > prev_prevented;
        self.get_mut_base().record_fault(fault, prevented);
        self.get_mut_base()
            .set_active_path(failover.get_active_path());
        self.get_mut_base()
            .set_cpu_mirror_active(failover.cpu_mirror_active());
        action
    }
}

/// Default initialization detecting iPhone (`Ios`) vs iPad (`IpadOs`) at runtime via UIKit.
impl Default for IosPlatform {
    /// Creates an initialized iOS / iPadOS UIKit platform backend.
    ///
    /// # Returns
    ///
    /// - `Self` - Configured UIKit backend.
    fn default() -> Self {
        let hz: f32 = ios_display_refresh_rate_hz();
        let is_sim: bool = ios_is_simulator_target();
        Self {
            resolved_kind: ios_detect_platform_kind(),
            next_id: 1,
            windows: HashMap::new(),
            pending_events: Vec::new(),
            clipboard_cache: None,
            display_link: 0,
            refresh_rate_hz: hz,
            pump_paused: false,
            cached_color_space: 0,
            present_telemetry: IosPresentTelemetry::for_host(
                MobilePresentPath::GpuDirect,
                hz,
                is_sim,
            ),
            failover: MobileFailoverController::default(),
        }
    }
}

/// UIKit system event injection and display-link lifecycle helpers for `IosPlatform`.
impl IosPlatform {
    /// Encodes a `DirectGpuFrameBatch` directly onto the window's `CAMetalLayer` drawable via `NativeGpuDriver` with zero CPU mirror.
    ///
    /// # Arguments
    ///
    /// - `WindowId` - Active UIKit window identifier.
    /// - `&mut NativeGpuDriver` - Live Apple Metal GPU driver.
    /// - `&DirectGpuFrameBatch` - Zero-CPU-mirror direct GPU primitive and atlas batch.
    /// - `Color` - Surface clear color.
    ///
    /// # Returns
    ///
    /// - `Result<bool, PlatformError>` - `Ok(true)` when encoded directly onto `CAMetalDrawable`, `Ok(false)` when fallback is required.
    pub fn present_direct_metal_batch(
        &mut self,
        id: WindowId,
        driver: &mut NativeGpuDriver,
        batch: &DirectGpuFrameBatch,
        clear_color: Color,
    ) -> Result<bool, PlatformError> {
        let layer_ptr: usize = self
            .get_windows()
            .get(&id)
            .map(IosWindowRecord::get_metal_layer)
            .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
        if layer_ptr == 0 || driver.get_device_handle() == 0 || driver.get_pipeline_handle() == 0 {
            let Self {
                present_telemetry,
                failover,
                ..
            } = self;
            let _: MobileFailoverAction = present_telemetry
                .record_fault_with_failover(MobileSurfaceFault::SurfaceLost, failover);
            return Ok(false);
        }
        if driver.get_surface_layer_handle() != layer_ptr {
            driver.attach_metal_layer(layer_ptr);
        }
        if let Some(glyph_atlas) = batch.glyph_r8_atlas_ref()
            && glyph_atlas.get_width() > 0
            && glyph_atlas.get_height() > 0
        {
            let _: bool = driver.upload_texture_dirty_rect(
                GpuAtlasPixelFormat::R8Unorm,
                0,
                (glyph_atlas.get_width(), glyph_atlas.get_height()),
                (0, 0, glyph_atlas.get_width(), glyph_atlas.get_height()),
                glyph_atlas.get_pixels().as_slice(),
                glyph_atlas.get_width() as usize,
            );
        }
        if let Some(img_atlas) = batch.image_rgba8_atlas_ref()
            && img_atlas.get_width() > 0
            && img_atlas.get_height() > 0
        {
            let _: bool = driver.upload_texture_dirty_rect(
                GpuAtlasPixelFormat::Rgba8Unorm,
                2,
                (img_atlas.get_width(), img_atlas.get_height()),
                (0, 0, img_atlas.get_width(), img_atlas.get_height()),
                img_atlas.get_pixels().as_slice(),
                (img_atlas.get_width() as usize).saturating_mul(4),
            );
        }
        let gpu_batches: Vec<GpuBatch> = ios_direct_gpu_batches_from_frame(batch);
        let submit_res: Result<usize, PlatformError> = driver.submit_batches(
            batch.get_viewport_width(),
            batch.get_viewport_height(),
            clear_color,
            &gpu_batches,
        );
        if submit_res.is_err() {
            let Self {
                present_telemetry,
                failover,
                ..
            } = self;
            let _: MobileFailoverAction = present_telemetry
                .record_fault_with_failover(MobileSurfaceFault::SubmitFailed, failover);
            return Ok(false);
        }
        let presented_ns: u64 = driver.get_last_presented_time_ns();
        let gpu_exec_us: u64 = driver.get_last_gpu_exec_ns() / 1_000;
        self.get_mut_failover().mark_frame_presented();
        self.get_mut_present_telemetry()
            .record_direct_metal_present(
                batch,
                gpu_exec_us,
                if presented_ns > 0 {
                    Some(presented_ns)
                } else {
                    None
                },
            );
        Ok(true)
    }

    /// Records `CADisplayLink` actual and target timestamps into iOS presentation telemetry.
    ///
    /// # Arguments
    ///
    /// - `f64` - `CADisplayLink.timestamp` in seconds.
    /// - `f64` - `CADisplayLink.targetTimestamp` in seconds.
    pub fn record_display_link_timing(&mut self, timestamp_secs: f64, target_timestamp_secs: f64) {
        self.get_mut_present_telemetry()
            .record_display_link_tick(timestamp_secs, target_timestamp_secs);
    }

    /// Records `MTLDrawable.presentedTime` from `addPresentedHandler:` with simulator honesty.
    ///
    /// # Arguments
    ///
    /// - `f64` - `MTLDrawable.presentedTime` in seconds.
    pub fn record_metal_presented_time(&mut self, presented_time_secs: f64) {
        self.get_mut_present_telemetry()
            .record_metal_presented_time(presented_time_secs);
    }

    /// Handles a Metal device/surface fault immediately without waiting for perf comparisons while preventing blank frames.
    ///
    /// # Arguments
    ///
    /// - `MobileSurfaceFault` - Observed Metal fault category.
    ///
    /// # Returns
    ///
    /// - `MobileFailoverAction` - Deterministic failover instruction.
    pub fn handle_metal_fault(&mut self, fault: MobileSurfaceFault) -> MobileFailoverAction {
        let Self {
            present_telemetry,
            failover,
            ..
        } = self;
        present_telemetry.record_fault_with_failover(fault, failover)
    }

    /// Attaches a host `CADisplayLink*` pointer, unlocking ProMotion refresh range and automatic background pause.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable iOS/iPadOS platform backend.
    /// - `usize` - Raw `CADisplayLink*` pointer (`0` to detach).
    pub fn attach_display_link(&mut self, display_link: usize) {
        self.set_display_link(display_link);
        if display_link != 0 {
            uikit_configure_display_link_refresh(display_link, self.get_refresh_rate_hz());
            uikit_set_display_link_paused(display_link, self.get_pump_paused());
        }
    }

    /// Updates live safe-area insets across open UIKit windows and enqueues `WindowEvent::SafeAreaChanged`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable iOS/iPadOS platform backend.
    /// - `SafeAreaInsets` - Resolved safe-area insets in logical points.
    pub fn update_safe_area(&mut self, insets: SafeAreaInsets) {
        let mut ids: Vec<WindowId> = Vec::with_capacity(self.get_windows().len());
        for (&wid, rec) in self.get_mut_windows().iter_mut() {
            rec.get_mut_state().set_safe_area(insets);
            ids.push(wid);
        }
        for wid in ids.into_iter() {
            self.get_mut_pending_events()
                .push(WindowEvent::SafeAreaChanged(wid, insets));
        }
    }

    /// Resets transient per-scene UIKit session state on same-process scene disconnect and reconnect.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable iOS/iPadOS platform backend.
    pub fn reset_session(&mut self) {
        self.set_display_link(0);
        self.set_pump_paused(false);
        self.get_mut_windows().clear();
        self.get_mut_pending_events().clear();
    }

    /// Enqueues a normalized UIKit `SystemEvent` to be drained on the next `poll_events()` tick.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable iOS/iPadOS platform backend.
    /// - `SystemEvent` - System event forwarded from `UIApplicationDelegate` / `UISceneDelegate`.
    pub fn push_system_event(&mut self, event: SystemEvent) {
        match &event {
            SystemEvent::Background | SystemEvent::Terminate => self.set_frame_pump_paused(true),
            SystemEvent::Appear | SystemEvent::Foreground => self.set_frame_pump_paused(false),
            _ => {}
        }
        self.get_mut_pending_events()
            .push(WindowEvent::System(event));
    }
}

/// `WindowController` implementation for iOS and iPadOS.
impl WindowController for IosPlatform {
    /// Applies a `WindowCommand` against the active UIKit window scene.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable iOS/iPadOS platform.
    /// - `WindowCommand` - Command to execute.
    ///
    /// # Returns
    ///
    /// - `Result<(), PlatformError>` - Command execution result.
    fn apply_command(&mut self, command: WindowCommand) -> Result<(), PlatformError> {
        match command {
            WindowCommand::SetTitle(id, title) => {
                let rec: &mut IosWindowRecord = self
                    .get_mut_windows()
                    .get_mut(&id)
                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
                rec.get_mut_config().set_title(title);
                Ok(())
            }
            WindowCommand::SetSize(id, width, height) => {
                let rec: &mut IosWindowRecord = self
                    .get_mut_windows()
                    .get_mut(&id)
                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
                let scale: f32 = rec.get_state().get_scale_factor();
                rec.get_mut_state().set_logical_width(width.max(1) as f32);
                rec.get_mut_state().set_logical_height(height.max(1) as f32);
                rec.get_mut_state()
                    .set_physical_width(((width.max(1) as f32) * scale).round() as u32);
                rec.get_mut_state()
                    .set_physical_height(((height.max(1) as f32) * scale).round() as u32);
                Ok(())
            }
            WindowCommand::SetStatusBarStyle(id, style) => {
                let rec: &mut IosWindowRecord = self
                    .get_mut_windows()
                    .get_mut(&id)
                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
                rec.get_mut_config().set_status_bar(style);
                Ok(())
            }
            WindowCommand::SetFullscreen(id, mode) => {
                let rec: &mut IosWindowRecord = self
                    .get_mut_windows()
                    .get_mut(&id)
                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
                rec.get_mut_config().set_fullscreen(mode);
                rec.get_mut_state().set_fullscreen(mode);
                let arg: &str = if mode == FullscreenMode::Windowed {
                    FULLSCREEN_ACTION_OFF
                } else {
                    FULLSCREEN_ACTION_ON
                };
                let _: bool = dispatch_native_action(NATIVE_ACTION_FULLSCREEN, arg, "");
                Ok(())
            }
            WindowCommand::SetRenderMode(id, mode) => {
                let rec: &mut IosWindowRecord = self
                    .get_mut_windows()
                    .get_mut(&id)
                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
                rec.get_mut_config().get_mut_render().set_mode(mode);
                Ok(())
            }
            WindowCommand::RequestRedraw(id) => {
                if !self.get_windows().contains_key(&id) {
                    return Err(PlatformError::WindowNotFound(id.get_value()));
                }
                self.get_mut_pending_events()
                    .push(WindowEvent::RedrawRequested(id));
                Ok(())
            }
            WindowCommand::Close(id) => {
                if self.get_mut_windows().remove(&id).is_none() {
                    return Err(PlatformError::WindowNotFound(id.get_value()));
                }
                Ok(())
            }
            WindowCommand::SetPosition(id, _, _)
            | WindowCommand::SetResizable(id, _)
            | WindowCommand::SetDecorations(id, _)
            | WindowCommand::SetAlwaysOnTop(id, _)
            | WindowCommand::SetVisible(id, _)
            | WindowCommand::SetCursor(id, _)
            | WindowCommand::SetIme(id, _, _) => {
                if !self.get_windows().contains_key(&id) {
                    return Err(PlatformError::WindowNotFound(id.get_value()));
                }
                Ok(())
            }
        }
    }
}

/// `PlatformBackend` implementation covering both iOS Phone and iPadOS Tablet scenes.
impl PlatformBackend for IosPlatform {
    /// Returns `PlatformKind::IpadOs` on iPad or `PlatformKind::Ios` on iPhone.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Platform backend reference.
    ///
    /// # Returns
    ///
    /// - `PlatformKind` - Detected Apple mobile/tablet platform.
    fn kind(&self) -> PlatformKind {
        self.get_resolved_kind()
    }

    /// Returns capability flags reflecting iPadOS (multi-window, hover, keyboard, Apple Pencil) vs iOS.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Platform backend reference.
    ///
    /// # Returns
    ///
    /// - `PlatformCapabilities` - Normalized capability flags.
    fn capabilities(&self) -> PlatformCapabilities {
        PlatformCapabilities::for_platform(self.get_resolved_kind())
    }

    /// Creates a UIKit window scene with safe-area insets and ProMotion refresh metadata tailored to iPhone vs iPadOS.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable iOS/iPadOS platform.
    /// - `&WindowConfig` - Declarative window config.
    ///
    /// # Returns
    ///
    /// - `Result<WindowState, PlatformError>` - Initial window state.
    fn create_window(&mut self, config: &WindowConfig) -> Result<WindowState, PlatformError> {
        let (ui_window, ui_view, metal_layer): (usize, usize, usize) = ios_create_native_handles();
        let is_ipad: bool = self.get_resolved_kind() == PlatformKind::IpadOs;
        let id: WindowId = WindowId::new(self.get_next_id());
        self.set_next_id(self.get_next_id().wrapping_add(1));
        let scale: f32 = ios_screen_scale();
        let hz: f32 = ios_display_refresh_rate_hz();
        self.set_refresh_rate_hz(hz);
        let mut state: WindowState = WindowState::from_config(id, config, scale);
        state
            .get_mut_display()
            .set_refresh_rate_hz(hz.round() as u32);
        state.set_system_theme(ios_system_theme());
        let safe_area: SafeAreaInsets = if is_ipad {
            SafeAreaInsets::new(
                IPADOS_DEFAULT_SAFE_TOP,
                0.0,
                IPADOS_DEFAULT_SAFE_BOTTOM,
                0.0,
            )
        } else {
            SafeAreaInsets::new(IOS_DEFAULT_SAFE_TOP, 0.0, IOS_DEFAULT_SAFE_BOTTOM, 0.0)
        };
        state.set_safe_area(safe_area);
        self.get_mut_windows().insert(
            id,
            IosWindowRecord {
                config: config.clone(),
                state,
                ui_window,
                ui_view,
                metal_layer,
                is_ipad,
            },
        );
        Ok(state)
    }

    /// Queries live `WindowState` for `id`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Platform reference.
    /// - `WindowId` - Window handle.
    ///
    /// # Returns
    ///
    /// - `Option<WindowState>` - Live window state.
    fn window_state(&self, id: WindowId) -> Option<WindowState> {
        self.get_windows().get(&id).map(IosWindowRecord::get_state)
    }

    /// Returns `RawWindowHandle::UiKit` carrying `UIWindow`, `UIView`, `CAMetalLayer`, and `is_ipad`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Platform reference.
    /// - `WindowId` - Window handle.
    ///
    /// # Returns
    ///
    /// - `RawWindowHandle` - UIKit surface handles.
    fn raw_window_handle(&self, id: WindowId) -> RawWindowHandle {
        match self.get_windows().get(&id) {
            Some(rec) => RawWindowHandle::UiKit {
                ui_window: rec.get_ui_window(),
                ui_view: rec.get_ui_view(),
                metal_layer: rec.get_metal_layer(),
                is_ipad: rec.get_is_ipad(),
            },
            None => RawWindowHandle::Headless,
        }
    }

    /// Drains queued UIKit touch, Apple Pencil, keyboard, and lifecycle events.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable platform backend.
    ///
    /// # Returns
    ///
    /// - `Vec<WindowEvent>` - Pending events.
    fn poll_events(&mut self) -> Vec<WindowEvent> {
        take(self.get_mut_pending_events())
    }

    /// Pauses or resumes the attached UIKit `CADisplayLink` frame pump.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable iOS/iPadOS platform backend.
    /// - `bool` - `true` to pause frame ticks in background; `false` to resume.
    fn set_frame_pump_paused(&mut self, paused: bool) {
        self.set_pump_paused(paused);
        uikit_set_display_link_paused(self.get_display_link(), paused);
    }

    /// Returns whether the UIKit frame pump is currently paused for background freeze.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Platform backend reference.
    ///
    /// # Returns
    ///
    /// - `bool` - `true` when paused in background.
    fn is_frame_pump_paused(&self) -> bool {
        self.get_pump_paused()
    }

    /// Presents `framebuffer` directly onto the UIKit `CALayer` / `CAMetalLayer`.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable platform backend.
    /// - `WindowId` - Window handle.
    /// - `&Framebuffer` - Rendered RGBA8 framebuffer.
    ///
    /// # Returns
    ///
    /// - `Result<(), PlatformError>` - Presentation status.
    fn present_framebuffer(
        &mut self,
        id: WindowId,
        framebuffer: &Framebuffer,
    ) -> Result<(), PlatformError> {
        let layer_ptr: usize = self
            .get_windows()
            .get(&id)
            .map(IosWindowRecord::get_metal_layer)
            .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
        let mut color_space: usize = self.get_cached_color_space();
        if color_space == 0 {
            color_space = ios_create_device_rgb_space();
            self.set_cached_color_space(color_space);
        }
        ios_present_cg_image(layer_ptr, color_space, framebuffer)
    }

    /// Reads cached clipboard text.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Platform reference.
    ///
    /// # Returns
    ///
    /// - `Option<String>` - Clipboard contents.
    fn read_clipboard(&self) -> Option<String> {
        let Self {
            clipboard_cache, ..
        } = self;
        clipboard_cache.clone()
    }

    /// Stores `text` in the clipboard cache.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Mutable platform.
    /// - `&str` - Clipboard text.
    ///
    /// # Returns
    ///
    /// - `Result<(), PlatformError>` - Write status.
    fn write_clipboard(&mut self, text: &str) -> Result<(), PlatformError> {
        self.set_clipboard_cache(Some(text.to_string()));
        let _: bool = write_system_clipboard(text);
        Ok(())
    }

    /// Queries the live UIKit light/dark interface style.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Platform reference.
    ///
    /// # Returns
    ///
    /// - `ThemeMode` - Active system appearance.
    fn system_theme(&self) -> ThemeMode {
        ios_system_theme()
    }

    /// Queries the native iOS / iPadOS ProMotion display maximum refresh rate in Hertz.
    ///
    /// # Arguments
    ///
    /// - `&Self` - Platform reference.
    ///
    /// # Returns
    ///
    /// - `f32` - Active display maximum refresh rate in Hertz (`120.0` on ProMotion devices).
    fn display_refresh_rate_hz(&self) -> f32 {
        ios_display_refresh_rate_hz()
    }
}