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