euv-core 0.47.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
use super::*;

#[cfg(target_env = "ohos")]
#[link(name = "ace_ndk.z")]
unsafe extern "C" {
    /// Retrieves the UTF-8 `<XComponent>` ID string from `OH_NativeXComponent`.
    ///
    /// # Arguments
    ///
    /// - `*mut OhNativeXComponent` - Active XComponent handle.
    /// - `*mut u8` - Output UTF-8 buffer.
    /// - `*mut u64` - In-out buffer capacity / written length.
    ///
    /// # Returns
    ///
    /// - `i32` - `OH_NATIVEXCOMPONENT_RESULT_SUCCESS` (`0`) on success.
    pub fn OH_NativeXComponent_GetXComponentId(
        component: *mut OhNativeXComponent,
        id: *mut u8,
        size: *mut u64,
    ) -> i32;
    /// Queries physical surface `(width, height)` for an ArkUI XComponent window.
    ///
    /// # Arguments
    ///
    /// - `*mut OhNativeXComponent` - Active XComponent handle.
    /// - `*const OhNativeWindow` - Native surface window handle.
    /// - `*mut u64` - Output width in physical pixels.
    /// - `*mut u64` - Output height in physical pixels.
    ///
    /// # Returns
    ///
    /// - `i32` - `0` on success.
    pub fn OH_NativeXComponent_GetXComponentSize(
        component: *mut OhNativeXComponent,
        window: *const OhNativeWindow,
        width: *mut u64,
        height: *mut u64,
    ) -> i32;
    /// Registers surface lifecycle and touch callbacks on `OH_NativeXComponent`.
    ///
    /// # Arguments
    ///
    /// - `*mut OhNativeXComponent` - Active XComponent handle.
    /// - `*mut OhNativeXComponentCallback` - Static callback function table.
    ///
    /// # Returns
    ///
    /// - `i32` - `0` on success.
    pub fn OH_NativeXComponent_RegisterCallback(
        component: *mut OhNativeXComponent,
        callback: *mut OhNativeXComponentCallback,
    ) -> i32;
    /// Extracts the latest multi-touch payload from `OH_NativeXComponent`.
    ///
    /// # Arguments
    ///
    /// - `*mut OhNativeXComponent` - Active XComponent handle.
    /// - `*const OhNativeWindow` - Associated native window handle.
    /// - `*mut OhNativeXComponentTouchEvent` - Output touch event struct.
    ///
    /// # Returns
    ///
    /// - `i32` - `0` on success.
    pub fn OH_NativeXComponent_GetTouchEvent(
        component: *mut OhNativeXComponent,
        window: *const OhNativeWindow,
        touch_event: *mut OhNativeXComponentTouchEvent,
    ) -> i32;
}

