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 pos_x: f32 = phys_x / scale;
656        let pos_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, pos_x, pos_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 window_event: WindowEvent = if down {
745            WindowEvent::KeyDown(wid, kev)
746        } else {
747            WindowEvent::KeyUp(wid, kev)
748        };
749        self.get_mut_pending_events().push(window_event.clone());
750        Some(window_event)
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 point_coords: PointerButton = harmony_mouse_button_to_euv(button);
805        let mods: Modifiers = self.get_active_modifiers();
806        let ptr: PointerEvent = PointerEvent::new(
807            0,
808            PointerDevice::Mouse,
809            Point::new(lx, ly),
810            point_coords,
811            1.0,
812            mods,
813        );
814        let window_event: WindowEvent = match action {
815            HARMONY_MOUSE_PRESS => WindowEvent::PointerDown(wid, ptr),
816            HARMONY_MOUSE_RELEASE => WindowEvent::PointerUp(wid, ptr),
817            HARMONY_MOUSE_MOVE => WindowEvent::PointerMove(wid, ptr),
818            HARMONY_MOUSE_CANCEL => WindowEvent::PointerCancel(wid, 0),
819            _ => return Vec::new(),
820        };
821        self.get_mut_pending_events().push(window_event.clone());
822        vec![window_event]
823    }
824
825    /// Translates a HarmonyOS PC mouse-wheel or trackpad two-finger scroll delta into `WindowEvent::Scroll`.
826    ///
827    /// # Arguments
828    ///
829    /// - `&Self` - Mutable HarmonyOS platform.
830    /// - `f32` - Horizontal scroll delta in logical vp.
831    /// - `f32` - Vertical scroll delta in logical vp.
832    ///
833    /// # Returns
834    ///
835    /// - `WindowEvent` - Normalized scroll event also enqueued for `poll_events()`.
836    pub fn handle_scroll_event(&mut self, delta_x: f32, delta_y: f32) -> WindowEvent {
837        let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
838        let dx: f32 = if delta_x.is_finite() { delta_x } else { 0.0 };
839        let dy: f32 = if delta_y.is_finite() { delta_y } else { 0.0 };
840        let window_event: WindowEvent = WindowEvent::Scroll(wid, Point::new(dx, dy));
841        self.get_mut_pending_events().push(window_event.clone());
842        window_event
843    }
844
845    /// Translates a HarmonyOS Watch digital crown rotation delta into vertical scroll events.
846    ///
847    /// # Arguments
848    ///
849    /// - `&Self` - Mutable HarmonyOS platform.
850    /// - `f32` - Rotary crown delta in detents.
851    ///
852    /// # Returns
853    ///
854    /// - `Vec<WindowEvent>` - Normalized scroll event when `delta` is non-zero.
855    pub fn handle_crown_event(&mut self, delta: f32) -> Vec<WindowEvent> {
856        if !delta.is_finite() || delta.abs() < 1e-5 {
857            return Vec::new();
858        }
859        let scroll_ev: WindowEvent =
860            self.handle_scroll_event(0.0, delta * WEARABLE_CROWN_PIXELS_PER_DETENT);
861        vec![scroll_ev]
862    }
863
864    /// Dispatches committed HarmonyOS IME UTF-8 text into `WindowEvent::TextInput`.
865    ///
866    /// # Arguments
867    ///
868    /// - `&Self` - Mutable HarmonyOS platform.
869    /// - `String` - Committed UTF-8 text.
870    pub fn handle_ime_commit(&mut self, text: String) {
871        if text.is_empty() {
872            return;
873        }
874        let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
875        self.get_mut_pending_events()
876            .push(WindowEvent::Ime(wid, ImeEvent::Commit(text.clone())));
877        self.get_mut_pending_events()
878            .push(WindowEvent::TextInput(wid, text));
879    }
880}
881
882/// `WindowController` implementation for `HarmonyPlatform`.
883impl WindowController for HarmonyPlatform {
884    /// Applies a `WindowCommand` against the HarmonyOS XComponent window record.
885    ///
886    /// # Arguments
887    ///
888    /// - `&Self` - Mutable HarmonyOS platform.
889    /// - `WindowCommand` - Command to execute.
890    ///
891    /// # Returns
892    ///
893    /// - `Result<(), PlatformError>` - Execution status.
894    fn apply_command(&mut self, command: WindowCommand) -> Result<(), PlatformError> {
895        match command {
896            WindowCommand::SetTitle(id, title) => {
897                let rec: &mut HarmonyWindowRecord = self
898                    .get_mut_windows()
899                    .get_mut(&id)
900                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
901                rec.get_mut_config().set_title(title.clone());
902                self.get_mut_outbound_commands()
903                    .push(HarmonyHostCommand::SetWindowTitle(title.clone()));
904                let _: bool = dispatch_native_action(HARMONY_ACTION_WINDOW_TITLE, &title, "");
905                Ok(())
906            }
907            WindowCommand::SetFullscreen(id, mode) => {
908                let rec: &mut HarmonyWindowRecord = self
909                    .get_mut_windows()
910                    .get_mut(&id)
911                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
912                rec.get_mut_config().set_fullscreen(mode);
913                rec.get_mut_state().set_fullscreen(mode);
914                let target_mode: HarmonyWindowMode = if mode == FullscreenMode::Windowed {
915                    HarmonyWindowMode::Floating
916                } else {
917                    HarmonyWindowMode::Fullscreen
918                };
919                self.set_window_mode(target_mode);
920                self.get_mut_outbound_commands()
921                    .push(HarmonyHostCommand::SetWindowMode(target_mode));
922                let arg: &str = if mode == FullscreenMode::Windowed {
923                    FULLSCREEN_ACTION_OFF
924                } else {
925                    FULLSCREEN_ACTION_ON
926                };
927                let _: bool = dispatch_native_action(NATIVE_ACTION_FULLSCREEN, arg, "");
928                let _: bool = dispatch_native_action(HARMONY_ACTION_WINDOW_MODE, arg, "");
929                Ok(())
930            }
931            WindowCommand::SetRenderMode(id, mode) => {
932                let profile_api: HarmonyGraphicsApi = self.get_profile().get_graphics_api();
933                let rec: &mut HarmonyWindowRecord = self
934                    .get_mut_windows()
935                    .get_mut(&id)
936                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
937                rec.get_mut_config().get_mut_render().set_mode(mode);
938                let next_api: HarmonyGraphicsApi = match mode {
939                    RenderMode::Software => HarmonyGraphicsApi::SoftwareBuffer,
940                    RenderMode::Hardware | RenderMode::Hybrid | RenderMode::Auto => profile_api,
941                };
942                rec.set_graphics_api(next_api);
943                Ok(())
944            }
945            WindowCommand::RequestRedraw(id) => {
946                if !self.get_windows().contains_key(&id) {
947                    return Err(PlatformError::WindowNotFound(id.get_value()));
948                }
949                self.get_mut_pending_events()
950                    .push(WindowEvent::RedrawRequested(id));
951                Ok(())
952            }
953            WindowCommand::Close(id) => {
954                if self.get_mut_windows().remove(&id).is_none() {
955                    return Err(PlatformError::WindowNotFound(id.get_value()));
956                }
957                self.get_mut_outbound_commands()
958                    .push(HarmonyHostCommand::CloseWindow(id));
959                Ok(())
960            }
961            WindowCommand::SetSize(id, width, height) => {
962                let clamped_w: u32 = width.max(1);
963                let clamped_h: u32 = height.max(1);
964                let scale: f32 = {
965                    let rec: &mut HarmonyWindowRecord = self
966                        .get_mut_windows()
967                        .get_mut(&id)
968                        .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
969                    let source_val: f32 = rec.get_state().get_scale_factor();
970                    rec.get_mut_config().set_size(clamped_w, clamped_h);
971                    rec.get_mut_state()
972                        .set_logical_width(clamped_w as f32)
973                        .set_logical_height(clamped_h as f32)
974                        .set_physical_width(((clamped_w as f32) * source_val).round() as u32)
975                        .set_physical_height(((clamped_h as f32) * source_val).round() as u32);
976                    source_val
977                };
978                self.get_mut_outbound_commands()
979                    .push(HarmonyHostCommand::SetWindowSize {
980                        width: clamped_w,
981                        height: clamped_h,
982                    });
983                self.get_mut_pending_events()
984                    .push(WindowEvent::Resized(id, clamped_w, clamped_h, scale));
985                Ok(())
986            }
987            WindowCommand::SetDecorations(id, enabled) => {
988                let rec: &mut HarmonyWindowRecord = self
989                    .get_mut_windows()
990                    .get_mut(&id)
991                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
992                rec.get_mut_config().set_decorations(enabled);
993                self.get_mut_outbound_commands()
994                    .push(HarmonyHostCommand::SetDecorations(enabled));
995                let arg: &str = if enabled {
996                    HARMONY_ACTION_ARG_ON
997                } else {
998                    HARMONY_ACTION_ARG_OFF
999                };
1000                let _: bool = dispatch_native_action(HARMONY_ACTION_DECORATIONS, arg, "");
1001                Ok(())
1002            }
1003            WindowCommand::SetAlwaysOnTop(id, enabled) => {
1004                let rec: &mut HarmonyWindowRecord = self
1005                    .get_mut_windows()
1006                    .get_mut(&id)
1007                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
1008                rec.get_mut_config().set_always_on_top(enabled);
1009                self.get_mut_outbound_commands()
1010                    .push(HarmonyHostCommand::SetAlwaysOnTop(enabled));
1011                let arg: &str = if enabled {
1012                    HARMONY_ACTION_ARG_ON
1013                } else {
1014                    HARMONY_ACTION_ARG_OFF
1015                };
1016                let _: bool = dispatch_native_action(HARMONY_ACTION_ALWAYS_ON_TOP, arg, "");
1017                Ok(())
1018            }
1019            WindowCommand::SetCursor(id, cursor) => {
1020                if !self.get_windows().contains_key(&id) {
1021                    return Err(PlatformError::WindowNotFound(id.get_value()));
1022                }
1023                if self.get_last_cursor() != cursor {
1024                    self.set_last_cursor(cursor);
1025                    self.get_mut_outbound_commands()
1026                        .push(HarmonyHostCommand::SetCursor(cursor));
1027                    let style_id: String = harmony_cursor_to_pointer_style(cursor).to_string();
1028                    let _: bool = dispatch_native_action(HARMONY_ACTION_CURSOR, &style_id, "");
1029                }
1030                Ok(())
1031            }
1032            WindowCommand::SetIme(id, enabled, rect) => {
1033                if !self.get_windows().contains_key(&id) {
1034                    return Err(PlatformError::WindowNotFound(id.get_value()));
1035                }
1036                self.get_mut_outbound_commands()
1037                    .push(HarmonyHostCommand::SetIme { enabled, rect });
1038                let arg: &str = if enabled {
1039                    HARMONY_ACTION_ARG_SHOW
1040                } else {
1041                    HARMONY_ACTION_ARG_HIDE
1042                };
1043                let _: bool = dispatch_native_action(HARMONY_ACTION_IME, arg, "");
1044                Ok(())
1045            }
1046            WindowCommand::SetPosition(id, _, _)
1047            | WindowCommand::SetResizable(id, _)
1048            | WindowCommand::SetVisible(id, _)
1049            | WindowCommand::SetStatusBarStyle(id, _) => {
1050                if !self.get_windows().contains_key(&id) {
1051                    return Err(PlatformError::WindowNotFound(id.get_value()));
1052                }
1053                Ok(())
1054            }
1055        }
1056    }
1057}
1058
1059/// `PlatformBackend` implementation for `HarmonyPlatform`.
1060impl PlatformBackend for HarmonyPlatform {
1061    /// Returns `PlatformKind::HarmonyOs`.
1062    ///
1063    /// # Arguments
1064    ///
1065    /// - `&Self` - HarmonyOS platform reference.
1066    ///
1067    /// # Returns
1068    ///
1069    /// - `PlatformKind` - `PlatformKind::HarmonyOs`.
1070    fn kind(&self) -> PlatformKind {
1071        PlatformKind::HarmonyOs
1072    }
1073
1074    /// Returns HarmonyOS capabilities refined by the concrete `HarmonyDeviceType`.
1075    ///
1076    /// # Arguments
1077    ///
1078    /// - `&Self` - HarmonyOS platform reference.
1079    ///
1080    /// # Returns
1081    ///
1082    /// - `PlatformCapabilities` - Device-specific HarmonyOS capabilities.
1083    fn capabilities(&self) -> PlatformCapabilities {
1084        let mut caps: PlatformCapabilities =
1085            PlatformCapabilities::for_platform(PlatformKind::HarmonyOs);
1086        match self.get_profile().get_device_type() {
1087            HarmonyDeviceType::Phone => {
1088                caps.multi_window = false;
1089                caps.hover_pointer = false;
1090                caps.hardware_keyboard = false;
1091                caps.rotary_input = false;
1092            }
1093            HarmonyDeviceType::Watch => {
1094                caps.multi_window = false;
1095                caps.hover_pointer = false;
1096                caps.stylus = false;
1097                caps.hardware_keyboard = false;
1098                caps.biometrics = false;
1099                caps.rotary_input = true;
1100            }
1101            HarmonyDeviceType::Tv => {
1102                caps.touch = false;
1103                caps.stylus = false;
1104                caps.haptics = false;
1105                caps.biometrics = false;
1106                caps.rotary_input = false;
1107            }
1108            HarmonyDeviceType::Automotive => {
1109                caps.stylus = false;
1110                caps.biometrics = false;
1111                caps.rotary_input = true;
1112            }
1113            HarmonyDeviceType::Pc2In1 => {
1114                caps.multi_window = true;
1115                caps.hover_pointer = true;
1116                caps.hardware_keyboard = true;
1117                caps.touch = true;
1118                caps.rotary_input = false;
1119            }
1120            HarmonyDeviceType::Tablet | HarmonyDeviceType::Foldable => {
1121                caps.multi_window = true;
1122                caps.hover_pointer = true;
1123                caps.hardware_keyboard = true;
1124                caps.rotary_input = false;
1125            }
1126        }
1127        caps
1128    }
1129
1130    /// Creates an ArkUI XComponent window state configured for the active HarmonyOS device profile.
1131    ///
1132    /// # Arguments
1133    ///
1134    /// - `&Self` - Mutable HarmonyOS platform.
1135    /// - `&WindowConfig` - Declarative window config.
1136    ///
1137    /// # Returns
1138    ///
1139    /// - `Result<WindowState, PlatformError>` - Created window state.
1140    fn create_window(&mut self, config: &WindowConfig) -> Result<WindowState, PlatformError> {
1141        let id: WindowId = WindowId::new(self.get_next_id());
1142        self.set_next_id(self.get_next_id().wrapping_add(1));
1143        let profile: HarmonyDeviceProfile = self.get_profile();
1144        let mut oh_cfg: WindowConfig = config.clone();
1145        if self.primary_window_id().is_none() || !self.is_pc_desktop() {
1146            oh_cfg.set_size(profile.get_logical_width(), profile.get_logical_height());
1147        }
1148        let mut state: WindowState = WindowState::from_config(id, &oh_cfg, profile.get_density());
1149        state.set_safe_area(self.get_safe_area());
1150        state.set_system_theme(self.get_theme());
1151        state
1152            .get_mut_display()
1153            .set_refresh_rate_hz(profile.get_refresh_rate_hz().round() as u32);
1154        let record: HarmonyWindowRecord = HarmonyWindowRecord {
1155            config: oh_cfg,
1156            state,
1157            xcomponent_id: HARMONY_DEFAULT_XCOMPONENT_ID.to_string(),
1158            native_window: self.get_attached_native_window(),
1159            xcomponent: self.get_attached_xcomponent(),
1160            graphics_api: profile.get_graphics_api(),
1161            surface_width: state.get_physical_width(),
1162            surface_height: state.get_physical_height(),
1163            last_frame: Framebuffer::allocate(1, 1),
1164            present_count: 0,
1165        };
1166        self.get_mut_windows().insert(id, record);
1167        if self.primary_window_id().is_none() {
1168            self.set_primary_window(Some(id));
1169        }
1170        Ok(state)
1171    }
1172
1173    /// Queries live `WindowState` for `id`.
1174    ///
1175    /// # Arguments
1176    ///
1177    /// - `&Self` - HarmonyOS platform reference.
1178    /// - `WindowId` - Window identifier.
1179    ///
1180    /// # Returns
1181    ///
1182    /// - `Option<WindowState>` - Window state if active.
1183    fn window_state(&self, id: WindowId) -> Option<WindowState> {
1184        self.get_windows()
1185            .get(&id)
1186            .map(HarmonyWindowRecord::get_state)
1187    }
1188
1189    /// Returns `RawWindowHandle::HarmonyXComponent` carrying `OHNativeWindow*` and `OH_NativeXComponent*`.
1190    ///
1191    /// # Arguments
1192    ///
1193    /// - `&Self` - HarmonyOS platform reference.
1194    /// - `WindowId` - Window identifier.
1195    ///
1196    /// # Returns
1197    ///
1198    /// - `RawWindowHandle` - HarmonyOS XComponent handle.
1199    fn raw_window_handle(&self, id: WindowId) -> RawWindowHandle {
1200        match self.get_windows().get(&id) {
1201            Some(rec) => RawWindowHandle::HarmonyXComponent {
1202                native_window: rec.get_native_window(),
1203                xcomponent: rec.get_xcomponent(),
1204            },
1205            None => RawWindowHandle::Headless,
1206        }
1207    }
1208
1209    /// Drains queued HarmonyOS XComponent, avoidArea, and UIAbility lifecycle events.
1210    ///
1211    /// # Arguments
1212    ///
1213    /// - `&Self` - Mutable HarmonyOS platform.
1214    ///
1215    /// # Returns
1216    ///
1217    /// - `Vec<WindowEvent>` - Pending events.
1218    fn poll_events(&mut self) -> Vec<WindowEvent> {
1219        take(self.get_mut_pending_events())
1220    }
1221
1222    /// Pauses or resumes the HarmonyOS `OH_NativeVSync` frame pump flag.
1223    ///
1224    /// # Arguments
1225    ///
1226    /// - `&Self` - Mutable HarmonyOS platform.
1227    /// - `bool` - `true` to pause for background freeze.
1228    fn set_frame_pump_paused(&mut self, paused: bool) {
1229        self.set_pump_paused(paused);
1230    }
1231
1232    /// Returns whether the HarmonyOS frame pump is currently paused.
1233    ///
1234    /// # Arguments
1235    ///
1236    /// - `&Self` - HarmonyOS platform reference.
1237    ///
1238    /// # Returns
1239    ///
1240    /// - `bool` - Pause state.
1241    fn is_frame_pump_paused(&self) -> bool {
1242        self.get_pump_paused()
1243    }
1244
1245    /// Presents `framebuffer` to the attached `OHNativeWindow*` buffer or offscreen fallback snapshot.
1246    ///
1247    /// # Arguments
1248    ///
1249    /// - `&Self` - Mutable HarmonyOS platform.
1250    /// - `WindowId` - Window identifier.
1251    /// - `&Framebuffer` - Rendered RGBA8 framebuffer.
1252    ///
1253    /// # Returns
1254    ///
1255    /// - `Result<(), PlatformError>` - Presentation status.
1256    fn present_framebuffer(
1257        &mut self,
1258        id: WindowId,
1259        framebuffer: &Framebuffer,
1260    ) -> Result<(), PlatformError> {
1261        self.present_framebuffer_region(id, framebuffer, DamageRegion::full())
1262    }
1263
1264    /// Presents `framebuffer` (or only `damage`) to the attached `OHNativeWindow*` buffer without cloning when capture is disabled.
1265    ///
1266    /// # Arguments
1267    ///
1268    /// - `WindowId` - Window identifier.
1269    /// - `&Framebuffer` - Rendered RGBA8 framebuffer.
1270    /// - `DamageRegion` - Damaged pixel region updated this frame.
1271    ///
1272    /// # Returns
1273    ///
1274    /// - `Result<(), PlatformError>` - Presentation status.
1275    fn present_framebuffer_region(
1276        &mut self,
1277        id: WindowId,
1278        framebuffer: &Framebuffer,
1279        damage: DamageRegion,
1280    ) -> Result<(), PlatformError> {
1281        let capture: bool = self.get_capture_last_frame();
1282        let dirty_rect: Option<Rect> = if damage.get_full_damage() {
1283            None
1284        } else {
1285            damage.bounds_rect()
1286        };
1287        let rec: &mut HarmonyWindowRecord = self
1288            .get_mut_windows()
1289            .get_mut(&id)
1290            .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
1291        let nw: usize = rec.get_native_window();
1292        let mut stroke_width: u32 = rec.get_surface_width();
1293        let mut sh: u32 = rec.get_surface_height();
1294        let res: Result<(), PlatformError> =
1295            harmony_present_native_window(nw, framebuffer, &mut stroke_width, &mut sh, dirty_rect);
1296        rec.set_surface_width(stroke_width);
1297        rec.set_surface_height(sh);
1298        if capture {
1299            rec.set_last_frame(framebuffer.clone());
1300        }
1301        rec.set_present_count(rec.get_present_count().wrapping_add(1));
1302        res
1303    }
1304
1305    /// Reads cached HarmonyOS pasteboard text.
1306    ///
1307    /// # Arguments
1308    ///
1309    /// - `&Self` - HarmonyOS platform reference.
1310    ///
1311    /// # Returns
1312    ///
1313    /// - `Option<String>` - Cached clipboard string.
1314    fn read_clipboard(&self) -> Option<String> {
1315        let Self { clipboard, .. } = self;
1316        clipboard.clone()
1317    }
1318
1319    /// Writes `text` to the HarmonyOS pasteboard cache and native action bridge.
1320    ///
1321    /// # Arguments
1322    ///
1323    /// - `&Self` - Mutable HarmonyOS platform.
1324    /// - `&str` - Clipboard text.
1325    ///
1326    /// # Returns
1327    ///
1328    /// - `Result<(), PlatformError>` - Write status.
1329    fn write_clipboard(&mut self, text: &str) -> Result<(), PlatformError> {
1330        self.set_clipboard(Some(text.to_string()));
1331        self.get_mut_outbound_commands()
1332            .push(HarmonyHostCommand::SetClipboard(text.to_string()));
1333        let _: bool = write_system_clipboard(text);
1334        Ok(())
1335    }
1336
1337    /// Returns the active HarmonyOS appearance mode.
1338    ///
1339    /// # Arguments
1340    ///
1341    /// - `&Self` - HarmonyOS platform reference.
1342    ///
1343    /// # Returns
1344    ///
1345    /// - `ThemeMode` - Active appearance mode.
1346    fn system_theme(&self) -> ThemeMode {
1347        self.get_theme()
1348    }
1349
1350    /// Returns the active HarmonyOS hardware display refresh rate in Hertz.
1351    ///
1352    /// # Arguments
1353    ///
1354    /// - `&Self` - HarmonyOS platform reference.
1355    ///
1356    /// # Returns
1357    ///
1358    /// - `f32` - Active display refresh rate in Hertz.
1359    fn display_refresh_rate_hz(&self) -> f32 {
1360        self.get_profile().get_refresh_rate_hz()
1361    }
1362}
1363
1364/// `PlatformStorage` implementation for `HarmonyPlatform`.
1365impl PlatformStorage for HarmonyPlatform {
1366    /// Reads a key from HarmonyOS preferences storage.
1367    ///
1368    /// # Arguments
1369    ///
1370    /// - `&Self` - HarmonyOS platform reference.
1371    /// - `&str` - Storage key.
1372    ///
1373    /// # Returns
1374    ///
1375    /// - `Option<String>` - Stored value, if present.
1376    fn storage_get(&self, key: &str) -> Option<String> {
1377        self.get_storage().get(key).cloned()
1378    }
1379
1380    /// Writes a key-value pair into HarmonyOS preferences storage.
1381    ///
1382    /// # Arguments
1383    ///
1384    /// - `&Self` - Mutable HarmonyOS platform.
1385    /// - `&str` - Storage key.
1386    /// - `&str` - UTF-8 value.
1387    ///
1388    /// # Returns
1389    ///
1390    /// - `Result<(), PlatformError>` - Persistence status.
1391    fn storage_set(&mut self, key: &str, value: &str) -> Result<(), PlatformError> {
1392        let _: Option<String> = self
1393            .get_mut_storage()
1394            .insert(key.to_string(), value.to_string());
1395        Ok(())
1396    }
1397
1398    /// Removes `key` from HarmonyOS preferences storage.
1399    ///
1400    /// # Arguments
1401    ///
1402    /// - `&Self` - Mutable HarmonyOS platform.
1403    /// - `&str` - Storage key.
1404    ///
1405    /// # Returns
1406    ///
1407    /// - `Result<(), PlatformError>` - Removal status.
1408    fn storage_remove(&mut self, key: &str) -> Result<(), PlatformError> {
1409        let _: Option<String> = self.get_mut_storage().remove(key);
1410        Ok(())
1411    }
1412
1413    /// Clears all keys from HarmonyOS preferences storage.
1414    ///
1415    /// # Arguments
1416    ///
1417    /// - `&Self` - Mutable HarmonyOS platform.
1418    ///
1419    /// # Returns
1420    ///
1421    /// - `Result<(), PlatformError>` - Clear status.
1422    fn storage_clear(&mut self) -> Result<(), PlatformError> {
1423        self.get_mut_storage().clear();
1424        Ok(())
1425    }
1426}
1427
1428/// `PlatformNavigation` implementation for `HarmonyPlatform`.
1429impl PlatformNavigation for HarmonyPlatform {
1430    /// Navigates to `route` on the HarmonyOS UIAbility route stack.
1431    ///
1432    /// # Arguments
1433    ///
1434    /// - `&Self` - Mutable HarmonyOS platform.
1435    /// - `&str` - Logical route path.
1436    ///
1437    /// # Returns
1438    ///
1439    /// - `Result<(), PlatformError>` - Navigation status.
1440    fn navigate_to(&mut self, route: &str) -> Result<(), PlatformError> {
1441        if !route.is_empty() {
1442            self.get_mut_route_stack().push(route.to_string());
1443        }
1444        Ok(())
1445    }
1446
1447    /// Pops `delta` entries from the HarmonyOS route stack.
1448    ///
1449    /// # Arguments
1450    ///
1451    /// - `&Self` - Mutable HarmonyOS platform.
1452    /// - `u32` - Pages to pop.
1453    ///
1454    /// # Returns
1455    ///
1456    /// - `Result<(), PlatformError>` - Navigation status.
1457    fn navigate_back(&mut self, delta: u32) -> Result<(), PlatformError> {
1458        for _ in 0..delta.max(1) {
1459            if self.get_route_stack().len() > 1 {
1460                let _: Option<String> = self.get_mut_route_stack().pop();
1461            }
1462        }
1463        Ok(())
1464    }
1465
1466    /// Returns the active HarmonyOS logical route path.
1467    ///
1468    /// # Arguments
1469    ///
1470    /// - `&Self` - HarmonyOS platform reference.
1471    ///
1472    /// # Returns
1473    ///
1474    /// - `&str` - Active route path.
1475    fn current_route(&self) -> &str {
1476        self.get_route_stack()
1477            .last()
1478            .map(String::as_str)
1479            .unwrap_or(HARMONY_DEFAULT_ROUTE)
1480    }
1481}
1482
1483/// `PlatformLifecycleBridge` implementation for `HarmonyPlatform`.
1484impl PlatformLifecycleBridge for HarmonyPlatform {
1485    /// Maps HarmonyOS `onBackground` into unified freeze semantics.
1486    ///
1487    /// # Arguments
1488    ///
1489    /// - `&Self` - Mutable HarmonyOS platform.
1490    ///
1491    /// # Returns
1492    ///
1493    /// - `Vec<WindowEvent>` - Normalized freeze events.
1494    fn freeze_surface(&mut self) -> Vec<WindowEvent> {
1495        self.handle_lifecycle_hook(HarmonyLifecycleHook::OnBackground)
1496    }
1497
1498    /// Maps HarmonyOS `onForeground` into unified resume semantics.
1499    ///
1500    /// # Arguments
1501    ///
1502    /// - `&Self` - Mutable HarmonyOS platform.
1503    ///
1504    /// # Returns
1505    ///
1506    /// - `Vec<WindowEvent>` - Normalized resume events.
1507    fn resume_surface(&mut self) -> Vec<WindowEvent> {
1508        self.handle_lifecycle_hook(HarmonyLifecycleHook::OnForeground)
1509    }
1510
1511    /// Maps HarmonyOS `onDestroy` into unified destroy semantics.
1512    ///
1513    /// # Arguments
1514    ///
1515    /// - `&Self` - Mutable HarmonyOS platform.
1516    ///
1517    /// # Returns
1518    ///
1519    /// - `Vec<WindowEvent>` - Normalized teardown events.
1520    fn destroy_surface(&mut self) -> Vec<WindowEvent> {
1521        self.handle_lifecycle_hook(HarmonyLifecycleHook::OnDestroy)
1522    }
1523}
1524
1525/// `PlatformHostAdapter` implementation for `HarmonyPlatform`.
1526impl PlatformHostAdapter for HarmonyPlatform {
1527    /// Returns the concrete `DeviceFormFactor` matching this HarmonyOS device category.
1528    ///
1529    /// # Arguments
1530    ///
1531    /// - `&Self` - HarmonyOS platform reference.
1532    ///
1533    /// # Returns
1534    ///
1535    /// - `DeviceFormFactor` - Active HarmonyOS form factor.
1536    fn device_form_factor(&self) -> DeviceFormFactor {
1537        self.get_profile().get_device_type().form_factor()
1538    }
1539
1540    /// Returns the canonical HarmonyOS device type string (`"phone"`, `"tablet"`, `"2in1"`, `"foldable"`, `"wearable"`, `"tv"`, `"car"`).
1541    ///
1542    /// # Arguments
1543    ///
1544    /// - `&Self` - HarmonyOS platform reference.
1545    ///
1546    /// # Returns
1547    ///
1548    /// - `&'static str` - Canonical HarmonyOS device identifier.
1549    fn host_vendor_name(&self) -> &'static str {
1550        self.get_profile().get_device_type().as_str()
1551    }
1552}
1553
1554/// Default full visual-equivalence invariant checklist for `HostVisualEquivalenceGate`.
1555impl Default for HostVisualEquivalenceGate {
1556    /// Creates a visual-equivalence gate with all 8 quality invariants satisfied.
1557    ///
1558    /// # Returns
1559    ///
1560    /// - `Self` - All-equivalent gate.
1561    fn default() -> Self {
1562        Self {
1563            fonts_equivalent: true,
1564            layout_equivalent: true,
1565            color_equivalent: true,
1566            aa_equivalent: true,
1567            shadow_equivalent: true,
1568            blur_equivalent: true,
1569            visible_tiles_equivalent: true,
1570            media_quality_equivalent: true,
1571        }
1572    }
1573}
1574
1575/// Visual-equivalence invariant evaluation for `HostVisualEquivalenceGate`.
1576impl HostVisualEquivalenceGate {
1577    /// Returns `true` iff every visual invariant (fonts, layout, color, AA, shadow, blur, tiles, media) holds.
1578    ///
1579    /// # Returns
1580    ///
1581    /// - `bool` - `true` when visually equivalent.
1582    #[must_use]
1583    pub fn is_visually_equivalent(&self) -> bool {
1584        self.get_fonts_equivalent()
1585            && self.get_layout_equivalent()
1586            && self.get_color_equivalent()
1587            && self.get_aa_equivalent()
1588            && self.get_shadow_equivalent()
1589            && self.get_blur_equivalent()
1590            && self.get_visible_tiles_equivalent()
1591            && self.get_media_quality_equivalent()
1592    }
1593}
1594
1595/// Host-declared channel capability, single-channel non-probing, visual-equivalence gate, and simulated-profile honesty helpers.
1596impl HostChannelCapabilities {
1597    /// Constructs a validated `HostChannelCapabilities` enforcing single-channel non-probing and simulated-profile honesty.
1598    ///
1599    /// Whenever `simulated_profile` is `true`, `direct_gpu_verified_on_device` is unconditionally forced to `false`.
1600    ///
1601    /// # Arguments
1602    ///
1603    /// - `&'static str` - Lowercase host or vendor runtime name.
1604    /// - `Vec<HostRenderChannel>` - Host-declared supported rendering channels.
1605    /// - `HostRenderChannel` - Preferred rendering channel.
1606    /// - `HostVisualEquivalenceGate` - Visual-equivalence invariant gate.
1607    /// - `bool` - Whether this profile is simulated/off-device.
1608    /// - `bool` - Whether direct GPU presentation was verified on a real physical device.
1609    ///
1610    /// # Returns
1611    ///
1612    /// - `Self` - Validated capability descriptor.
1613    #[must_use]
1614    pub fn from_host_declaration(
1615        host_name: &'static str,
1616        supported_channels: Vec<HostRenderChannel>,
1617        preferred_channel: HostRenderChannel,
1618        visual_equivalence: HostVisualEquivalenceGate,
1619        simulated_profile: bool,
1620        direct_gpu_verified_on_device: bool,
1621    ) -> Self {
1622        let mut deduped: Vec<HostRenderChannel> =
1623            Vec::with_capacity(supported_channels.len().max(1));
1624        for ch in supported_channels.into_iter() {
1625            if !deduped.contains(&ch) {
1626                deduped.push(ch);
1627            }
1628        }
1629        if deduped.is_empty() {
1630            deduped.push(preferred_channel);
1631        }
1632        let resolved_preferred: HostRenderChannel = if deduped.contains(&preferred_channel) {
1633            preferred_channel
1634        } else {
1635            deduped[0]
1636        };
1637        let verified_gpu: bool = !simulated_profile
1638            && direct_gpu_verified_on_device
1639            && deduped.contains(&HostRenderChannel::GpuDirect);
1640        Self {
1641            host_name,
1642            supported_channels: deduped,
1643            preferred_channel: resolved_preferred,
1644            visual_equivalence,
1645            simulated_profile,
1646            direct_gpu_verified_on_device: verified_gpu,
1647        }
1648    }
1649
1650    /// Returns `true` when the host declares at most one rendering channel (strictly prohibiting alternate-mode probing).
1651    ///
1652    /// # Returns
1653    ///
1654    /// - `bool` - `true` when locked to a single channel.
1655    #[must_use]
1656    pub fn is_single_channel(&self) -> bool {
1657        self.get_supported_channels().len() <= 1
1658    }
1659
1660    /// Returns `true` iff alternate rendering channels may be probed (`supported_channels.len() > 1` and visually equivalent).
1661    ///
1662    /// # Returns
1663    ///
1664    /// - `bool` - `false` for single-channel hosts or when visual equivalence fails.
1665    #[must_use]
1666    pub fn can_probe_alternate_channels(&self) -> bool {
1667        self.get_supported_channels().len() > 1
1668            && self.get_visual_equivalence().is_visually_equivalent()
1669    }
1670
1671    /// Returns the ordered list of alternate channels eligible for probing (ALWAYS empty when `supported_channels.len() <= 1`).
1672    ///
1673    /// # Returns
1674    ///
1675    /// - `Vec<HostRenderChannel>` - Empty for single-channel hosts or visual-equivalence failures.
1676    #[must_use]
1677    pub fn probe_candidates(&self) -> Vec<HostRenderChannel> {
1678        if !self.can_probe_alternate_channels() {
1679            return Vec::new();
1680        }
1681        let preferred: HostRenderChannel = self.get_preferred_channel();
1682        self.get_supported_channels()
1683            .iter()
1684            .copied()
1685            .filter(|ch: &HostRenderChannel| *ch != preferred)
1686            .collect()
1687    }
1688
1689    /// Resolves a channel selection honoring single-channel locks, visual-equivalence gating, and simulated-profile honesty.
1690    ///
1691    /// # Arguments
1692    ///
1693    /// - `Option<HostRenderChannel>` - Optional requested channel override.
1694    ///
1695    /// # Returns
1696    ///
1697    /// - `HostChannelSelection` - Resolved channel selection and honesty flags.
1698    #[must_use]
1699    pub fn select_channel(&self, requested: Option<HostRenderChannel>) -> HostChannelSelection {
1700        let single_locked: bool = self.is_single_channel();
1701        let visual_ok: bool = self.get_visual_equivalence().is_visually_equivalent();
1702        let simulated: bool = self.get_simulated_profile();
1703        let gpu_verified: bool = !simulated && self.get_direct_gpu_verified_on_device();
1704        if single_locked {
1705            let sole: HostRenderChannel = self
1706                .get_supported_channels()
1707                .first()
1708                .copied()
1709                .unwrap_or(self.get_preferred_channel());
1710            return HostChannelSelection {
1711                selected: sole,
1712                single_channel_locked: true,
1713                probing_disabled: true,
1714                visual_equivalence_passed: visual_ok,
1715                simulated_profile: simulated,
1716                direct_gpu_verified_on_device: gpu_verified && sole == HostRenderChannel::GpuDirect,
1717            };
1718        }
1719        if !visual_ok {
1720            let safe_fallback: HostRenderChannel = if self
1721                .get_supported_channels()
1722                .contains(&HostRenderChannel::SoftwareBuffer)
1723            {
1724                HostRenderChannel::SoftwareBuffer
1725            } else if self
1726                .get_supported_channels()
1727                .contains(&HostRenderChannel::Canvas2d)
1728            {
1729                HostRenderChannel::Canvas2d
1730            } else {
1731                self.get_preferred_channel()
1732            };
1733            return HostChannelSelection {
1734                selected: safe_fallback,
1735                single_channel_locked: false,
1736                probing_disabled: true,
1737                visual_equivalence_passed: false,
1738                simulated_profile: simulated,
1739                direct_gpu_verified_on_device: false,
1740            };
1741        }
1742        let chosen: HostRenderChannel = match requested {
1743            Some(ch) if self.get_supported_channels().contains(&ch) => ch,
1744            _ => self.get_preferred_channel(),
1745        };
1746        HostChannelSelection {
1747            selected: chosen,
1748            single_channel_locked: false,
1749            probing_disabled: false,
1750            visual_equivalence_passed: true,
1751            simulated_profile: simulated,
1752            direct_gpu_verified_on_device: gpu_verified && chosen == HostRenderChannel::GpuDirect,
1753        }
1754    }
1755}
1756
1757/// Unified host-channel capability and visual-equivalence queries for `HarmonyPlatform`.
1758impl HarmonyPlatform {
1759    /// Returns the truthful `HostChannelCapabilities` for this HarmonyOS instance.
1760    ///
1761    /// Off-device / simulated profiles ALWAYS set `simulated_profile = true` and `direct_gpu_verified_on_device = false`.
1762    ///
1763    /// # Returns
1764    ///
1765    /// - `HostChannelCapabilities` - Declared HarmonyOS channels, visual gate, and real-device GPU verification flags.
1766    #[must_use]
1767    pub fn host_channel_capabilities(&self) -> HostChannelCapabilities {
1768        let on_live_ohos_device: bool =
1769            cfg!(target_env = "ohos") && self.get_attached_native_window() != 0;
1770        let simulated: bool = !on_live_ohos_device;
1771        let api: HarmonyGraphicsApi = self.get_profile().get_graphics_api();
1772        let (channels, preferred, gpu_verified): (Vec<HostRenderChannel>, HostRenderChannel, bool) =
1773            match api {
1774                HarmonyGraphicsApi::Vulkan | HarmonyGraphicsApi::OpenGlEs3 => (
1775                    vec![
1776                        HostRenderChannel::GpuDirect,
1777                        HostRenderChannel::SoftwareBuffer,
1778                    ],
1779                    if on_live_ohos_device {
1780                        HostRenderChannel::GpuDirect
1781                    } else {
1782                        HostRenderChannel::SoftwareBuffer
1783                    },
1784                    on_live_ohos_device,
1785                ),
1786                HarmonyGraphicsApi::SoftwareBuffer => (
1787                    vec![HostRenderChannel::SoftwareBuffer],
1788                    HostRenderChannel::SoftwareBuffer,
1789                    false,
1790                ),
1791            };
1792        HostChannelCapabilities::from_host_declaration(
1793            self.host_vendor_name(),
1794            channels,
1795            preferred,
1796            HostVisualEquivalenceGate::default(),
1797            simulated,
1798            gpu_verified,
1799        )
1800    }
1801
1802    /// Resolves the HarmonyOS rendering channel under unified visual-equivalence and single-channel non-probing rules.
1803    ///
1804    /// # Arguments
1805    ///
1806    /// - `Option<HostRenderChannel>` - Optional requested channel.
1807    ///
1808    /// # Returns
1809    ///
1810    /// - `HostChannelSelection` - Resolved channel decision.
1811    #[must_use]
1812    pub fn select_render_channel(
1813        &self,
1814        requested: Option<HostRenderChannel>,
1815    ) -> HostChannelSelection {
1816        self.host_channel_capabilities().select_channel(requested)
1817    }
1818}