Skip to main content

euv_core/platform/harmony/
impl.rs

1use super::*;
2
3/// Canonical `module.json5` metadata and form-factor mapping for `HarmonyDeviceType`.
4impl HarmonyDeviceType {
5    /// Returns the canonical HarmonyOS `module.json5` `deviceTypes` identifier string.
6    ///
7    /// # Arguments
8    ///
9    /// - `&Self` - HarmonyOS device type.
10    ///
11    /// # Returns
12    ///
13    /// - `&'static str` - Canonical `deviceType` string.
14    #[must_use]
15    pub const fn as_str(&self) -> &'static str {
16        match *self {
17            Self::Phone => HARMONY_DEVICE_PHONE,
18            Self::Tablet => HARMONY_DEVICE_TABLET,
19            Self::Pc2In1 => HARMONY_DEVICE_PC_2IN1,
20            Self::Foldable => HARMONY_DEVICE_FOLDABLE,
21            Self::Watch => HARMONY_DEVICE_WATCH,
22            Self::Tv => HARMONY_DEVICE_TV,
23            Self::Automotive => HARMONY_DEVICE_AUTOMOTIVE,
24        }
25    }
26
27    /// Maps this HarmonyOS device category onto the unified cross-platform `DeviceFormFactor`.
28    ///
29    /// # Arguments
30    ///
31    /// - `&Self` - HarmonyOS device type.
32    ///
33    /// # Returns
34    ///
35    /// - `DeviceFormFactor` - Normalized EUV device form factor.
36    #[must_use]
37    pub const fn form_factor(&self) -> DeviceFormFactor {
38        match *self {
39            Self::Phone => DeviceFormFactor::Phone,
40            Self::Tablet => DeviceFormFactor::Tablet,
41            Self::Pc2In1 => DeviceFormFactor::Desktop,
42            Self::Foldable => DeviceFormFactor::Foldable,
43            Self::Watch => DeviceFormFactor::Watch,
44            Self::Tv => DeviceFormFactor::Tv,
45            Self::Automotive => DeviceFormFactor::Automotive,
46        }
47    }
48
49    /// Parses a canonical HarmonyOS device type or alias (`"phone"`, `"tablet"`, `"2in1"`, `"pc"`, `"harmony-pc"`, `"foldable"`, `"wearable"`, `"watch"`, `"tv"`, `"car"`).
50    ///
51    /// # Arguments
52    ///
53    /// - `&str` - Case-insensitive device identifier or alias.
54    ///
55    /// # Returns
56    ///
57    /// - `Option<Self>` - Matching `HarmonyDeviceType`, if recognized.
58    #[must_use]
59    pub fn from_str_id(name: &str) -> Option<Self> {
60        let lower: String = name.trim().to_ascii_lowercase();
61        match lower.as_str() {
62            HARMONY_DEVICE_PHONE => Some(Self::Phone),
63            HARMONY_DEVICE_TABLET => Some(Self::Tablet),
64            HARMONY_DEVICE_PC_2IN1
65            | HARMONY_ALIAS_PC
66            | HARMONY_ALIAS_HARMONY_PC
67            | HARMONY_ALIAS_DESKTOP => Some(Self::Pc2In1),
68            HARMONY_DEVICE_FOLDABLE => Some(Self::Foldable),
69            HARMONY_DEVICE_WATCH | HARMONY_ALIAS_WATCH => Some(Self::Watch),
70            HARMONY_DEVICE_TV | HARMONY_ALIAS_VISION => Some(Self::Tv),
71            HARMONY_DEVICE_AUTOMOTIVE | HARMONY_ALIAS_AUTOMOTIVE => Some(Self::Automotive),
72            _ => None,
73        }
74    }
75
76    /// Returns all 7 supported HarmonyOS / OpenHarmony device form factors.
77    ///
78    /// # Returns
79    ///
80    /// - `[Self; 7]` - Array covering Phone, Tablet, PC/2-in-1, Foldable, Watch, TV, and Automotive.
81    #[must_use]
82    pub const fn all_device_types() -> [Self; 7] {
83        [
84            Self::Phone,
85            Self::Tablet,
86            Self::Pc2In1,
87            Self::Foldable,
88            Self::Watch,
89            Self::Tv,
90            Self::Automotive,
91        ]
92    }
93}
94
95/// Hardware presets for `HarmonyDeviceProfile`.
96impl HarmonyDeviceProfile {
97    /// Returns the canonical viewport, density, refresh rate, and graphics API profile for `device_type`.
98    ///
99    /// # Arguments
100    ///
101    /// - `HarmonyDeviceType` - Target HarmonyOS device category.
102    ///
103    /// # Returns
104    ///
105    /// - `Self` - Preconfigured HarmonyOS device profile.
106    #[must_use]
107    pub const fn for_device_type(device_type: HarmonyDeviceType) -> Self {
108        match device_type {
109            HarmonyDeviceType::Phone => Self {
110                device_type,
111                logical_width: 390,
112                logical_height: 844,
113                density: 3.0,
114                refresh_rate_hz: 120.0,
115                graphics_api: HarmonyGraphicsApi::OpenGlEs3,
116            },
117            HarmonyDeviceType::Tablet => Self {
118                device_type,
119                logical_width: 960,
120                logical_height: 640,
121                density: 2.0,
122                refresh_rate_hz: 120.0,
123                graphics_api: HarmonyGraphicsApi::Vulkan,
124            },
125            HarmonyDeviceType::Pc2In1 => Self {
126                device_type,
127                logical_width: 1440,
128                logical_height: 900,
129                density: 2.0,
130                refresh_rate_hz: 120.0,
131                graphics_api: HarmonyGraphicsApi::Vulkan,
132            },
133            HarmonyDeviceType::Foldable => Self {
134                device_type,
135                logical_width: 712,
136                logical_height: 800,
137                density: 3.0,
138                refresh_rate_hz: 120.0,
139                graphics_api: HarmonyGraphicsApi::Vulkan,
140            },
141            HarmonyDeviceType::Watch => Self {
142                device_type,
143                logical_width: 233,
144                logical_height: 233,
145                density: 2.0,
146                refresh_rate_hz: 60.0,
147                graphics_api: HarmonyGraphicsApi::OpenGlEs3,
148            },
149            HarmonyDeviceType::Tv => Self {
150                device_type,
151                logical_width: 1920,
152                logical_height: 1080,
153                density: 2.0,
154                refresh_rate_hz: 120.0,
155                graphics_api: HarmonyGraphicsApi::Vulkan,
156            },
157            HarmonyDeviceType::Automotive => Self {
158                device_type,
159                logical_width: 1920,
160                logical_height: 720,
161                density: 1.5,
162                refresh_rate_hz: 60.0,
163                graphics_api: HarmonyGraphicsApi::OpenGlEs3,
164            },
165        }
166    }
167}
168
169/// Default `HarmonyPlatform` configured for `HarmonyDeviceType::Phone`.
170impl Default for HarmonyPlatform {
171    /// Creates a default HarmonyOS smartphone platform backend.
172    ///
173    /// # Returns
174    ///
175    /// - `Self` - Default `HarmonyPlatform`.
176    fn default() -> Self {
177        Self::for_device_type(HarmonyDeviceType::Phone)
178    }
179}
180
181/// ArkUI XComponent binding, `avoidArea` safe-area, foldable transition, touch/key/IME, and UIAbility lifecycle hooks for `HarmonyPlatform`.
182impl HarmonyPlatform {
183    /// Creates a `HarmonyPlatform` configured for any of the 7 HarmonyOS device form factors.
184    ///
185    /// # Arguments
186    ///
187    /// - `HarmonyDeviceType` - Target HarmonyOS device category.
188    ///
189    /// # Returns
190    ///
191    /// - `Self` - Configured HarmonyOS platform backend.
192    #[must_use]
193    pub fn for_device_type(device_type: HarmonyDeviceType) -> Self {
194        let mut profile: HarmonyDeviceProfile = HarmonyDeviceProfile::for_device_type(device_type);
195        let vsync_handle: usize = harmony_create_native_vsync();
196        if let Some(live_hz) = harmony_query_vsync_refresh_hz(vsync_handle) {
197            profile.set_refresh_rate_hz(live_hz);
198        }
199        let safe_area: SafeAreaInsets = resolve_harmony_avoid_area(
200            device_type,
201            HarmonyAvoidArea::default(),
202            profile.get_density(),
203            profile.get_logical_width(),
204            profile.get_logical_height(),
205            false,
206        );
207        let initial_window_mode: HarmonyWindowMode = match device_type {
208            HarmonyDeviceType::Pc2In1 => HarmonyWindowMode::Floating,
209            HarmonyDeviceType::Tablet | HarmonyDeviceType::Foldable => {
210                HarmonyWindowMode::Fullscreen
211            }
212            HarmonyDeviceType::Phone
213            | HarmonyDeviceType::Watch
214            | HarmonyDeviceType::Tv
215            | HarmonyDeviceType::Automotive => HarmonyWindowMode::Fullscreen,
216        };
217        Self {
218            profile,
219            fold_state: HarmonyFoldState::Expanded,
220            window_mode: initial_window_mode,
221            active_modifiers: Modifiers::default(),
222            last_cursor: CursorIcon::Default,
223            outbound_commands: Vec::new(),
224            attached_native_window: 0,
225            attached_xcomponent: 0,
226            safe_area,
227            lifecycle: MobileSessionLifecycle::default(),
228            next_id: 1,
229            primary_window: None,
230            windows: HashMap::new(),
231            pending_events: Vec::new(),
232            clipboard: None,
233            storage: HashMap::new(),
234            route_stack: vec![HARMONY_DEFAULT_ROUTE.to_string()],
235            theme: ThemeMode::Light,
236            pump_paused: false,
237            capture_last_frame: false,
238            vsync_handle,
239            last_vsync_timestamp_ns: 0,
240        }
241    }
242
243    /// Enables or disables retaining a cloned snapshot of the last presented framebuffer.
244    ///
245    /// # Arguments
246    ///
247    /// - `bool` - `true` to capture snapshots on each present; `false` for zero-clone production mode.
248    ///
249    /// # Returns
250    ///
251    /// - `Self` - Updated HarmonyOS platform backend.
252    #[must_use]
253    pub fn with_capture_last_frame(mut self, enabled: bool) -> Self {
254        self.set_capture_last_frame(enabled);
255        self
256    }
257
258    /// Returns the last presented framebuffer snapshot for `id` when `capture_last_frame` is enabled.
259    ///
260    /// # Arguments
261    ///
262    /// - `WindowId` - XComponent window identifier.
263    ///
264    /// # Returns
265    ///
266    /// - `Option<&Framebuffer>` - Cloned framebuffer reference when capture is enabled and `id` exists.
267    #[must_use]
268    pub fn last_framebuffer(&self, id: WindowId) -> Option<&Framebuffer> {
269        if !self.get_capture_last_frame() {
270            return None;
271        }
272        self.get_windows()
273            .get(&id)
274            .map(HarmonyWindowRecord::get_last_frame)
275    }
276
277    /// Handles a hardware `OH_NativeVSync` frame callback timestamp, updating live display Hz and scheduling a redraw when active.
278    ///
279    /// # Arguments
280    ///
281    /// - `i64` - Hardware VSync timestamp in nanoseconds.
282    ///
283    /// # Returns
284    ///
285    /// - `f32` - Active display refresh rate in Hertz after processing this VSync tick.
286    pub fn on_vsync_frame(&mut self, timestamp_ns: i64) -> f32 {
287        let prev_ns: i64 = self.get_last_vsync_timestamp_ns();
288        self.set_last_vsync_timestamp_ns(timestamp_ns);
289        if prev_ns > 0 && timestamp_ns > prev_ns {
290            let delta_ns: i64 = timestamp_ns.saturating_sub(prev_ns);
291            if (HARMONY_VSYNC_MIN_PERIOD_NS..=HARMONY_VSYNC_MAX_PERIOD_NS).contains(&delta_ns) {
292                let measured_hz: f32 = ((1_000_000_000.0_f64 / (delta_ns as f64)) as f32)
293                    .clamp(MIN_REFRESH_RATE_HZ, MAX_REFRESH_RATE_HZ);
294                self.get_mut_profile().set_refresh_rate_hz(measured_hz);
295                let rounded_hz: u32 = measured_hz.round() as u32;
296                for rec in self.get_mut_windows().values_mut() {
297                    rec.get_mut_state()
298                        .get_mut_display()
299                        .set_refresh_rate_hz(rounded_hz);
300                }
301            }
302        }
303        if !self.get_pump_paused()
304            && let Some(wid) = self.primary_window_id()
305        {
306            self.get_mut_pending_events()
307                .push(WindowEvent::RedrawRequested(wid));
308        }
309        self.get_profile().get_refresh_rate_hz()
310    }
311
312    /// Schedules the next native `OH_NativeVSync` frame callback using `callback` and opaque `user_data`.
313    ///
314    /// # Arguments
315    ///
316    /// - `unsafe extern "C" fn(i64, usize)` - Native C callback receiving `(timestamp_ns, user_data)`.
317    /// - `usize` - Opaque context pointer forwarded to `callback`.
318    ///
319    /// # Returns
320    ///
321    /// - `bool` - `true` if `OH_NativeVSync_RequestFrame` accepted the request.
322    pub fn request_native_vsync_frame(
323        &self,
324        callback: unsafe extern "C" fn(i64, usize),
325        user_data: usize,
326    ) -> bool {
327        if self.get_pump_paused() {
328            return false;
329        }
330        harmony_request_vsync_frame(self.get_vsync_handle(), callback, user_data)
331    }
332
333    /// Releases the native `OH_NativeVSync*` handle if active.
334    pub fn destroy_native_vsync(&mut self) {
335        let handle: usize = self.get_vsync_handle();
336        if handle != 0 {
337            harmony_destroy_native_vsync(handle);
338            self.set_vsync_handle(0);
339        }
340    }
341
342    /// Returns the primary XComponent `WindowId`, if created.
343    ///
344    /// # Arguments
345    ///
346    /// - `&Self` - HarmonyOS platform reference.
347    ///
348    /// # Returns
349    ///
350    /// - `Option<WindowId>` - Primary window handle.
351    #[must_use]
352    pub fn primary_window_id(&self) -> Option<WindowId> {
353        let Self { primary_window, .. } = self;
354        *primary_window
355    }
356
357    /// Attaches live ArkUI `OHNativeWindow*` and `OH_NativeXComponent*` handles received from `OnSurfaceCreatedCB`.
358    ///
359    /// # Arguments
360    ///
361    /// - `&Self` - Mutable HarmonyOS platform.
362    /// - `usize` - Raw `OHNativeWindow*` pointer.
363    /// - `usize` - Raw `OH_NativeXComponent*` pointer.
364    /// - `u32` - Physical surface width in pixels.
365    /// - `u32` - Physical surface height in pixels.
366    pub fn attach_xcomponent(
367        &mut self,
368        native_window: usize,
369        xcomponent: usize,
370        phys_width: u32,
371        phys_height: u32,
372    ) {
373        self.set_attached_native_window(native_window);
374        self.set_attached_xcomponent(xcomponent);
375        self.get_mut_lifecycle().on_surface_created();
376        let scale: f32 = self.get_profile().get_density().max(0.75);
377        let pw: u32 = phys_width.max(1);
378        let ph: u32 = phys_height.max(1);
379        let lw: u32 = ((pw as f32) / scale).round().max(1.0) as u32;
380        let lh: u32 = ((ph as f32) / scale).round().max(1.0) as u32;
381        let mut resized: Vec<WindowId> = Vec::with_capacity(self.get_windows().len());
382        for (&wid, rec) in self.get_mut_windows().iter_mut() {
383            rec.set_native_window(native_window);
384            rec.set_xcomponent(xcomponent);
385            rec.set_surface_width(pw);
386            rec.set_surface_height(ph);
387            rec.get_mut_state()
388                .set_physical_width(pw)
389                .set_physical_height(ph)
390                .set_logical_width(lw as f32)
391                .set_logical_height(lh as f32)
392                .set_scale_factor(scale);
393            resized.push(wid);
394        }
395        for wid in resized.into_iter() {
396            self.get_mut_pending_events()
397                .push(WindowEvent::Resized(wid, lw, lh, scale));
398        }
399    }
400
401    /// Detaches ArkUI `OHNativeWindow*` safely on `OnSurfaceDestroyedCB` and cancels dangling touches.
402    ///
403    /// # Arguments
404    ///
405    /// - `&Self` - Mutable HarmonyOS platform.
406    pub fn detach_xcomponent(&mut self) {
407        self.set_attached_native_window(0);
408        self.set_attached_xcomponent(0);
409        let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
410        for rec in self.get_mut_windows().values_mut() {
411            rec.set_native_window(0);
412            rec.set_xcomponent(0);
413            rec.set_surface_width(0);
414            rec.set_surface_height(0);
415        }
416        let cancels: Vec<WindowEvent> = self.get_mut_lifecycle().on_surface_destroyed(wid);
417        self.get_mut_pending_events().extend(cancels);
418    }
419
420    /// Updates HarmonyOS `window.AvoidArea` insets and emits `SafeAreaChanged` plus `KeyboardVisibilityChanged`.
421    ///
422    /// # Arguments
423    ///
424    /// - `&Self` - Mutable HarmonyOS platform.
425    /// - `HarmonyAvoidArea` - Physical-pixel avoid area from `@ohos.window`.
426    pub fn update_avoid_area(&mut self, avoid: HarmonyAvoidArea) {
427        let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
428        let scale: f32 = self.get_profile().get_density().max(0.75);
429        let (lw, lh, immersive): (u32, u32, bool) = self
430            .get_windows()
431            .get(&wid)
432            .map(|rec: &HarmonyWindowRecord| {
433                (
434                    rec.get_state().get_logical_width().round().max(1.0) as u32,
435                    rec.get_state().get_logical_height().round().max(1.0) as u32,
436                    rec.get_state().get_fullscreen() != FullscreenMode::Windowed,
437                )
438            })
439            .unwrap_or((
440                self.get_profile().get_logical_width(),
441                self.get_profile().get_logical_height(),
442                false,
443            ));
444        let insets: SafeAreaInsets = resolve_harmony_avoid_area(
445            self.get_profile().get_device_type(),
446            avoid,
447            scale,
448            lw,
449            lh,
450            immersive,
451        );
452        self.set_safe_area(insets);
453        for rec in self.get_mut_windows().values_mut() {
454            rec.get_mut_state().set_safe_area(insets);
455        }
456        self.get_mut_pending_events()
457            .push(WindowEvent::SafeAreaChanged(wid, insets));
458        self.get_mut_pending_events()
459            .push(WindowEvent::System(SystemEvent::SafeAreaChanged(insets)));
460        let kb_h: f32 = (avoid.get_keyboard_px() as f32) / scale;
461        self.get_mut_pending_events().push(WindowEvent::System(
462            SystemEvent::KeyboardVisibilityChanged {
463                visible: avoid.get_keyboard_px() > 0,
464                height: kb_h,
465            },
466        ));
467    }
468
469    /// Translates a Stage-Model `HarmonyLifecycleHook` into canonical EUV `SystemEvent`s and Freeze/Resume/Destroy transitions.
470    ///
471    /// # Arguments
472    ///
473    /// - `&Self` - Mutable HarmonyOS platform.
474    /// - `HarmonyLifecycleHook` - Native ArkTS UIAbility / WindowStage callback payload.
475    ///
476    /// # Returns
477    ///
478    /// - `Vec<WindowEvent>` - Normalized events also enqueued for `poll_events()`.
479    pub fn handle_lifecycle_hook(&mut self, hook: HarmonyLifecycleHook) -> Vec<WindowEvent> {
480        let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
481        let mut emitted: Vec<WindowEvent> = Vec::new();
482        match hook {
483            HarmonyLifecycleHook::OnCreate { want_uri } => {
484                let _: u64 = self
485                    .get_mut_lifecycle()
486                    .begin_session(wid.get_value().max(1));
487                if let Some(uri) = want_uri
488                    && !uri.is_empty()
489                {
490                    emitted.push(WindowEvent::System(SystemEvent::DeepLink(uri)));
491                }
492            }
493            HarmonyLifecycleHook::OnWindowStageCreate {
494                native_window,
495                xcomponent,
496            } => {
497                self.set_attached_native_window(native_window);
498                self.set_attached_xcomponent(xcomponent);
499                self.get_mut_lifecycle().on_surface_created();
500                emitted.push(WindowEvent::System(SystemEvent::Appear));
501            }
502            HarmonyLifecycleHook::OnForeground => {
503                let _: u64 = self.get_mut_lifecycle().on_resume();
504                self.set_pump_paused(false);
505                emitted.push(WindowEvent::System(SystemEvent::Appear));
506                emitted.push(WindowEvent::System(SystemEvent::Foreground));
507            }
508            HarmonyLifecycleHook::OnWindowActive => {
509                if let Some(rec) = self.get_mut_windows().get_mut(&wid) {
510                    rec.get_mut_state().set_focused(true);
511                }
512                emitted.push(WindowEvent::Focused(wid, true));
513                emitted.push(WindowEvent::System(SystemEvent::FocusChanged(true)));
514            }
515            HarmonyLifecycleHook::OnWindowInactive => {
516                if let Some(rec) = self.get_mut_windows().get_mut(&wid) {
517                    rec.get_mut_state().set_focused(false);
518                }
519                let cancels: Vec<WindowEvent> = self.get_mut_lifecycle().on_pause(wid);
520                emitted.extend(cancels);
521                emitted.push(WindowEvent::Focused(wid, false));
522                emitted.push(WindowEvent::System(SystemEvent::FocusChanged(false)));
523                emitted.push(WindowEvent::System(SystemEvent::Inactive));
524            }
525            HarmonyLifecycleHook::OnBackground => {
526                let cancels: Vec<WindowEvent> = self.get_mut_lifecycle().on_pause(wid);
527                self.get_mut_lifecycle().on_background();
528                self.set_pump_paused(true);
529                emitted.extend(cancels);
530                emitted.push(WindowEvent::System(SystemEvent::Disappear));
531                emitted.push(WindowEvent::System(SystemEvent::Background));
532            }
533            HarmonyLifecycleHook::OnWindowStageDestroy => {
534                self.set_attached_native_window(0);
535                self.set_attached_xcomponent(0);
536                let cancels: Vec<WindowEvent> = self.get_mut_lifecycle().on_surface_destroyed(wid);
537                self.set_pump_paused(true);
538                emitted.extend(cancels);
539                emitted.push(WindowEvent::System(SystemEvent::Disappear));
540            }
541            HarmonyLifecycleHook::OnDestroy => {
542                self.set_attached_native_window(0);
543                self.set_attached_xcomponent(0);
544                self.destroy_native_vsync();
545                self.get_mut_lifecycle().on_terminate();
546                self.set_pump_paused(true);
547                emitted.push(WindowEvent::System(SystemEvent::Terminate));
548            }
549            HarmonyLifecycleHook::OnMemoryLevel(level) => {
550                let pressure: MemoryPressure = harmony_memory_level_to_pressure(level);
551                emitted.push(WindowEvent::System(SystemEvent::MemoryWarning(pressure)));
552            }
553            HarmonyLifecycleHook::OnConfigurationUpdate {
554                theme,
555                locale,
556                density,
557                fold_state,
558            } => {
559                self.set_theme(theme);
560                let safe_density: f32 = if density.is_finite() {
561                    density.clamp(0.75, 4.5)
562                } else {
563                    self.get_profile().get_density()
564                };
565                self.get_mut_profile().set_density(safe_density);
566                emitted.push(WindowEvent::ThemeChanged(wid, theme));
567                emitted.push(WindowEvent::System(SystemEvent::ThemeChanged(theme)));
568                if !locale.trim().is_empty() {
569                    emitted.push(WindowEvent::System(SystemEvent::LocaleChanged(locale)));
570                }
571                if let Some(posture) = fold_state {
572                    self.set_fold_state(posture);
573                    let (lw, lh): (u32, u32) = match posture {
574                        HarmonyFoldState::Folded => (390, 844),
575                        HarmonyFoldState::HalfFolded => (712, 420),
576                        HarmonyFoldState::Expanded => (712, 800),
577                    };
578                    if let Some(rec) = self.get_mut_windows().get_mut(&wid) {
579                        rec.get_mut_state()
580                            .set_logical_width(lw as f32)
581                            .set_logical_height(lh as f32)
582                            .set_physical_width(((lw as f32) * safe_density).round() as u32)
583                            .set_physical_height(((lh as f32) * safe_density).round() as u32)
584                            .set_scale_factor(safe_density);
585                    }
586                    emitted.push(WindowEvent::Resized(wid, lw, lh, safe_density));
587                    emitted.push(WindowEvent::System(SystemEvent::Resize {
588                        width: lw as f32,
589                        height: lh as f32,
590                        scale_factor: safe_density,
591                    }));
592                }
593            }
594            HarmonyLifecycleHook::OnBackPress => {
595                emitted.push(WindowEvent::KeyDown(
596                    wid,
597                    KeyEvent::new(KeyCode::Back, Modifiers::default(), false),
598                ));
599                emitted.push(WindowEvent::System(SystemEvent::BackPressed));
600            }
601            HarmonyLifecycleHook::OnNewWant(uri) => {
602                if !uri.is_empty() {
603                    emitted.push(WindowEvent::System(SystemEvent::DeepLink(uri)));
604                }
605            }
606            HarmonyLifecycleHook::OnWindowModeChanged(mode) => {
607                self.set_window_mode(mode);
608                let fs: FullscreenMode = if mode == HarmonyWindowMode::Fullscreen {
609                    FullscreenMode::Exclusive
610                } else {
611                    FullscreenMode::Windowed
612                };
613                for rec in self.get_mut_windows().values_mut() {
614                    rec.get_mut_state().set_fullscreen(fs);
615                }
616                if mode == HarmonyWindowMode::Minimized {
617                    self.set_pump_paused(true);
618                    emitted.push(WindowEvent::System(SystemEvent::Inactive));
619                } else {
620                    self.set_pump_paused(false);
621                }
622            }
623            HarmonyLifecycleHook::OnNetworkStatusChanged(status) => {
624                emitted.push(WindowEvent::System(SystemEvent::NetworkStatusChanged(
625                    status,
626                )));
627            }
628        }
629        self.get_mut_pending_events().extend(emitted.clone());
630        emitted
631    }
632
633    /// Translates an OpenHarmony `OH_NativeXComponent` touch contact action into normalized EUV pointer events.
634    ///
635    /// # Arguments
636    ///
637    /// - `&Self` - Mutable HarmonyOS platform.
638    /// - `i32` - OpenHarmony touch action (`HARMONY_TOUCH_DOWN`..`HARMONY_TOUCH_CANCEL`).
639    /// - `i32` - Raw contact identifier.
640    /// - `f32` - Component-local physical X coordinate.
641    /// - `f32` - Component-local physical Y coordinate.
642    ///
643    /// # Returns
644    ///
645    /// - `Vec<WindowEvent>` - Normalized pointer events.
646    pub fn handle_touch_event(
647        &mut self,
648        touch_type: i32,
649        raw_id: i32,
650        phys_x: f32,
651        phys_y: f32,
652    ) -> Vec<WindowEvent> {
653        let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
654        let scale: f32 = self.get_profile().get_density().max(0.75);
655        let x: f32 = phys_x / scale;
656        let y: f32 = phys_y / scale;
657        let action_mapped: i32 = match touch_type {
658            HARMONY_TOUCH_DOWN => ANDROID_ACTION_DOWN,
659            HARMONY_TOUCH_MOVE => ANDROID_ACTION_MOVE,
660            HARMONY_TOUCH_UP => ANDROID_ACTION_UP,
661            HARMONY_TOUCH_CANCEL => ANDROID_ACTION_CANCEL,
662            _ => return Vec::new(),
663        };
664        let events: Vec<WindowEvent> = self
665            .get_mut_lifecycle()
666            .touch_tracker_mut()
667            .handle_android_motion(wid, action_mapped, 0, &[(raw_id, x, y)]);
668        self.get_mut_pending_events().extend(events.clone());
669        events
670    }
671
672    /// Translates an OpenHarmony NDK key code (`KEYCODE_*`) into a unified `WindowEvent::KeyDown` or `KeyUp`.
673    ///
674    /// # Arguments
675    ///
676    /// - `&Self` - Mutable HarmonyOS platform.
677    /// - `i32` - OpenHarmony key code.
678    /// - `bool` - `true` for key down, `false` for key up.
679    ///
680    /// # Returns
681    ///
682    /// - `Option<WindowEvent>` - Translated keyboard event if recognized.
683    pub fn handle_key_event(&mut self, ohos_code: i32, down: bool) -> Option<WindowEvent> {
684        let mods: Modifiers = self.get_active_modifiers();
685        self.handle_key_event_with_modifiers(ohos_code, down, mods, false)
686    }
687
688    /// Translates an OpenHarmony NDK key code with explicit modifier keys and repeat state (for HarmonyOS PC keyboards).
689    ///
690    /// Automatically maintains internal `active_modifiers` when Shift, Ctrl, Alt, or Meta keys are pressed or released.
691    ///
692    /// # Arguments
693    ///
694    /// - `&Self` - Mutable HarmonyOS platform.
695    /// - `i32` - OpenHarmony NDK key code (`HARMONY_KEYCODE_*`).
696    /// - `bool` - `true` for key down, `false` for key up.
697    /// - `Modifiers` - Active keyboard modifier bitset.
698    /// - `bool` - Whether this key press is an auto-repeat event.
699    ///
700    /// # Returns
701    ///
702    /// - `Option<WindowEvent>` - Translated keyboard event if `ohos_code` maps to a non-modifier `KeyCode`.
703    pub fn handle_key_event_with_modifiers(
704        &mut self,
705        ohos_code: i32,
706        down: bool,
707        mut mods: Modifiers,
708        repeat: bool,
709    ) -> Option<WindowEvent> {
710        let mut tracked: Modifiers = self.get_active_modifiers();
711        match ohos_code {
712            HARMONY_KEYCODE_SHIFT_LEFT | HARMONY_KEYCODE_SHIFT_RIGHT => {
713                tracked.set_shift(down);
714                self.set_active_modifiers(tracked);
715                return None;
716            }
717            HARMONY_KEYCODE_CTRL_LEFT | HARMONY_KEYCODE_CTRL_RIGHT => {
718                tracked.set_ctrl(down);
719                self.set_active_modifiers(tracked);
720                return None;
721            }
722            HARMONY_KEYCODE_ALT_LEFT | HARMONY_KEYCODE_ALT_RIGHT => {
723                tracked.set_alt(down);
724                self.set_active_modifiers(tracked);
725                return None;
726            }
727            HARMONY_KEYCODE_META_LEFT | HARMONY_KEYCODE_META_RIGHT => {
728                tracked.set_meta(down);
729                self.set_active_modifiers(tracked);
730                return None;
731            }
732            _ => {}
733        }
734        mods.set_shift(mods.get_shift() || tracked.get_shift());
735        mods.set_ctrl(mods.get_ctrl() || tracked.get_ctrl());
736        mods.set_alt(mods.get_alt() || tracked.get_alt());
737        mods.set_meta(mods.get_meta() || tracked.get_meta());
738        let code: KeyCode = harmony_keycode_to_euv(ohos_code);
739        if code == KeyCode::Unknown {
740            return None;
741        }
742        let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
743        let kev: KeyEvent = KeyEvent::new(code, mods, repeat);
744        let ev: WindowEvent = if down {
745            WindowEvent::KeyDown(wid, kev)
746        } else {
747            WindowEvent::KeyUp(wid, kev)
748        };
749        self.get_mut_pending_events().push(ev.clone());
750        Some(ev)
751    }
752
753    /// Returns `true` when this `HarmonyPlatform` targets HarmonyOS PC / 2-in-1 desktop environments.
754    ///
755    /// # Arguments
756    ///
757    /// - `&Self` - HarmonyOS platform reference.
758    ///
759    /// # Returns
760    ///
761    /// - `bool` - `true` for `HarmonyDeviceType::Pc2In1`.
762    #[must_use]
763    pub fn is_pc_desktop(&self) -> bool {
764        self.get_profile().get_device_type() == HarmonyDeviceType::Pc2In1
765    }
766
767    /// Drains all queued outbound ArkTS / N-API host commands for HarmonyOS PC windowing, cursor, IME, and OS bridges.
768    ///
769    /// # Arguments
770    ///
771    /// - `&Self` - Mutable HarmonyOS platform.
772    ///
773    /// # Returns
774    ///
775    /// - `Vec<HarmonyHostCommand>` - Ordered host commands to execute in ArkTS / N-API.
776    pub fn drain_host_commands(&mut self) -> Vec<HarmonyHostCommand> {
777        take(self.get_mut_outbound_commands())
778    }
779
780    /// Translates an OpenHarmony PC/Tablet mouse event (`OH_NativeXComponent_MouseEvent`) into normalized EUV pointer events.
781    ///
782    /// # Arguments
783    ///
784    /// - `&Self` - Mutable HarmonyOS platform.
785    /// - `i32` - Mouse action (`HARMONY_MOUSE_PRESS`..`HARMONY_MOUSE_CANCEL`).
786    /// - `i32` - Mouse button (`HARMONY_MOUSE_BUTTON_*`).
787    /// - `f32` - Component-local physical X coordinate.
788    /// - `f32` - Component-local physical Y coordinate.
789    ///
790    /// # Returns
791    ///
792    /// - `Vec<WindowEvent>` - Normalized desktop mouse pointer events.
793    pub fn handle_mouse_event(
794        &mut self,
795        action: i32,
796        button: i32,
797        phys_x: f32,
798        phys_y: f32,
799    ) -> Vec<WindowEvent> {
800        let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
801        let scale: f32 = self.get_profile().get_density().max(0.75);
802        let lx: f32 = phys_x / scale;
803        let ly: f32 = phys_y / scale;
804        let btn: PointerButton = harmony_mouse_button_to_euv(button);
805        let mods: Modifiers = self.get_active_modifiers();
806        let ptr: PointerEvent =
807            PointerEvent::new(0, PointerDevice::Mouse, Point::new(lx, ly), btn, 1.0, mods);
808        let ev: WindowEvent = match action {
809            HARMONY_MOUSE_PRESS => WindowEvent::PointerDown(wid, ptr),
810            HARMONY_MOUSE_RELEASE => WindowEvent::PointerUp(wid, ptr),
811            HARMONY_MOUSE_MOVE => WindowEvent::PointerMove(wid, ptr),
812            HARMONY_MOUSE_CANCEL => WindowEvent::PointerCancel(wid, 0),
813            _ => return Vec::new(),
814        };
815        self.get_mut_pending_events().push(ev.clone());
816        vec![ev]
817    }
818
819    /// Translates a HarmonyOS PC mouse-wheel or trackpad two-finger scroll delta into `WindowEvent::Scroll`.
820    ///
821    /// # Arguments
822    ///
823    /// - `&Self` - Mutable HarmonyOS platform.
824    /// - `f32` - Horizontal scroll delta in logical vp.
825    /// - `f32` - Vertical scroll delta in logical vp.
826    ///
827    /// # Returns
828    ///
829    /// - `WindowEvent` - Normalized scroll event also enqueued for `poll_events()`.
830    pub fn handle_scroll_event(&mut self, delta_x: f32, delta_y: f32) -> WindowEvent {
831        let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
832        let dx: f32 = if delta_x.is_finite() { delta_x } else { 0.0 };
833        let dy: f32 = if delta_y.is_finite() { delta_y } else { 0.0 };
834        let ev: WindowEvent = WindowEvent::Scroll(wid, Point::new(dx, dy));
835        self.get_mut_pending_events().push(ev.clone());
836        ev
837    }
838
839    /// Translates a HarmonyOS Watch digital crown rotation delta into vertical scroll events.
840    ///
841    /// # Arguments
842    ///
843    /// - `&Self` - Mutable HarmonyOS platform.
844    /// - `f32` - Rotary crown delta in detents.
845    ///
846    /// # Returns
847    ///
848    /// - `Vec<WindowEvent>` - Normalized scroll event when `delta` is non-zero.
849    pub fn handle_crown_event(&mut self, delta: f32) -> Vec<WindowEvent> {
850        if !delta.is_finite() || delta.abs() < 1e-5 {
851            return Vec::new();
852        }
853        let scroll_ev: WindowEvent =
854            self.handle_scroll_event(0.0, delta * WEARABLE_CROWN_PIXELS_PER_DETENT);
855        vec![scroll_ev]
856    }
857
858    /// Dispatches committed HarmonyOS IME UTF-8 text into `WindowEvent::TextInput`.
859    ///
860    /// # Arguments
861    ///
862    /// - `&Self` - Mutable HarmonyOS platform.
863    /// - `String` - Committed UTF-8 text.
864    pub fn handle_ime_commit(&mut self, text: String) {
865        if text.is_empty() {
866            return;
867        }
868        let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
869        self.get_mut_pending_events()
870            .push(WindowEvent::Ime(wid, ImeEvent::Commit(text.clone())));
871        self.get_mut_pending_events()
872            .push(WindowEvent::TextInput(wid, text));
873    }
874}
875
876/// `WindowController` implementation for `HarmonyPlatform`.
877impl WindowController for HarmonyPlatform {
878    /// Applies a `WindowCommand` against the HarmonyOS XComponent window record.
879    ///
880    /// # Arguments
881    ///
882    /// - `&Self` - Mutable HarmonyOS platform.
883    /// - `WindowCommand` - Command to execute.
884    ///
885    /// # Returns
886    ///
887    /// - `Result<(), PlatformError>` - Execution status.
888    fn apply_command(&mut self, command: WindowCommand) -> Result<(), PlatformError> {
889        match command {
890            WindowCommand::SetTitle(id, title) => {
891                let rec: &mut HarmonyWindowRecord = self
892                    .get_mut_windows()
893                    .get_mut(&id)
894                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
895                rec.get_mut_config().set_title(title.clone());
896                self.get_mut_outbound_commands()
897                    .push(HarmonyHostCommand::SetWindowTitle(title.clone()));
898                let _: bool = dispatch_native_action(HARMONY_ACTION_WINDOW_TITLE, &title, "");
899                Ok(())
900            }
901            WindowCommand::SetFullscreen(id, mode) => {
902                let rec: &mut HarmonyWindowRecord = self
903                    .get_mut_windows()
904                    .get_mut(&id)
905                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
906                rec.get_mut_config().set_fullscreen(mode);
907                rec.get_mut_state().set_fullscreen(mode);
908                let target_mode: HarmonyWindowMode = if mode == FullscreenMode::Windowed {
909                    HarmonyWindowMode::Floating
910                } else {
911                    HarmonyWindowMode::Fullscreen
912                };
913                self.set_window_mode(target_mode);
914                self.get_mut_outbound_commands()
915                    .push(HarmonyHostCommand::SetWindowMode(target_mode));
916                let arg: &str = if mode == FullscreenMode::Windowed {
917                    FULLSCREEN_ACTION_OFF
918                } else {
919                    FULLSCREEN_ACTION_ON
920                };
921                let _: bool = dispatch_native_action(NATIVE_ACTION_FULLSCREEN, arg, "");
922                let _: bool = dispatch_native_action(HARMONY_ACTION_WINDOW_MODE, arg, "");
923                Ok(())
924            }
925            WindowCommand::SetRenderMode(id, mode) => {
926                let profile_api: HarmonyGraphicsApi = self.get_profile().get_graphics_api();
927                let rec: &mut HarmonyWindowRecord = self
928                    .get_mut_windows()
929                    .get_mut(&id)
930                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
931                rec.get_mut_config().get_mut_render().set_mode(mode);
932                let next_api: HarmonyGraphicsApi = match mode {
933                    RenderMode::Software => HarmonyGraphicsApi::SoftwareBuffer,
934                    RenderMode::Hardware | RenderMode::Hybrid | RenderMode::Auto => profile_api,
935                };
936                rec.set_graphics_api(next_api);
937                Ok(())
938            }
939            WindowCommand::RequestRedraw(id) => {
940                if !self.get_windows().contains_key(&id) {
941                    return Err(PlatformError::WindowNotFound(id.get_value()));
942                }
943                self.get_mut_pending_events()
944                    .push(WindowEvent::RedrawRequested(id));
945                Ok(())
946            }
947            WindowCommand::Close(id) => {
948                if self.get_mut_windows().remove(&id).is_none() {
949                    return Err(PlatformError::WindowNotFound(id.get_value()));
950                }
951                self.get_mut_outbound_commands()
952                    .push(HarmonyHostCommand::CloseWindow(id));
953                Ok(())
954            }
955            WindowCommand::SetSize(id, width, height) => {
956                let clamped_w: u32 = width.max(1);
957                let clamped_h: u32 = height.max(1);
958                let scale: f32 = {
959                    let rec: &mut HarmonyWindowRecord = self
960                        .get_mut_windows()
961                        .get_mut(&id)
962                        .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
963                    let s: f32 = rec.get_state().get_scale_factor();
964                    rec.get_mut_config().set_size(clamped_w, clamped_h);
965                    rec.get_mut_state()
966                        .set_logical_width(clamped_w as f32)
967                        .set_logical_height(clamped_h as f32)
968                        .set_physical_width(((clamped_w as f32) * s).round() as u32)
969                        .set_physical_height(((clamped_h as f32) * s).round() as u32);
970                    s
971                };
972                self.get_mut_outbound_commands()
973                    .push(HarmonyHostCommand::SetWindowSize {
974                        width: clamped_w,
975                        height: clamped_h,
976                    });
977                self.get_mut_pending_events()
978                    .push(WindowEvent::Resized(id, clamped_w, clamped_h, scale));
979                Ok(())
980            }
981            WindowCommand::SetDecorations(id, enabled) => {
982                let rec: &mut HarmonyWindowRecord = self
983                    .get_mut_windows()
984                    .get_mut(&id)
985                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
986                rec.get_mut_config().set_decorations(enabled);
987                self.get_mut_outbound_commands()
988                    .push(HarmonyHostCommand::SetDecorations(enabled));
989                let arg: &str = if enabled {
990                    HARMONY_ACTION_ARG_ON
991                } else {
992                    HARMONY_ACTION_ARG_OFF
993                };
994                let _: bool = dispatch_native_action(HARMONY_ACTION_DECORATIONS, arg, "");
995                Ok(())
996            }
997            WindowCommand::SetAlwaysOnTop(id, enabled) => {
998                let rec: &mut HarmonyWindowRecord = self
999                    .get_mut_windows()
1000                    .get_mut(&id)
1001                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
1002                rec.get_mut_config().set_always_on_top(enabled);
1003                self.get_mut_outbound_commands()
1004                    .push(HarmonyHostCommand::SetAlwaysOnTop(enabled));
1005                let arg: &str = if enabled {
1006                    HARMONY_ACTION_ARG_ON
1007                } else {
1008                    HARMONY_ACTION_ARG_OFF
1009                };
1010                let _: bool = dispatch_native_action(HARMONY_ACTION_ALWAYS_ON_TOP, arg, "");
1011                Ok(())
1012            }
1013            WindowCommand::SetCursor(id, cursor) => {
1014                if !self.get_windows().contains_key(&id) {
1015                    return Err(PlatformError::WindowNotFound(id.get_value()));
1016                }
1017                if self.get_last_cursor() != cursor {
1018                    self.set_last_cursor(cursor);
1019                    self.get_mut_outbound_commands()
1020                        .push(HarmonyHostCommand::SetCursor(cursor));
1021                    let style_id: String = harmony_cursor_to_pointer_style(cursor).to_string();
1022                    let _: bool = dispatch_native_action(HARMONY_ACTION_CURSOR, &style_id, "");
1023                }
1024                Ok(())
1025            }
1026            WindowCommand::SetIme(id, enabled, rect) => {
1027                if !self.get_windows().contains_key(&id) {
1028                    return Err(PlatformError::WindowNotFound(id.get_value()));
1029                }
1030                self.get_mut_outbound_commands()
1031                    .push(HarmonyHostCommand::SetIme { enabled, rect });
1032                let arg: &str = if enabled {
1033                    HARMONY_ACTION_ARG_SHOW
1034                } else {
1035                    HARMONY_ACTION_ARG_HIDE
1036                };
1037                let _: bool = dispatch_native_action(HARMONY_ACTION_IME, arg, "");
1038                Ok(())
1039            }
1040            WindowCommand::SetPosition(id, _, _)
1041            | WindowCommand::SetResizable(id, _)
1042            | WindowCommand::SetVisible(id, _)
1043            | WindowCommand::SetStatusBarStyle(id, _) => {
1044                if !self.get_windows().contains_key(&id) {
1045                    return Err(PlatformError::WindowNotFound(id.get_value()));
1046                }
1047                Ok(())
1048            }
1049        }
1050    }
1051}
1052
1053/// `PlatformBackend` implementation for `HarmonyPlatform`.
1054impl PlatformBackend for HarmonyPlatform {
1055    /// Returns `PlatformKind::HarmonyOs`.
1056    ///
1057    /// # Arguments
1058    ///
1059    /// - `&Self` - HarmonyOS platform reference.
1060    ///
1061    /// # Returns
1062    ///
1063    /// - `PlatformKind` - `PlatformKind::HarmonyOs`.
1064    fn kind(&self) -> PlatformKind {
1065        PlatformKind::HarmonyOs
1066    }
1067
1068    /// Returns HarmonyOS capabilities refined by the concrete `HarmonyDeviceType`.
1069    ///
1070    /// # Arguments
1071    ///
1072    /// - `&Self` - HarmonyOS platform reference.
1073    ///
1074    /// # Returns
1075    ///
1076    /// - `PlatformCapabilities` - Device-specific HarmonyOS capabilities.
1077    fn capabilities(&self) -> PlatformCapabilities {
1078        let mut caps: PlatformCapabilities =
1079            PlatformCapabilities::for_platform(PlatformKind::HarmonyOs);
1080        match self.get_profile().get_device_type() {
1081            HarmonyDeviceType::Phone => {
1082                caps.multi_window = false;
1083                caps.hover_pointer = false;
1084                caps.hardware_keyboard = false;
1085                caps.rotary_input = false;
1086            }
1087            HarmonyDeviceType::Watch => {
1088                caps.multi_window = false;
1089                caps.hover_pointer = false;
1090                caps.stylus = false;
1091                caps.hardware_keyboard = false;
1092                caps.biometrics = false;
1093                caps.rotary_input = true;
1094            }
1095            HarmonyDeviceType::Tv => {
1096                caps.touch = false;
1097                caps.stylus = false;
1098                caps.haptics = false;
1099                caps.biometrics = false;
1100                caps.rotary_input = false;
1101            }
1102            HarmonyDeviceType::Automotive => {
1103                caps.stylus = false;
1104                caps.biometrics = false;
1105                caps.rotary_input = true;
1106            }
1107            HarmonyDeviceType::Pc2In1 => {
1108                caps.multi_window = true;
1109                caps.hover_pointer = true;
1110                caps.hardware_keyboard = true;
1111                caps.touch = true;
1112                caps.rotary_input = false;
1113            }
1114            HarmonyDeviceType::Tablet | HarmonyDeviceType::Foldable => {
1115                caps.multi_window = true;
1116                caps.hover_pointer = true;
1117                caps.hardware_keyboard = true;
1118                caps.rotary_input = false;
1119            }
1120        }
1121        caps
1122    }
1123
1124    /// Creates an ArkUI XComponent window state configured for the active HarmonyOS device profile.
1125    ///
1126    /// # Arguments
1127    ///
1128    /// - `&Self` - Mutable HarmonyOS platform.
1129    /// - `&WindowConfig` - Declarative window config.
1130    ///
1131    /// # Returns
1132    ///
1133    /// - `Result<WindowState, PlatformError>` - Created window state.
1134    fn create_window(&mut self, config: &WindowConfig) -> Result<WindowState, PlatformError> {
1135        let id: WindowId = WindowId::new(self.get_next_id());
1136        self.set_next_id(self.get_next_id().wrapping_add(1));
1137        let profile: HarmonyDeviceProfile = self.get_profile();
1138        let mut oh_cfg: WindowConfig = config.clone();
1139        if self.primary_window_id().is_none() || !self.is_pc_desktop() {
1140            oh_cfg.set_size(profile.get_logical_width(), profile.get_logical_height());
1141        }
1142        let mut state: WindowState = WindowState::from_config(id, &oh_cfg, profile.get_density());
1143        state.set_safe_area(self.get_safe_area());
1144        state.set_system_theme(self.get_theme());
1145        state
1146            .get_mut_display()
1147            .set_refresh_rate_hz(profile.get_refresh_rate_hz().round() as u32);
1148        let record: HarmonyWindowRecord = HarmonyWindowRecord {
1149            config: oh_cfg,
1150            state,
1151            xcomponent_id: HARMONY_DEFAULT_XCOMPONENT_ID.to_string(),
1152            native_window: self.get_attached_native_window(),
1153            xcomponent: self.get_attached_xcomponent(),
1154            graphics_api: profile.get_graphics_api(),
1155            surface_width: state.get_physical_width(),
1156            surface_height: state.get_physical_height(),
1157            last_frame: Framebuffer::allocate(1, 1),
1158            present_count: 0,
1159        };
1160        self.get_mut_windows().insert(id, record);
1161        if self.primary_window_id().is_none() {
1162            self.set_primary_window(Some(id));
1163        }
1164        Ok(state)
1165    }
1166
1167    /// Queries live `WindowState` for `id`.
1168    ///
1169    /// # Arguments
1170    ///
1171    /// - `&Self` - HarmonyOS platform reference.
1172    /// - `WindowId` - Window identifier.
1173    ///
1174    /// # Returns
1175    ///
1176    /// - `Option<WindowState>` - Window state if active.
1177    fn window_state(&self, id: WindowId) -> Option<WindowState> {
1178        self.get_windows()
1179            .get(&id)
1180            .map(HarmonyWindowRecord::get_state)
1181    }
1182
1183    /// Returns `RawWindowHandle::HarmonyXComponent` carrying `OHNativeWindow*` and `OH_NativeXComponent*`.
1184    ///
1185    /// # Arguments
1186    ///
1187    /// - `&Self` - HarmonyOS platform reference.
1188    /// - `WindowId` - Window identifier.
1189    ///
1190    /// # Returns
1191    ///
1192    /// - `RawWindowHandle` - HarmonyOS XComponent handle.
1193    fn raw_window_handle(&self, id: WindowId) -> RawWindowHandle {
1194        match self.get_windows().get(&id) {
1195            Some(rec) => RawWindowHandle::HarmonyXComponent {
1196                native_window: rec.get_native_window(),
1197                xcomponent: rec.get_xcomponent(),
1198            },
1199            None => RawWindowHandle::Headless,
1200        }
1201    }
1202
1203    /// Drains queued HarmonyOS XComponent, avoidArea, and UIAbility lifecycle events.
1204    ///
1205    /// # Arguments
1206    ///
1207    /// - `&Self` - Mutable HarmonyOS platform.
1208    ///
1209    /// # Returns
1210    ///
1211    /// - `Vec<WindowEvent>` - Pending events.
1212    fn poll_events(&mut self) -> Vec<WindowEvent> {
1213        take(self.get_mut_pending_events())
1214    }
1215
1216    /// Pauses or resumes the HarmonyOS `OH_NativeVSync` frame pump flag.
1217    ///
1218    /// # Arguments
1219    ///
1220    /// - `&Self` - Mutable HarmonyOS platform.
1221    /// - `bool` - `true` to pause for background freeze.
1222    fn set_frame_pump_paused(&mut self, paused: bool) {
1223        self.set_pump_paused(paused);
1224    }
1225
1226    /// Returns whether the HarmonyOS frame pump is currently paused.
1227    ///
1228    /// # Arguments
1229    ///
1230    /// - `&Self` - HarmonyOS platform reference.
1231    ///
1232    /// # Returns
1233    ///
1234    /// - `bool` - Pause state.
1235    fn is_frame_pump_paused(&self) -> bool {
1236        self.get_pump_paused()
1237    }
1238
1239    /// Presents `framebuffer` to the attached `OHNativeWindow*` buffer or offscreen fallback snapshot.
1240    ///
1241    /// # Arguments
1242    ///
1243    /// - `&Self` - Mutable HarmonyOS platform.
1244    /// - `WindowId` - Window identifier.
1245    /// - `&Framebuffer` - Rendered RGBA8 framebuffer.
1246    ///
1247    /// # Returns
1248    ///
1249    /// - `Result<(), PlatformError>` - Presentation status.
1250    fn present_framebuffer(
1251        &mut self,
1252        id: WindowId,
1253        framebuffer: &Framebuffer,
1254    ) -> Result<(), PlatformError> {
1255        self.present_framebuffer_region(id, framebuffer, DamageRegion::full())
1256    }
1257
1258    /// Presents `framebuffer` (or only `damage`) to the attached `OHNativeWindow*` buffer without cloning when capture is disabled.
1259    ///
1260    /// # Arguments
1261    ///
1262    /// - `WindowId` - Window identifier.
1263    /// - `&Framebuffer` - Rendered RGBA8 framebuffer.
1264    /// - `DamageRegion` - Damaged pixel region updated this frame.
1265    ///
1266    /// # Returns
1267    ///
1268    /// - `Result<(), PlatformError>` - Presentation status.
1269    fn present_framebuffer_region(
1270        &mut self,
1271        id: WindowId,
1272        framebuffer: &Framebuffer,
1273        damage: DamageRegion,
1274    ) -> Result<(), PlatformError> {
1275        let capture: bool = self.get_capture_last_frame();
1276        let dirty_rect: Option<Rect> = if damage.get_full_damage() {
1277            None
1278        } else {
1279            damage.bounds_rect()
1280        };
1281        let rec: &mut HarmonyWindowRecord = self
1282            .get_mut_windows()
1283            .get_mut(&id)
1284            .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
1285        let nw: usize = rec.get_native_window();
1286        let mut sw: u32 = rec.get_surface_width();
1287        let mut sh: u32 = rec.get_surface_height();
1288        let res: Result<(), PlatformError> =
1289            harmony_present_native_window(nw, framebuffer, &mut sw, &mut sh, dirty_rect);
1290        rec.set_surface_width(sw);
1291        rec.set_surface_height(sh);
1292        if capture {
1293            rec.set_last_frame(framebuffer.clone());
1294        }
1295        rec.set_present_count(rec.get_present_count().wrapping_add(1));
1296        res
1297    }
1298
1299    /// Reads cached HarmonyOS pasteboard text.
1300    ///
1301    /// # Arguments
1302    ///
1303    /// - `&Self` - HarmonyOS platform reference.
1304    ///
1305    /// # Returns
1306    ///
1307    /// - `Option<String>` - Cached clipboard string.
1308    fn read_clipboard(&self) -> Option<String> {
1309        let Self { clipboard, .. } = self;
1310        clipboard.clone()
1311    }
1312
1313    /// Writes `text` to the HarmonyOS pasteboard cache and native action bridge.
1314    ///
1315    /// # Arguments
1316    ///
1317    /// - `&Self` - Mutable HarmonyOS platform.
1318    /// - `&str` - Clipboard text.
1319    ///
1320    /// # Returns
1321    ///
1322    /// - `Result<(), PlatformError>` - Write status.
1323    fn write_clipboard(&mut self, text: &str) -> Result<(), PlatformError> {
1324        self.set_clipboard(Some(text.to_string()));
1325        self.get_mut_outbound_commands()
1326            .push(HarmonyHostCommand::SetClipboard(text.to_string()));
1327        let _: bool = write_system_clipboard(text);
1328        Ok(())
1329    }
1330
1331    /// Returns the active HarmonyOS appearance mode.
1332    ///
1333    /// # Arguments
1334    ///
1335    /// - `&Self` - HarmonyOS platform reference.
1336    ///
1337    /// # Returns
1338    ///
1339    /// - `ThemeMode` - Active appearance mode.
1340    fn system_theme(&self) -> ThemeMode {
1341        self.get_theme()
1342    }
1343
1344    /// Returns the active HarmonyOS hardware display refresh rate in Hertz.
1345    ///
1346    /// # Arguments
1347    ///
1348    /// - `&Self` - HarmonyOS platform reference.
1349    ///
1350    /// # Returns
1351    ///
1352    /// - `f32` - Active display refresh rate in Hertz.
1353    fn display_refresh_rate_hz(&self) -> f32 {
1354        self.get_profile().get_refresh_rate_hz()
1355    }
1356}
1357
1358/// `PlatformStorage` implementation for `HarmonyPlatform`.
1359impl PlatformStorage for HarmonyPlatform {
1360    /// Reads a key from HarmonyOS preferences storage.
1361    ///
1362    /// # Arguments
1363    ///
1364    /// - `&Self` - HarmonyOS platform reference.
1365    /// - `&str` - Storage key.
1366    ///
1367    /// # Returns
1368    ///
1369    /// - `Option<String>` - Stored value, if present.
1370    fn storage_get(&self, key: &str) -> Option<String> {
1371        self.get_storage().get(key).cloned()
1372    }
1373
1374    /// Writes a key-value pair into HarmonyOS preferences storage.
1375    ///
1376    /// # Arguments
1377    ///
1378    /// - `&Self` - Mutable HarmonyOS platform.
1379    /// - `&str` - Storage key.
1380    /// - `&str` - UTF-8 value.
1381    ///
1382    /// # Returns
1383    ///
1384    /// - `Result<(), PlatformError>` - Persistence status.
1385    fn storage_set(&mut self, key: &str, value: &str) -> Result<(), PlatformError> {
1386        let _: Option<String> = self
1387            .get_mut_storage()
1388            .insert(key.to_string(), value.to_string());
1389        Ok(())
1390    }
1391
1392    /// Removes `key` from HarmonyOS preferences storage.
1393    ///
1394    /// # Arguments
1395    ///
1396    /// - `&Self` - Mutable HarmonyOS platform.
1397    /// - `&str` - Storage key.
1398    ///
1399    /// # Returns
1400    ///
1401    /// - `Result<(), PlatformError>` - Removal status.
1402    fn storage_remove(&mut self, key: &str) -> Result<(), PlatformError> {
1403        let _: Option<String> = self.get_mut_storage().remove(key);
1404        Ok(())
1405    }
1406
1407    /// Clears all keys from HarmonyOS preferences storage.
1408    ///
1409    /// # Arguments
1410    ///
1411    /// - `&Self` - Mutable HarmonyOS platform.
1412    ///
1413    /// # Returns
1414    ///
1415    /// - `Result<(), PlatformError>` - Clear status.
1416    fn storage_clear(&mut self) -> Result<(), PlatformError> {
1417        self.get_mut_storage().clear();
1418        Ok(())
1419    }
1420}
1421
1422/// `PlatformNavigation` implementation for `HarmonyPlatform`.
1423impl PlatformNavigation for HarmonyPlatform {
1424    /// Navigates to `route` on the HarmonyOS UIAbility route stack.
1425    ///
1426    /// # Arguments
1427    ///
1428    /// - `&Self` - Mutable HarmonyOS platform.
1429    /// - `&str` - Logical route path.
1430    ///
1431    /// # Returns
1432    ///
1433    /// - `Result<(), PlatformError>` - Navigation status.
1434    fn navigate_to(&mut self, route: &str) -> Result<(), PlatformError> {
1435        if !route.is_empty() {
1436            self.get_mut_route_stack().push(route.to_string());
1437        }
1438        Ok(())
1439    }
1440
1441    /// Pops `delta` entries from the HarmonyOS route stack.
1442    ///
1443    /// # Arguments
1444    ///
1445    /// - `&Self` - Mutable HarmonyOS platform.
1446    /// - `u32` - Pages to pop.
1447    ///
1448    /// # Returns
1449    ///
1450    /// - `Result<(), PlatformError>` - Navigation status.
1451    fn navigate_back(&mut self, delta: u32) -> Result<(), PlatformError> {
1452        for _ in 0..delta.max(1) {
1453            if self.get_route_stack().len() > 1 {
1454                let _: Option<String> = self.get_mut_route_stack().pop();
1455            }
1456        }
1457        Ok(())
1458    }
1459
1460    /// Returns the active HarmonyOS logical route path.
1461    ///
1462    /// # Arguments
1463    ///
1464    /// - `&Self` - HarmonyOS platform reference.
1465    ///
1466    /// # Returns
1467    ///
1468    /// - `&str` - Active route path.
1469    fn current_route(&self) -> &str {
1470        self.get_route_stack()
1471            .last()
1472            .map(String::as_str)
1473            .unwrap_or(HARMONY_DEFAULT_ROUTE)
1474    }
1475}
1476
1477/// `PlatformLifecycleBridge` implementation for `HarmonyPlatform`.
1478impl PlatformLifecycleBridge for HarmonyPlatform {
1479    /// Maps HarmonyOS `onBackground` into unified freeze semantics.
1480    ///
1481    /// # Arguments
1482    ///
1483    /// - `&Self` - Mutable HarmonyOS platform.
1484    ///
1485    /// # Returns
1486    ///
1487    /// - `Vec<WindowEvent>` - Normalized freeze events.
1488    fn freeze_surface(&mut self) -> Vec<WindowEvent> {
1489        self.handle_lifecycle_hook(HarmonyLifecycleHook::OnBackground)
1490    }
1491
1492    /// Maps HarmonyOS `onForeground` into unified resume semantics.
1493    ///
1494    /// # Arguments
1495    ///
1496    /// - `&Self` - Mutable HarmonyOS platform.
1497    ///
1498    /// # Returns
1499    ///
1500    /// - `Vec<WindowEvent>` - Normalized resume events.
1501    fn resume_surface(&mut self) -> Vec<WindowEvent> {
1502        self.handle_lifecycle_hook(HarmonyLifecycleHook::OnForeground)
1503    }
1504
1505    /// Maps HarmonyOS `onDestroy` into unified destroy semantics.
1506    ///
1507    /// # Arguments
1508    ///
1509    /// - `&Self` - Mutable HarmonyOS platform.
1510    ///
1511    /// # Returns
1512    ///
1513    /// - `Vec<WindowEvent>` - Normalized teardown events.
1514    fn destroy_surface(&mut self) -> Vec<WindowEvent> {
1515        self.handle_lifecycle_hook(HarmonyLifecycleHook::OnDestroy)
1516    }
1517}
1518
1519/// `PlatformHostAdapter` implementation for `HarmonyPlatform`.
1520impl PlatformHostAdapter for HarmonyPlatform {
1521    /// Returns the concrete `DeviceFormFactor` matching this HarmonyOS device category.
1522    ///
1523    /// # Arguments
1524    ///
1525    /// - `&Self` - HarmonyOS platform reference.
1526    ///
1527    /// # Returns
1528    ///
1529    /// - `DeviceFormFactor` - Active HarmonyOS form factor.
1530    fn device_form_factor(&self) -> DeviceFormFactor {
1531        self.get_profile().get_device_type().form_factor()
1532    }
1533
1534    /// Returns the canonical HarmonyOS device type string (`"phone"`, `"tablet"`, `"2in1"`, `"foldable"`, `"wearable"`, `"tv"`, `"car"`).
1535    ///
1536    /// # Arguments
1537    ///
1538    /// - `&Self` - HarmonyOS platform reference.
1539    ///
1540    /// # Returns
1541    ///
1542    /// - `&'static str` - Canonical HarmonyOS device identifier.
1543    fn host_vendor_name(&self) -> &'static str {
1544        self.get_profile().get_device_type().as_str()
1545    }
1546}
1547
1548/// Default full visual-equivalence invariant checklist for `HostVisualEquivalenceGate`.
1549impl Default for HostVisualEquivalenceGate {
1550    /// Creates a visual-equivalence gate with all 8 quality invariants satisfied.
1551    ///
1552    /// # Returns
1553    ///
1554    /// - `Self` - All-equivalent gate.
1555    fn default() -> Self {
1556        Self {
1557            fonts_equivalent: true,
1558            layout_equivalent: true,
1559            color_equivalent: true,
1560            aa_equivalent: true,
1561            shadow_equivalent: true,
1562            blur_equivalent: true,
1563            visible_tiles_equivalent: true,
1564            media_quality_equivalent: true,
1565        }
1566    }
1567}
1568
1569/// Visual-equivalence invariant evaluation for `HostVisualEquivalenceGate`.
1570impl HostVisualEquivalenceGate {
1571    /// Returns `true` iff every visual invariant (fonts, layout, color, AA, shadow, blur, tiles, media) holds.
1572    ///
1573    /// # Returns
1574    ///
1575    /// - `bool` - `true` when visually equivalent.
1576    #[must_use]
1577    pub fn is_visually_equivalent(&self) -> bool {
1578        self.get_fonts_equivalent()
1579            && self.get_layout_equivalent()
1580            && self.get_color_equivalent()
1581            && self.get_aa_equivalent()
1582            && self.get_shadow_equivalent()
1583            && self.get_blur_equivalent()
1584            && self.get_visible_tiles_equivalent()
1585            && self.get_media_quality_equivalent()
1586    }
1587}
1588
1589/// Host-declared channel capability, single-channel non-probing, visual-equivalence gate, and simulated-profile honesty helpers.
1590impl HostChannelCapabilities {
1591    /// Constructs a validated `HostChannelCapabilities` enforcing single-channel non-probing and simulated-profile honesty.
1592    ///
1593    /// Whenever `simulated_profile` is `true`, `direct_gpu_verified_on_device` is unconditionally forced to `false`.
1594    ///
1595    /// # Arguments
1596    ///
1597    /// - `&'static str` - Lowercase host or vendor runtime name.
1598    /// - `Vec<HostRenderChannel>` - Host-declared supported rendering channels.
1599    /// - `HostRenderChannel` - Preferred rendering channel.
1600    /// - `HostVisualEquivalenceGate` - Visual-equivalence invariant gate.
1601    /// - `bool` - Whether this profile is simulated/off-device.
1602    /// - `bool` - Whether direct GPU presentation was verified on a real physical device.
1603    ///
1604    /// # Returns
1605    ///
1606    /// - `Self` - Validated capability descriptor.
1607    #[must_use]
1608    pub fn from_host_declaration(
1609        host_name: &'static str,
1610        supported_channels: Vec<HostRenderChannel>,
1611        preferred_channel: HostRenderChannel,
1612        visual_equivalence: HostVisualEquivalenceGate,
1613        simulated_profile: bool,
1614        direct_gpu_verified_on_device: bool,
1615    ) -> Self {
1616        let mut deduped: Vec<HostRenderChannel> =
1617            Vec::with_capacity(supported_channels.len().max(1));
1618        for ch in supported_channels.into_iter() {
1619            if !deduped.contains(&ch) {
1620                deduped.push(ch);
1621            }
1622        }
1623        if deduped.is_empty() {
1624            deduped.push(preferred_channel);
1625        }
1626        let resolved_preferred: HostRenderChannel = if deduped.contains(&preferred_channel) {
1627            preferred_channel
1628        } else {
1629            deduped[0]
1630        };
1631        let verified_gpu: bool = !simulated_profile
1632            && direct_gpu_verified_on_device
1633            && deduped.contains(&HostRenderChannel::GpuDirect);
1634        Self {
1635            host_name,
1636            supported_channels: deduped,
1637            preferred_channel: resolved_preferred,
1638            visual_equivalence,
1639            simulated_profile,
1640            direct_gpu_verified_on_device: verified_gpu,
1641        }
1642    }
1643
1644    /// Returns `true` when the host declares at most one rendering channel (strictly prohibiting alternate-mode probing).
1645    ///
1646    /// # Returns
1647    ///
1648    /// - `bool` - `true` when locked to a single channel.
1649    #[must_use]
1650    pub fn is_single_channel(&self) -> bool {
1651        self.get_supported_channels().len() <= 1
1652    }
1653
1654    /// Returns `true` iff alternate rendering channels may be probed (`supported_channels.len() > 1` and visually equivalent).
1655    ///
1656    /// # Returns
1657    ///
1658    /// - `bool` - `false` for single-channel hosts or when visual equivalence fails.
1659    #[must_use]
1660    pub fn can_probe_alternate_channels(&self) -> bool {
1661        self.get_supported_channels().len() > 1
1662            && self.get_visual_equivalence().is_visually_equivalent()
1663    }
1664
1665    /// Returns the ordered list of alternate channels eligible for probing (ALWAYS empty when `supported_channels.len() <= 1`).
1666    ///
1667    /// # Returns
1668    ///
1669    /// - `Vec<HostRenderChannel>` - Empty for single-channel hosts or visual-equivalence failures.
1670    #[must_use]
1671    pub fn probe_candidates(&self) -> Vec<HostRenderChannel> {
1672        if !self.can_probe_alternate_channels() {
1673            return Vec::new();
1674        }
1675        let preferred: HostRenderChannel = self.get_preferred_channel();
1676        self.get_supported_channels()
1677            .iter()
1678            .copied()
1679            .filter(|ch: &HostRenderChannel| *ch != preferred)
1680            .collect()
1681    }
1682
1683    /// Resolves a channel selection honoring single-channel locks, visual-equivalence gating, and simulated-profile honesty.
1684    ///
1685    /// # Arguments
1686    ///
1687    /// - `Option<HostRenderChannel>` - Optional requested channel override.
1688    ///
1689    /// # Returns
1690    ///
1691    /// - `HostChannelSelection` - Resolved channel selection and honesty flags.
1692    #[must_use]
1693    pub fn select_channel(&self, requested: Option<HostRenderChannel>) -> HostChannelSelection {
1694        let single_locked: bool = self.is_single_channel();
1695        let visual_ok: bool = self.get_visual_equivalence().is_visually_equivalent();
1696        let simulated: bool = self.get_simulated_profile();
1697        let gpu_verified: bool = !simulated && self.get_direct_gpu_verified_on_device();
1698        if single_locked {
1699            let sole: HostRenderChannel = self
1700                .get_supported_channels()
1701                .first()
1702                .copied()
1703                .unwrap_or(self.get_preferred_channel());
1704            return HostChannelSelection {
1705                selected: sole,
1706                single_channel_locked: true,
1707                probing_disabled: true,
1708                visual_equivalence_passed: visual_ok,
1709                simulated_profile: simulated,
1710                direct_gpu_verified_on_device: gpu_verified && sole == HostRenderChannel::GpuDirect,
1711            };
1712        }
1713        if !visual_ok {
1714            let safe_fallback: HostRenderChannel = if self
1715                .get_supported_channels()
1716                .contains(&HostRenderChannel::SoftwareBuffer)
1717            {
1718                HostRenderChannel::SoftwareBuffer
1719            } else if self
1720                .get_supported_channels()
1721                .contains(&HostRenderChannel::Canvas2d)
1722            {
1723                HostRenderChannel::Canvas2d
1724            } else {
1725                self.get_preferred_channel()
1726            };
1727            return HostChannelSelection {
1728                selected: safe_fallback,
1729                single_channel_locked: false,
1730                probing_disabled: true,
1731                visual_equivalence_passed: false,
1732                simulated_profile: simulated,
1733                direct_gpu_verified_on_device: false,
1734            };
1735        }
1736        let chosen: HostRenderChannel = match requested {
1737            Some(ch) if self.get_supported_channels().contains(&ch) => ch,
1738            _ => self.get_preferred_channel(),
1739        };
1740        HostChannelSelection {
1741            selected: chosen,
1742            single_channel_locked: false,
1743            probing_disabled: false,
1744            visual_equivalence_passed: true,
1745            simulated_profile: simulated,
1746            direct_gpu_verified_on_device: gpu_verified && chosen == HostRenderChannel::GpuDirect,
1747        }
1748    }
1749}
1750
1751/// Unified host-channel capability and visual-equivalence queries for `HarmonyPlatform`.
1752impl HarmonyPlatform {
1753    /// Returns the truthful `HostChannelCapabilities` for this HarmonyOS instance.
1754    ///
1755    /// Off-device / simulated profiles ALWAYS set `simulated_profile = true` and `direct_gpu_verified_on_device = false`.
1756    ///
1757    /// # Returns
1758    ///
1759    /// - `HostChannelCapabilities` - Declared HarmonyOS channels, visual gate, and real-device GPU verification flags.
1760    #[must_use]
1761    pub fn host_channel_capabilities(&self) -> HostChannelCapabilities {
1762        let on_live_ohos_device: bool =
1763            cfg!(target_env = "ohos") && self.get_attached_native_window() != 0;
1764        let simulated: bool = !on_live_ohos_device;
1765        let api: HarmonyGraphicsApi = self.get_profile().get_graphics_api();
1766        let (channels, preferred, gpu_verified): (Vec<HostRenderChannel>, HostRenderChannel, bool) =
1767            match api {
1768                HarmonyGraphicsApi::Vulkan | HarmonyGraphicsApi::OpenGlEs3 => (
1769                    vec![
1770                        HostRenderChannel::GpuDirect,
1771                        HostRenderChannel::SoftwareBuffer,
1772                    ],
1773                    if on_live_ohos_device {
1774                        HostRenderChannel::GpuDirect
1775                    } else {
1776                        HostRenderChannel::SoftwareBuffer
1777                    },
1778                    on_live_ohos_device,
1779                ),
1780                HarmonyGraphicsApi::SoftwareBuffer => (
1781                    vec![HostRenderChannel::SoftwareBuffer],
1782                    HostRenderChannel::SoftwareBuffer,
1783                    false,
1784                ),
1785            };
1786        HostChannelCapabilities::from_host_declaration(
1787            self.host_vendor_name(),
1788            channels,
1789            preferred,
1790            HostVisualEquivalenceGate::default(),
1791            simulated,
1792            gpu_verified,
1793        )
1794    }
1795
1796    /// Resolves the HarmonyOS rendering channel under unified visual-equivalence and single-channel non-probing rules.
1797    ///
1798    /// # Arguments
1799    ///
1800    /// - `Option<HostRenderChannel>` - Optional requested channel.
1801    ///
1802    /// # Returns
1803    ///
1804    /// - `HostChannelSelection` - Resolved channel decision.
1805    #[must_use]
1806    pub fn select_render_channel(
1807        &self,
1808        requested: Option<HostRenderChannel>,
1809    ) -> HostChannelSelection {
1810        self.host_channel_capabilities().select_channel(requested)
1811    }
1812}