#[cfg(target_env = "ohos")]
#[link(name = "native_window")]
unsafe extern "C" {
    /// Configures `OHNativeWindow` geometry or pixel format options (`SET_BUFFER_GEOMETRY`, `SET_FORMAT`).
    ///
    /// # Arguments
    ///
    /// - `*mut OhNativeWindow` - Active native window handle.
    /// - `i32` - `NativeWindowOperation` option code.
    /// - `...` - Variadic option value arguments.
    ///
    /// # Returns
    ///
    /// - `i32` - `0` on success.
    pub fn OH_NativeWindow_NativeWindowHandleOpt(
        window: *mut OhNativeWindow,
        code: i32,
        ...
    ) -> i32;
    /// Requests the next writable producer buffer from `OHNativeWindow`.
    ///
    /// # Arguments
    ///
    /// - `*mut OhNativeWindow` - Active native window handle.
    /// - `*mut *mut OhNativeWindowBuffer` - Output native buffer pointer.
    /// - `*mut i32` - Output acquire sync fence file descriptor.
    ///
    /// # Returns
    ///
    /// - `i32` - `0` on success.
    pub fn OH_NativeWindow_NativeWindowRequestBuffer(
        window: *mut OhNativeWindow,
        buffer: *mut *mut OhNativeWindowBuffer,
        fence_fd: *mut i32,
    ) -> i32;
    /// Flushes a rendered producer buffer to HarmonyOS RenderService with optional damage `region`.
    ///
    /// # Arguments
    ///
    /// - `*mut OhNativeWindow` - Active native window handle.
    /// - `*mut OhNativeWindowBuffer` - Producer buffer obtained via `RequestBuffer`.
    /// - `i32` - Release sync fence file descriptor (`-1` when CPU writes are complete).
    /// - `OhRegion` - Damaged pixel region descriptor.
    ///
    /// # Returns
    ///
    /// - `i32` - `0` on success.
    pub fn OH_NativeWindow_NativeWindowFlushBuffer(
        window: *mut OhNativeWindow,
        buffer: *mut OhNativeWindowBuffer,
        fence_fd: i32,
        region: OhRegion,
    ) -> i32;
    /// Aborts a previously requested `OHNativeWindowBuffer` without presenting it.
    ///
    /// # Arguments
    ///
    /// - `*mut OhNativeWindow` - Active native window handle.
    /// - `*mut OhNativeWindowBuffer` - Buffer to return cleanly to the queue.
    ///
    /// # Returns
    ///
    /// - `i32` - `0` on success.
    pub fn OH_NativeWindow_NativeWindowAbortBuffer(
        window: *mut OhNativeWindow,
        buffer: *mut OhNativeWindowBuffer,
    ) -> i32;
    /// Resolves the `OhBufferHandle` descriptor backing `buffer`.
    ///
    /// # Arguments
    ///
    /// - `*mut OhNativeWindowBuffer` - Requested native window buffer.
    ///
    /// # Returns
    ///
    /// - `*mut OhBufferHandle` - Buffer handle pointer or null.
    pub fn OH_NativeWindow_GetBufferHandleFromNative(
        buffer: *mut OhNativeWindowBuffer,
    ) -> *mut OhBufferHandle;
}

#[cfg(target_env = "ohos")]
#[link(name = "native_vsync")]
unsafe extern "C" {
    /// Creates an OpenHarmony `OH_NativeVSync` display refresh channel.
    ///
    /// # Arguments
    ///
    /// - `*const c_char` - Channel name bytes.
    /// - `u32` - Byte length of `name`.
    ///
    /// # Returns
    ///
    /// - `*mut OhNativeVSync` - Newly created VSync channel or null.
    pub fn OH_NativeVSync_Create(name: *const c_char, length: u32) -> *mut OhNativeVSync;
    /// Destroys a previously created `OH_NativeVSync` channel.
    ///
    /// # Arguments
    ///
    /// - `*mut OhNativeVSync` - Active VSync channel handle.
    pub fn OH_NativeVSync_Destroy(native_vsync: *mut OhNativeVSync);
    /// Requests a single callback invocation on the next display hardware VSync tick.
    ///
    /// # Arguments
    ///
    /// - `*mut OhNativeVSync` - Active VSync channel handle.
    /// - `unsafe extern "C" fn(i64, *mut c_void)` - VSync timestamp callback.
    /// - `*mut c_void` - Opaque user context pointer.
    ///
    /// # Returns
    ///
    /// - `i32` - `0` on success.
    pub fn OH_NativeVSync_RequestFrame(
        native_vsync: *mut OhNativeVSync,
        callback: unsafe extern "C" fn(i64, *mut c_void),
        data: *mut c_void,
    ) -> i32;
    /// Queries the nominal VSync display refresh period in nanoseconds.
    ///
    /// # Arguments
    ///
    /// - `*mut OhNativeVSync` - Active VSync channel handle.
    /// - `*mut i64` - Output refresh period in nanoseconds.
    ///
    /// # Returns
    ///
    /// - `i32` - `0` on success.
    pub fn OH_NativeVSync_GetPeriod(native_vsync: *mut OhNativeVSync, period: *mut i64) -> i32;
}

#[cfg(target_env = "ohos")]
unsafe extern "C" {
    /// Closes a POSIX file descriptor (used to release `OHNativeWindow` acquire fence FDs).
    ///
    /// # Arguments
    ///
    /// - `i32` - File descriptor to close.
    ///
    /// # Returns
    ///
    /// - `i32` - `0` on success.
    fn close(fd: i32) -> i32;
    /// Polls a POSIX file descriptor set until ready or timed out.
    ///
    /// # Arguments
    ///
    /// - `*mut c_void` - Poll descriptor array.
    /// - `usize` - Entry count.
    /// - `i32` - Timeout in milliseconds.
    ///
    /// # Returns
    ///
    /// - `i32` - Number of ready descriptors, `0` on timeout, or `-1` on error.
    fn poll(fds: *mut c_void, nfds: usize, timeout: i32) -> i32;
    /// Maps a DMA-BUF / shared memory file descriptor into process address space.
    ///
    /// # Arguments
    ///
    /// - `*mut c_void` - Hint address (`null_mut()`).
    /// - `usize` - Mapping length in bytes.
    /// - `i32` - Protection flags (`HARMONY_PROT_READ_WRITE`).
    /// - `i32` - Mapping flags (`HARMONY_MAP_SHARED`).
    /// - `i32` - Buffer handle file descriptor.
    /// - `isize` - Byte offset (`0`).
    ///
    /// # Returns
    ///
    /// - `*mut c_void` - Mapped pointer or `MAP_FAILED`.
    fn mmap(
        addr: *mut c_void,
        len: usize,
        prot: i32,
        flags: i32,
        fd: i32,
        offset: isize,
    ) -> *mut c_void;
    /// Unmaps a previously `mmap`'d buffer region.
    ///
    /// # Arguments
    ///
    /// - `*mut c_void` - Base address returned by `mmap`.
    /// - `usize` - Mapping length in bytes.
    ///
    /// # Returns
    ///
    /// - `i32` - `0` on success.
    fn munmap(addr: *mut c_void, len: usize) -> i32;
}

/// Converts a HarmonyOS `HarmonyAvoidArea` (in physical pixels) into logical `SafeAreaInsets` respecting device form factor.
///
/// # Arguments
///
/// - `HarmonyDeviceType` - Active HarmonyOS device form factor.
/// - `HarmonyAvoidArea` - Physical-pixel avoid area reported by `@ohos.window`.
/// - `f32` - Active display density (`vp -> px`).
/// - `u32` - Logical viewport width in `vp`.
/// - `u32` - Logical viewport height in `vp`.
/// - `bool` - Whether edge-to-edge immersive fullscreen mode is active.
///
/// # Returns
///
/// - `SafeAreaInsets` - Sanitized safe-area insets in logical `vp`.
#[must_use]
pub fn resolve_harmony_avoid_area(
    device_type: HarmonyDeviceType,
    avoid: HarmonyAvoidArea,
    density: f32,
    logical_width: u32,
    logical_height: u32,
    immersive_fullscreen: bool,
) -> SafeAreaInsets {
    let scale: f32 = if density.is_finite() && density >= 0.75 {
        density
    } else {
        1.0
    };
    let kb_vp: f32 = (avoid.get_keyboard_px() as f32) / scale;
    if immersive_fullscreen {
        return SafeAreaInsets::new(0.0, 0.0, kb_vp, 0.0);
    }
    let top_vp: f32 = (avoid.get_top_px() as f32) / scale;
    let right_vp: f32 = (avoid.get_right_px() as f32) / scale;
    let bottom_vp: f32 = ((avoid.get_bottom_px() as f32) / scale).max(kb_vp);
    let left_vp: f32 = (avoid.get_left_px() as f32) / scale;
    match device_type {
        HarmonyDeviceType::Watch => {
            let round_safe: SafeAreaInsets = compute_wearable_safe_area(
                WearableShape::Round,
                logical_width.max(1) as f32,
                logical_height.max(1) as f32,
                0.0,
            );
            SafeAreaInsets::new(
                top_vp.max(round_safe.get_top()),
                right_vp.max(round_safe.get_right()),
                bottom_vp.max(round_safe.get_bottom()),
                left_vp.max(round_safe.get_left()),
            )
        }
        HarmonyDeviceType::Tv => SafeAreaInsets::new(
            top_vp.max(HARMONY_TV_OVERSCAN_VP),
            right_vp.max(HARMONY_TV_OVERSCAN_VP),
            bottom_vp.max(HARMONY_TV_OVERSCAN_VP),
            left_vp.max(HARMONY_TV_OVERSCAN_VP),
        ),
        HarmonyDeviceType::Automotive => SafeAreaInsets::new(
            top_vp.max(HARMONY_CAR_DOCK_VP),
            right_vp,
            bottom_vp.max(HARMONY_CAR_DOCK_VP),
            left_vp,
        ),
        HarmonyDeviceType::Phone | HarmonyDeviceType::Foldable => SafeAreaInsets::new(
            top_vp.max(HARMONY_PHONE_SAFE_TOP_VP),
            right_vp,
            bottom_vp.max(HARMONY_PHONE_SAFE_BOTTOM_VP),
            left_vp,
        ),
        HarmonyDeviceType::Tablet | HarmonyDeviceType::Pc2In1 => {
            SafeAreaInsets::new(top_vp, right_vp, bottom_vp, left_vp)
        }
    }
}

/// Maps an OpenHarmony `OH_NativeXComponent` key code (`KEYCODE_*`) into a unified EUV `KeyCode`.
///
/// # Arguments
///
/// - `i32` - OpenHarmony NDK key code.
///
/// # Returns
///
/// - `KeyCode` - Normalized EUV key code.
#[must_use]
pub const fn harmony_keycode_to_euv(ohos_code: i32) -> KeyCode {
    match ohos_code {
        HARMONY_KEYCODE_BACK => KeyCode::Back,
        HARMONY_KEYCODE_DPAD_UP => KeyCode::ArrowUp,
        HARMONY_KEYCODE_DPAD_DOWN => KeyCode::ArrowDown,
        HARMONY_KEYCODE_DPAD_LEFT => KeyCode::ArrowLeft,
        HARMONY_KEYCODE_DPAD_RIGHT => KeyCode::ArrowRight,
        HARMONY_KEYCODE_DPAD_CENTER | HARMONY_KEYCODE_ENTER => KeyCode::Enter,
        HARMONY_KEYCODE_TAB => KeyCode::Tab,
        HARMONY_KEYCODE_SPACE => KeyCode::Space,
        HARMONY_KEYCODE_DEL => KeyCode::Backspace,
        HARMONY_KEYCODE_FORWARD_DEL => KeyCode::Delete,
        HARMONY_KEYCODE_ESCAPE => KeyCode::Escape,
        _ => KeyCode::Unknown,
    }
}

/// Maps an OpenHarmony `AbilityConstant.MemoryLevel` integer into a normalized `MemoryPressure`.
///
/// # Arguments
///
/// - `i32` - OpenHarmony memory level (`0`=MODERATE, `1`=LOW, `2`=CRITICAL).
///
/// # Returns
///
/// - `MemoryPressure` - Normalized memory pressure severity.
#[must_use]
pub const fn harmony_memory_level_to_pressure(level: i32) -> MemoryPressure {
    match level {
        HARMONY_MEMORY_CRITICAL => MemoryPressure::Critical,
        HARMONY_MEMORY_MODERATE | HARMONY_MEMORY_LOW => MemoryPressure::Warning,
        _ => MemoryPressure::Normal,
    }
}

/// Copies RGBA8 pixels from `framebuffer` into a strided destination buffer, optionally restricted to `dirty_rect`.
///
/// # Arguments
///
/// - `&Framebuffer` - Source RGBA8 framebuffer.
/// - `&mut [u8]` - Destination mapped buffer memory.
/// - `u32` - Destination surface width in pixels.
/// - `u32` - Destination surface height in pixels.
/// - `usize` - Destination row stride in bytes.
/// - `Option<Rect>` - Optional dirty pixel rectangle to copy; `None` copies the full overlapping intersection.
///
/// # Returns
///
/// - `usize` - Total pixel bytes written into `dst`.
pub fn harmony_copy_rgba_to_strided_buffer(
    framebuffer: &Framebuffer,
    dst: &mut [u8],
    dst_width: u32,
    dst_height: u32,
    dst_stride_bytes: usize,
    dirty_rect: Option<Rect>,
) -> usize {
    let copy_w: u32 = framebuffer.get_width().min(dst_width);
    let copy_h: u32 = framebuffer.get_height().min(dst_height);
    if copy_w == 0 || copy_h == 0 || dst_stride_bytes < 4 {
        return 0;
    }
    let (x0, y0, x1, y1): (u32, u32, u32, u32) = match dirty_rect {
        Some(r) => {
            let rx0: u32 = (r.get_x().floor().max(0.0) as u32).min(copy_w);
            let ry0: u32 = (r.get_y().floor().max(0.0) as u32).min(copy_h);
            let rx1: u32 = ((r.get_x() + r.get_width()).ceil().max(0.0) as u32).min(copy_w);
            let ry1: u32 = ((r.get_y() + r.get_height()).ceil().max(0.0) as u32).min(copy_h);
            if rx1 <= rx0 || ry1 <= ry0 {
                return 0;
            }
            (rx0, ry0, rx1, ry1)
        }
        None => (0, 0, copy_w, copy_h),
    };
    let src_bytes: &[u8] = framebuffer.get_pixels().as_slice();
    let src_stride_bytes: usize = (framebuffer.get_width() as usize).saturating_mul(4);
    let row_bytes: usize = ((x1 - x0) as usize).saturating_mul(4);
    let x_offset_bytes: usize = (x0 as usize).saturating_mul(4);
    let mut written: usize = 0;
    for row in y0..y1 {
        let src_start: usize = (row as usize)
            .saturating_mul(src_stride_bytes)
            .saturating_add(x_offset_bytes);
        let dst_start: usize = (row as usize)
            .saturating_mul(dst_stride_bytes)
            .saturating_add(x_offset_bytes);
        let src_end: usize = src_start.saturating_add(row_bytes);
        let dst_end: usize = dst_start.saturating_add(row_bytes);
        if src_end <= src_bytes.len() && dst_end <= dst.len() {
            dst[dst_start..dst_end].copy_from_slice(&src_bytes[src_start..src_end]);
            written = written.saturating_add(row_bytes);
        }
    }
    written
}

/// Creates a live `OH_NativeVSync` display refresh channel on OpenHarmony (`0` on non-OHOS hosts).
///
/// # Returns
///
/// - `usize` - Raw `OH_NativeVSync*` pointer or `0` if unavailable.
#[must_use]
pub(crate) fn harmony_create_native_vsync() -> usize {
    #[cfg(target_env = "ohos")]
    {
        // SAFETY: Passes valid UTF-8 byte slice and exact length to `OH_NativeVSync_Create`.
        unsafe {
            let ptr: *mut OhNativeVSync = OH_NativeVSync_Create(
                HARMONY_VSYNC_NAME.as_ptr().cast::<c_char>(),
                HARMONY_VSYNC_NAME.len() as u32,
            );
            ptr as usize
        }
    }
    #[cfg(not(target_env = "ohos"))]
    {
        0
    }
}

/// Destroys a previously created `OH_NativeVSync*` handle on OpenHarmony.
///
/// # Arguments
///
/// - `usize` - Raw `OH_NativeVSync*` pointer (`0` is a no-op).
pub(crate) fn harmony_destroy_native_vsync(vsync_handle: usize) {
    #[cfg(target_env = "ohos")]
    if vsync_handle != 0 {
        // SAFETY: `vsync_handle` was returned by `OH_NativeVSync_Create` and is destroyed at most once.
        unsafe {
            OH_NativeVSync_Destroy(vsync_handle as *mut OhNativeVSync);
        }
    }
    #[cfg(not(target_env = "ohos"))]
    {
        let _: usize = vsync_handle;
    }
}

/// Queries the hardware VSync display refresh rate in Hertz from `OH_NativeVSync_GetPeriod`.
///
/// # Arguments
///
/// - `usize` - Raw `OH_NativeVSync*` pointer.
///
/// # Returns
///
/// - `Option<f32>` - Detected refresh rate in Hertz, or `None` when off-device or unsupported.
#[must_use]
pub(crate) fn harmony_query_vsync_refresh_hz(vsync_handle: usize) -> Option<f32> {
    if vsync_handle == 0 {
        return None;
    }
    #[cfg(target_env = "ohos")]
    {
        let mut period_ns: i64 = 0;
        // SAFETY: Valid `OH_NativeVSync*` handle and aligned `i64` out-pointer.
        let rc: i32 =
            unsafe { OH_NativeVSync_GetPeriod(vsync_handle as *mut OhNativeVSync, &mut period_ns) };
        if rc == 0
            && period_ns >= HARMONY_VSYNC_MIN_PERIOD_NS
            && period_ns <= HARMONY_VSYNC_MAX_PERIOD_NS
        {
            let hz: f32 = (1_000_000_000.0_f64 / (period_ns as f64)) as f32;
            return Some(hz.clamp(MIN_REFRESH_RATE_HZ, MAX_REFRESH_RATE_HZ));
        }
        None
    }
    #[cfg(not(target_env = "ohos"))]
    {
        None
    }
}

/// Requests a single `OH_NativeVSync` hardware frame callback on OpenHarmony.
///
/// # Arguments
///
/// - `usize` - Raw `OH_NativeVSync*` pointer.
/// - `unsafe extern "C" fn(i64, usize)` - Native VSync callback function pointer receiving `(timestamp_ns, user_data)`.
/// - `usize` - Opaque user context pointer passed to `callback`.
///
/// # Returns
///
/// - `bool` - `true` if `OH_NativeVSync_RequestFrame` accepted the request.
pub(crate) fn harmony_request_vsync_frame(
    vsync_handle: usize,
    callback: unsafe extern "C" fn(i64, usize),
    data: usize,
) -> bool {
    if vsync_handle == 0 {
        return false;
    }
    #[cfg(target_env = "ohos")]
    {
        // SAFETY: Caller supplies a valid `OH_NativeVSync*` handle and C ABI callback pointer (`usize` has pointer ABI).
        unsafe {
            let c_cb: unsafe extern "C" fn(i64, *mut c_void) = transmute(callback);
            OH_NativeVSync_RequestFrame(
                vsync_handle as *mut OhNativeVSync,
                c_cb,
                data as *mut c_void,
            ) == 0
        }
    }
    #[cfg(not(target_env = "ohos"))]
    {
        let _: (unsafe extern "C" fn(i64, usize), usize) = (callback, data);
        false
    }
}

/// Presents an RGBA8 `Framebuffer` directly to an OpenHarmony `OHNativeWindow*` with proper pixel mapping and acquire fence cleanup.
///
/// # Arguments
///
/// - `usize` - Raw `OHNativeWindow*` pointer (`0` returns `Ok(())` for offscreen hosts).
/// - `&Framebuffer` - Rendered RGBA8 framebuffer.
/// - `&mut u32` - Cached surface width avoiding redundant `SET_BUFFER_GEOMETRY` calls.
/// - `&mut u32` - Cached surface height avoiding redundant `SET_BUFFER_GEOMETRY` calls.
/// - `Option<Rect>` - Optional dirty pixel sub-rectangle for partial buffer upload and damage flush.
///
/// # Returns
///
/// - `Result<(), PlatformError>` - Presentation status.
pub(crate) fn harmony_present_native_window(
    native_window: usize,
    framebuffer: &Framebuffer,
    cached_w: &mut u32,
    cached_h: &mut u32,
    dirty_rect: Option<Rect>,
) -> Result<(), PlatformError> {
    if native_window == 0 {
        return Ok(());
    }
    #[cfg(target_env = "ohos")]
    {
        let fb_w: u32 = framebuffer.get_width();
        let fb_h: u32 = framebuffer.get_height();
        let win: *mut OhNativeWindow = native_window as *mut OhNativeWindow;
        // SAFETY: Invokes OpenHarmony `libnative_window.so` producer buffer lifecycle with verified pointers and guaranteed fence/mmap cleanup.
        unsafe {
            if *cached_w != fb_w || *cached_h != fb_h {
                let _: i32 = OH_NativeWindow_NativeWindowHandleOpt(
                    win,
                    HARMONY_NW_OPT_SET_BUFFER_GEOMETRY,
                    fb_w as i32,
                    fb_h as i32,
                );
                let _: i32 = OH_NativeWindow_NativeWindowHandleOpt(
                    win,
                    HARMONY_NW_OPT_SET_FORMAT,
                    HARMONY_PIXEL_FMT_RGBA_8888,
                );
                *cached_w = fb_w;
                *cached_h = fb_h;
            }
            let mut buffer: *mut OhNativeWindowBuffer = null_mut();
            let mut fence_fd: i32 = -1;
            let req_rc: i32 =
                OH_NativeWindow_NativeWindowRequestBuffer(win, &mut buffer, &mut fence_fd);
            if fence_fd >= 0 {
                let mut pfd: HarmonyPollFd = HarmonyPollFd {
                    fd: fence_fd,
                    events: HARMONY_POLLIN,
                    revents: 0,
                };
                let _: i32 = poll(
                    (&mut pfd as *mut HarmonyPollFd).cast::<c_void>(),
                    1,
                    HARMONY_FENCE_POLL_TIMEOUT_MS,
                );
                let _: i32 = close(fence_fd);
            }
            if req_rc != 0 || buffer.is_null() {
                return Err(PlatformError::SurfaceError(
                    ERR_HARMONY_SURFACE_POST.to_string(),
                ));
            }
            let handle_ptr: *mut OhBufferHandle = OH_NativeWindow_GetBufferHandleFromNative(buffer);
            if handle_ptr.is_null() {
                let _: i32 = OH_NativeWindow_NativeWindowAbortBuffer(win, buffer);
                return Err(PlatformError::SurfaceError(
                    ERR_HARMONY_SURFACE_POST.to_string(),
                ));
            }
            let handle: OhBufferHandle = *handle_ptr;
            let dst_w: u32 = handle.width.max(0) as u32;
            let dst_h: u32 = handle.height.max(0) as u32;
            let dst_stride: usize = handle.stride.max(0) as usize;
            let required_bytes: usize = dst_stride.saturating_mul(dst_h as usize);
            let map_bytes: usize = (handle.size.max(0) as usize).max(required_bytes);
            let mut mapped_ptr: *mut c_void = null_mut();
            let mut needs_munmap: bool = false;
            if handle.vir_addr != 0 {
                mapped_ptr = handle.vir_addr as *mut c_void;
            } else if handle.fd >= 0 && map_bytes > 0 {
                let addr: *mut c_void = mmap(
                    null_mut(),
                    map_bytes,
                    HARMONY_PROT_READ_WRITE,
                    HARMONY_MAP_SHARED,
                    handle.fd,
                    0,
                );
                if !addr.is_null() && (addr as usize) != HARMONY_MAP_FAILED {
                    mapped_ptr = addr;
                    needs_munmap = true;
                }
            }
            if !mapped_ptr.is_null() && map_bytes > 0 {
                let dst_slice: &mut [u8] = from_raw_parts_mut(mapped_ptr.cast::<u8>(), map_bytes);
                let _: usize = harmony_copy_rgba_to_strided_buffer(
                    framebuffer,
                    dst_slice,
                    dst_w,
                    dst_h,
                    dst_stride,
                    dirty_rect,
                );
                if needs_munmap {
                    let _: i32 = munmap(mapped_ptr, map_bytes);
                }
            } else {
                let _: i32 = OH_NativeWindow_NativeWindowAbortBuffer(win, buffer);
                return Err(PlatformError::SurfaceError(
                    ERR_HARMONY_SURFACE_POST.to_string(),
                ));
            }
            let damage_rect: OhRegionRect = match dirty_rect {
                Some(r) => OhRegionRect {
                    x: r.get_x().floor().max(0.0) as i32,
                    y: r.get_y().floor().max(0.0) as i32,
                    w: r.get_width().ceil().max(1.0) as u32,
                    h: r.get_height().ceil().max(1.0) as u32,
                },
                None => OhRegionRect::default(),
            };
            let region: OhRegion = if dirty_rect.is_some() {
                OhRegion {
                    rects: &damage_rect,
                    rect_number: 1,
                }
            } else {
                OhRegion {
                    rects: null(),
                    rect_number: 0,
                }
            };
            let flush_rc: i32 = OH_NativeWindow_NativeWindowFlushBuffer(win, buffer, -1, region);
            if flush_rc != 0 {
                let _: i32 = OH_NativeWindow_NativeWindowAbortBuffer(win, buffer);
                return Err(PlatformError::SurfaceError(
                    ERR_HARMONY_SURFACE_POST.to_string(),
                ));
            }
        }
        Ok(())
    }
    #[cfg(not(target_env = "ohos"))]
    {
        let _: (&Framebuffer, &mut u32, &mut u32, Option<Rect>) =
            (framebuffer, cached_w, cached_h, dirty_rect);
        Ok(())
    }
}