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    /// Returns all 7 supported HarmonyOS / OpenHarmony device form factors.
50    ///
51    /// # Returns
52    ///
53    /// - `[Self; 7]` - Array covering Phone, Tablet, PC/2-in-1, Foldable, Watch, TV, and Automotive.
54    #[must_use]
55    pub const fn all_device_types() -> [Self; 7] {
56        [
57            Self::Phone,
58            Self::Tablet,
59            Self::Pc2In1,
60            Self::Foldable,
61            Self::Watch,
62            Self::Tv,
63            Self::Automotive,
64        ]
65    }
66}
67
68/// Hardware presets for `HarmonyDeviceProfile`.
69impl HarmonyDeviceProfile {
70    /// Returns the canonical viewport, density, refresh rate, and graphics API profile for `device_type`.
71    ///
72    /// # Arguments
73    ///
74    /// - `HarmonyDeviceType` - Target HarmonyOS device category.
75    ///
76    /// # Returns
77    ///
78    /// - `Self` - Preconfigured HarmonyOS device profile.
79    #[must_use]
80    pub const fn for_device_type(device_type: HarmonyDeviceType) -> Self {
81        match device_type {
82            HarmonyDeviceType::Phone => Self {
83                device_type,
84                logical_width: 390,
85                logical_height: 844,
86                density: 3.0,
87                refresh_rate_hz: 120.0,
88                graphics_api: HarmonyGraphicsApi::OpenGlEs3,
89            },
90            HarmonyDeviceType::Tablet => Self {
91                device_type,
92                logical_width: 960,
93                logical_height: 640,
94                density: 2.0,
95                refresh_rate_hz: 120.0,
96                graphics_api: HarmonyGraphicsApi::Vulkan,
97            },
98            HarmonyDeviceType::Pc2In1 => Self {
99                device_type,
100                logical_width: 1440,
101                logical_height: 900,
102                density: 2.0,
103                refresh_rate_hz: 120.0,
104                graphics_api: HarmonyGraphicsApi::Vulkan,
105            },
106            HarmonyDeviceType::Foldable => Self {
107                device_type,
108                logical_width: 712,
109                logical_height: 800,
110                density: 3.0,
111                refresh_rate_hz: 120.0,
112                graphics_api: HarmonyGraphicsApi::Vulkan,
113            },
114            HarmonyDeviceType::Watch => Self {
115                device_type,
116                logical_width: 233,
117                logical_height: 233,
118                density: 2.0,
119                refresh_rate_hz: 60.0,
120                graphics_api: HarmonyGraphicsApi::OpenGlEs3,
121            },
122            HarmonyDeviceType::Tv => Self {
123                device_type,
124                logical_width: 1920,
125                logical_height: 1080,
126                density: 2.0,
127                refresh_rate_hz: 120.0,
128                graphics_api: HarmonyGraphicsApi::Vulkan,
129            },
130            HarmonyDeviceType::Automotive => Self {
131                device_type,
132                logical_width: 1920,
133                logical_height: 720,
134                density: 1.5,
135                refresh_rate_hz: 60.0,
136                graphics_api: HarmonyGraphicsApi::OpenGlEs3,
137            },
138        }
139    }
140}
141
142/// Default `HarmonyPlatform` configured for `HarmonyDeviceType::Phone`.
143impl Default for HarmonyPlatform {
144    /// Creates a default HarmonyOS smartphone platform backend.
145    ///
146    /// # Returns
147    ///
148    /// - `Self` - Default `HarmonyPlatform`.
149    fn default() -> Self {
150        Self::for_device_type(HarmonyDeviceType::Phone)
151    }
152}
153
154/// ArkUI XComponent binding, `avoidArea` safe-area, foldable transition, touch/key/IME, and UIAbility lifecycle hooks for `HarmonyPlatform`.
155impl HarmonyPlatform {
156    /// Creates a `HarmonyPlatform` configured for any of the 7 HarmonyOS device form factors.
157    ///
158    /// # Arguments
159    ///
160    /// - `HarmonyDeviceType` - Target HarmonyOS device category.
161    ///
162    /// # Returns
163    ///
164    /// - `Self` - Configured HarmonyOS platform backend.
165    #[must_use]
166    pub fn for_device_type(device_type: HarmonyDeviceType) -> Self {
167        let profile: HarmonyDeviceProfile = HarmonyDeviceProfile::for_device_type(device_type);
168        let safe_area: SafeAreaInsets = resolve_harmony_avoid_area(
169            device_type,
170            HarmonyAvoidArea::default(),
171            profile.get_density(),
172            profile.get_logical_width(),
173            profile.get_logical_height(),
174            false,
175        );
176        Self {
177            profile,
178            fold_state: HarmonyFoldState::Expanded,
179            attached_native_window: 0,
180            attached_xcomponent: 0,
181            safe_area,
182            lifecycle: MobileSessionLifecycle::default(),
183            next_id: 1,
184            primary_window: None,
185            windows: HashMap::new(),
186            pending_events: Vec::new(),
187            clipboard: None,
188            storage: HashMap::new(),
189            route_stack: vec![HARMONY_DEFAULT_ROUTE.to_string()],
190            theme: ThemeMode::Light,
191            pump_paused: false,
192        }
193    }
194
195    /// Returns the primary XComponent `WindowId`, if created.
196    ///
197    /// # Arguments
198    ///
199    /// - `&Self` - HarmonyOS platform reference.
200    ///
201    /// # Returns
202    ///
203    /// - `Option<WindowId>` - Primary window handle.
204    #[must_use]
205    pub fn primary_window_id(&self) -> Option<WindowId> {
206        let Self { primary_window, .. } = self;
207        *primary_window
208    }
209
210    /// Attaches live ArkUI `OHNativeWindow*` and `OH_NativeXComponent*` handles received from `OnSurfaceCreatedCB`.
211    ///
212    /// # Arguments
213    ///
214    /// - `&Self` - Mutable HarmonyOS platform.
215    /// - `usize` - Raw `OHNativeWindow*` pointer.
216    /// - `usize` - Raw `OH_NativeXComponent*` pointer.
217    /// - `u32` - Physical surface width in pixels.
218    /// - `u32` - Physical surface height in pixels.
219    pub fn attach_xcomponent(
220        &mut self,
221        native_window: usize,
222        xcomponent: usize,
223        phys_width: u32,
224        phys_height: u32,
225    ) {
226        self.set_attached_native_window(native_window);
227        self.set_attached_xcomponent(xcomponent);
228        self.get_mut_lifecycle().on_surface_created();
229        let scale: f32 = self.get_profile().get_density().max(0.75);
230        let pw: u32 = phys_width.max(1);
231        let ph: u32 = phys_height.max(1);
232        let lw: u32 = ((pw as f32) / scale).round().max(1.0) as u32;
233        let lh: u32 = ((ph as f32) / scale).round().max(1.0) as u32;
234        let mut resized: Vec<WindowId> = Vec::with_capacity(self.get_windows().len());
235        for (&wid, rec) in self.get_mut_windows().iter_mut() {
236            rec.set_native_window(native_window);
237            rec.set_xcomponent(xcomponent);
238            rec.set_surface_width(pw);
239            rec.set_surface_height(ph);
240            rec.get_mut_state()
241                .set_physical_width(pw)
242                .set_physical_height(ph)
243                .set_logical_width(lw as f32)
244                .set_logical_height(lh as f32)
245                .set_scale_factor(scale);
246            resized.push(wid);
247        }
248        for wid in resized.into_iter() {
249            self.get_mut_pending_events()
250                .push(WindowEvent::Resized(wid, lw, lh, scale));
251        }
252    }
253
254    /// Detaches ArkUI `OHNativeWindow*` safely on `OnSurfaceDestroyedCB` and cancels dangling touches.
255    ///
256    /// # Arguments
257    ///
258    /// - `&Self` - Mutable HarmonyOS platform.
259    pub fn detach_xcomponent(&mut self) {
260        self.set_attached_native_window(0);
261        self.set_attached_xcomponent(0);
262        let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
263        for rec in self.get_mut_windows().values_mut() {
264            rec.set_native_window(0);
265            rec.set_xcomponent(0);
266            rec.set_surface_width(0);
267            rec.set_surface_height(0);
268        }
269        let cancels: Vec<WindowEvent> = self.get_mut_lifecycle().on_surface_destroyed(wid);
270        self.get_mut_pending_events().extend(cancels);
271    }
272
273    /// Updates HarmonyOS `window.AvoidArea` insets and emits `SafeAreaChanged` plus `KeyboardVisibilityChanged`.
274    ///
275    /// # Arguments
276    ///
277    /// - `&Self` - Mutable HarmonyOS platform.
278    /// - `HarmonyAvoidArea` - Physical-pixel avoid area from `@ohos.window`.
279    pub fn update_avoid_area(&mut self, avoid: HarmonyAvoidArea) {
280        let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
281        let scale: f32 = self.get_profile().get_density().max(0.75);
282        let (lw, lh, immersive): (u32, u32, bool) = self
283            .get_windows()
284            .get(&wid)
285            .map(|rec: &HarmonyWindowRecord| {
286                (
287                    rec.get_state().get_logical_width().round().max(1.0) as u32,
288                    rec.get_state().get_logical_height().round().max(1.0) as u32,
289                    rec.get_state().get_fullscreen() != FullscreenMode::Windowed,
290                )
291            })
292            .unwrap_or((
293                self.get_profile().get_logical_width(),
294                self.get_profile().get_logical_height(),
295                false,
296            ));
297        let insets: SafeAreaInsets = resolve_harmony_avoid_area(
298            self.get_profile().get_device_type(),
299            avoid,
300            scale,
301            lw,
302            lh,
303            immersive,
304        );
305        self.set_safe_area(insets);
306        for rec in self.get_mut_windows().values_mut() {
307            rec.get_mut_state().set_safe_area(insets);
308        }
309        self.get_mut_pending_events()
310            .push(WindowEvent::SafeAreaChanged(wid, insets));
311        self.get_mut_pending_events()
312            .push(WindowEvent::System(SystemEvent::SafeAreaChanged(insets)));
313        let kb_h: f32 = (avoid.get_keyboard_px() as f32) / scale;
314        self.get_mut_pending_events().push(WindowEvent::System(
315            SystemEvent::KeyboardVisibilityChanged {
316                visible: avoid.get_keyboard_px() > 0,
317                height: kb_h,
318            },
319        ));
320    }
321
322    /// Translates a Stage-Model `HarmonyLifecycleHook` into canonical EUV `SystemEvent`s and Freeze/Resume/Destroy transitions.
323    ///
324    /// # Arguments
325    ///
326    /// - `&Self` - Mutable HarmonyOS platform.
327    /// - `HarmonyLifecycleHook` - Native ArkTS UIAbility / WindowStage callback payload.
328    ///
329    /// # Returns
330    ///
331    /// - `Vec<WindowEvent>` - Normalized events also enqueued for `poll_events()`.
332    pub fn handle_lifecycle_hook(&mut self, hook: HarmonyLifecycleHook) -> Vec<WindowEvent> {
333        let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
334        let mut emitted: Vec<WindowEvent> = Vec::new();
335        match hook {
336            HarmonyLifecycleHook::OnCreate { want_uri } => {
337                let _: u64 = self
338                    .get_mut_lifecycle()
339                    .begin_session(wid.get_value().max(1));
340                if let Some(uri) = want_uri
341                    && !uri.is_empty()
342                {
343                    emitted.push(WindowEvent::System(SystemEvent::DeepLink(uri)));
344                }
345            }
346            HarmonyLifecycleHook::OnWindowStageCreate {
347                native_window,
348                xcomponent,
349            } => {
350                self.set_attached_native_window(native_window);
351                self.set_attached_xcomponent(xcomponent);
352                self.get_mut_lifecycle().on_surface_created();
353                emitted.push(WindowEvent::System(SystemEvent::Appear));
354            }
355            HarmonyLifecycleHook::OnForeground => {
356                let _: u64 = self.get_mut_lifecycle().on_resume();
357                self.set_pump_paused(false);
358                emitted.push(WindowEvent::System(SystemEvent::Appear));
359                emitted.push(WindowEvent::System(SystemEvent::Foreground));
360            }
361            HarmonyLifecycleHook::OnWindowActive => {
362                if let Some(rec) = self.get_mut_windows().get_mut(&wid) {
363                    rec.get_mut_state().set_focused(true);
364                }
365                emitted.push(WindowEvent::Focused(wid, true));
366                emitted.push(WindowEvent::System(SystemEvent::FocusChanged(true)));
367            }
368            HarmonyLifecycleHook::OnWindowInactive => {
369                if let Some(rec) = self.get_mut_windows().get_mut(&wid) {
370                    rec.get_mut_state().set_focused(false);
371                }
372                let cancels: Vec<WindowEvent> = self.get_mut_lifecycle().on_pause(wid);
373                emitted.extend(cancels);
374                emitted.push(WindowEvent::Focused(wid, false));
375                emitted.push(WindowEvent::System(SystemEvent::FocusChanged(false)));
376                emitted.push(WindowEvent::System(SystemEvent::Inactive));
377            }
378            HarmonyLifecycleHook::OnBackground => {
379                let cancels: Vec<WindowEvent> = self.get_mut_lifecycle().on_pause(wid);
380                self.get_mut_lifecycle().on_background();
381                self.set_pump_paused(true);
382                emitted.extend(cancels);
383                emitted.push(WindowEvent::System(SystemEvent::Disappear));
384                emitted.push(WindowEvent::System(SystemEvent::Background));
385            }
386            HarmonyLifecycleHook::OnWindowStageDestroy => {
387                self.set_attached_native_window(0);
388                self.set_attached_xcomponent(0);
389                let cancels: Vec<WindowEvent> = self.get_mut_lifecycle().on_surface_destroyed(wid);
390                self.set_pump_paused(true);
391                emitted.extend(cancels);
392                emitted.push(WindowEvent::System(SystemEvent::Disappear));
393            }
394            HarmonyLifecycleHook::OnDestroy => {
395                self.set_attached_native_window(0);
396                self.set_attached_xcomponent(0);
397                self.get_mut_lifecycle().on_terminate();
398                self.set_pump_paused(true);
399                emitted.push(WindowEvent::System(SystemEvent::Terminate));
400            }
401            HarmonyLifecycleHook::OnMemoryLevel(level) => {
402                let pressure: MemoryPressure = harmony_memory_level_to_pressure(level);
403                emitted.push(WindowEvent::System(SystemEvent::MemoryWarning(pressure)));
404            }
405            HarmonyLifecycleHook::OnConfigurationUpdate {
406                theme,
407                locale,
408                density,
409                fold_state,
410            } => {
411                self.set_theme(theme);
412                let safe_density: f32 = if density.is_finite() {
413                    density.clamp(0.75, 4.5)
414                } else {
415                    self.get_profile().get_density()
416                };
417                self.get_mut_profile().set_density(safe_density);
418                emitted.push(WindowEvent::ThemeChanged(wid, theme));
419                emitted.push(WindowEvent::System(SystemEvent::ThemeChanged(theme)));
420                if !locale.trim().is_empty() {
421                    emitted.push(WindowEvent::System(SystemEvent::LocaleChanged(locale)));
422                }
423                if let Some(posture) = fold_state {
424                    self.set_fold_state(posture);
425                    let (lw, lh): (u32, u32) = match posture {
426                        HarmonyFoldState::Folded => (390, 844),
427                        HarmonyFoldState::HalfFolded => (712, 420),
428                        HarmonyFoldState::Expanded => (712, 800),
429                    };
430                    if let Some(rec) = self.get_mut_windows().get_mut(&wid) {
431                        rec.get_mut_state()
432                            .set_logical_width(lw as f32)
433                            .set_logical_height(lh as f32)
434                            .set_physical_width(((lw as f32) * safe_density).round() as u32)
435                            .set_physical_height(((lh as f32) * safe_density).round() as u32)
436                            .set_scale_factor(safe_density);
437                    }
438                    emitted.push(WindowEvent::Resized(wid, lw, lh, safe_density));
439                    emitted.push(WindowEvent::System(SystemEvent::Resize {
440                        width: lw as f32,
441                        height: lh as f32,
442                        scale_factor: safe_density,
443                    }));
444                }
445            }
446            HarmonyLifecycleHook::OnBackPress => {
447                emitted.push(WindowEvent::KeyDown(
448                    wid,
449                    KeyEvent::new(KeyCode::Back, Modifiers::default(), false),
450                ));
451                emitted.push(WindowEvent::System(SystemEvent::BackPressed));
452            }
453            HarmonyLifecycleHook::OnNewWant(uri) => {
454                if !uri.is_empty() {
455                    emitted.push(WindowEvent::System(SystemEvent::DeepLink(uri)));
456                }
457            }
458        }
459        self.get_mut_pending_events().extend(emitted.clone());
460        emitted
461    }
462
463    /// Translates an OpenHarmony `OH_NativeXComponent` touch contact action into normalized EUV pointer events.
464    ///
465    /// # Arguments
466    ///
467    /// - `&Self` - Mutable HarmonyOS platform.
468    /// - `i32` - OpenHarmony touch action (`HARMONY_TOUCH_DOWN`..`HARMONY_TOUCH_CANCEL`).
469    /// - `i32` - Raw contact identifier.
470    /// - `f32` - Component-local physical X coordinate.
471    /// - `f32` - Component-local physical Y coordinate.
472    ///
473    /// # Returns
474    ///
475    /// - `Vec<WindowEvent>` - Normalized pointer events.
476    pub fn handle_touch_event(
477        &mut self,
478        touch_type: i32,
479        raw_id: i32,
480        phys_x: f32,
481        phys_y: f32,
482    ) -> Vec<WindowEvent> {
483        let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
484        let scale: f32 = self.get_profile().get_density().max(0.75);
485        let x: f32 = phys_x / scale;
486        let y: f32 = phys_y / scale;
487        let action_mapped: i32 = match touch_type {
488            HARMONY_TOUCH_DOWN => ANDROID_ACTION_DOWN,
489            HARMONY_TOUCH_MOVE => ANDROID_ACTION_MOVE,
490            HARMONY_TOUCH_UP => ANDROID_ACTION_UP,
491            HARMONY_TOUCH_CANCEL => ANDROID_ACTION_CANCEL,
492            _ => return Vec::new(),
493        };
494        let events: Vec<WindowEvent> = self
495            .get_mut_lifecycle()
496            .touch_tracker_mut()
497            .handle_android_motion(wid, action_mapped, 0, &[(raw_id, x, y)]);
498        self.get_mut_pending_events().extend(events.clone());
499        events
500    }
501
502    /// Translates an OpenHarmony NDK key code (`KEYCODE_*`) into a unified `WindowEvent::KeyDown` or `KeyUp`.
503    ///
504    /// # Arguments
505    ///
506    /// - `&Self` - Mutable HarmonyOS platform.
507    /// - `i32` - OpenHarmony key code.
508    /// - `bool` - `true` for key down, `false` for key up.
509    ///
510    /// # Returns
511    ///
512    /// - `Option<WindowEvent>` - Translated keyboard event if recognized.
513    pub fn handle_key_event(&mut self, ohos_code: i32, down: bool) -> Option<WindowEvent> {
514        let code: KeyCode = harmony_keycode_to_euv(ohos_code);
515        if code == KeyCode::Unknown {
516            return None;
517        }
518        let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
519        let kev: KeyEvent = KeyEvent::new(code, Modifiers::default(), false);
520        let ev: WindowEvent = if down {
521            WindowEvent::KeyDown(wid, kev)
522        } else {
523            WindowEvent::KeyUp(wid, kev)
524        };
525        self.get_mut_pending_events().push(ev.clone());
526        Some(ev)
527    }
528
529    /// Dispatches committed HarmonyOS IME UTF-8 text into `WindowEvent::TextInput`.
530    ///
531    /// # Arguments
532    ///
533    /// - `&Self` - Mutable HarmonyOS platform.
534    /// - `String` - Committed UTF-8 text.
535    pub fn handle_ime_commit(&mut self, text: String) {
536        if text.is_empty() {
537            return;
538        }
539        let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
540        self.get_mut_pending_events()
541            .push(WindowEvent::Ime(wid, ImeEvent::Commit(text.clone())));
542        self.get_mut_pending_events()
543            .push(WindowEvent::TextInput(wid, text));
544    }
545}
546
547/// `WindowController` implementation for `HarmonyPlatform`.
548impl WindowController for HarmonyPlatform {
549    /// Applies a `WindowCommand` against the HarmonyOS XComponent window record.
550    ///
551    /// # Arguments
552    ///
553    /// - `&Self` - Mutable HarmonyOS platform.
554    /// - `WindowCommand` - Command to execute.
555    ///
556    /// # Returns
557    ///
558    /// - `Result<(), PlatformError>` - Execution status.
559    fn apply_command(&mut self, command: WindowCommand) -> Result<(), PlatformError> {
560        match command {
561            WindowCommand::SetTitle(id, title) => {
562                let rec: &mut HarmonyWindowRecord = self
563                    .get_mut_windows()
564                    .get_mut(&id)
565                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
566                rec.get_mut_config().set_title(title);
567                Ok(())
568            }
569            WindowCommand::SetFullscreen(id, mode) => {
570                let rec: &mut HarmonyWindowRecord = self
571                    .get_mut_windows()
572                    .get_mut(&id)
573                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
574                rec.get_mut_config().set_fullscreen(mode);
575                rec.get_mut_state().set_fullscreen(mode);
576                let arg: &str = if mode == FullscreenMode::Windowed {
577                    FULLSCREEN_ACTION_OFF
578                } else {
579                    FULLSCREEN_ACTION_ON
580                };
581                let _: bool = dispatch_native_action(NATIVE_ACTION_FULLSCREEN, arg, "");
582                Ok(())
583            }
584            WindowCommand::SetRenderMode(id, mode) => {
585                let profile_api: HarmonyGraphicsApi = self.get_profile().get_graphics_api();
586                let rec: &mut HarmonyWindowRecord = self
587                    .get_mut_windows()
588                    .get_mut(&id)
589                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
590                rec.get_mut_config().get_mut_render().set_mode(mode);
591                let next_api: HarmonyGraphicsApi = match mode {
592                    RenderMode::Software => HarmonyGraphicsApi::SoftwareBuffer,
593                    RenderMode::Hardware | RenderMode::Hybrid | RenderMode::Auto => profile_api,
594                };
595                rec.set_graphics_api(next_api);
596                Ok(())
597            }
598            WindowCommand::RequestRedraw(id) => {
599                if !self.get_windows().contains_key(&id) {
600                    return Err(PlatformError::WindowNotFound(id.get_value()));
601                }
602                self.get_mut_pending_events()
603                    .push(WindowEvent::RedrawRequested(id));
604                Ok(())
605            }
606            WindowCommand::Close(id) => {
607                if self.get_mut_windows().remove(&id).is_none() {
608                    return Err(PlatformError::WindowNotFound(id.get_value()));
609                }
610                Ok(())
611            }
612            WindowCommand::SetSize(id, width, height) => {
613                let scale: f32 = {
614                    let rec: &mut HarmonyWindowRecord = self
615                        .get_mut_windows()
616                        .get_mut(&id)
617                        .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
618                    let s: f32 = rec.get_state().get_scale_factor();
619                    rec.get_mut_config().set_size(width.max(1), height.max(1));
620                    rec.get_mut_state()
621                        .set_logical_width(width.max(1) as f32)
622                        .set_logical_height(height.max(1) as f32)
623                        .set_physical_width(((width.max(1) as f32) * s).round() as u32)
624                        .set_physical_height(((height.max(1) as f32) * s).round() as u32);
625                    s
626                };
627                self.get_mut_pending_events().push(WindowEvent::Resized(
628                    id,
629                    width.max(1),
630                    height.max(1),
631                    scale,
632                ));
633                Ok(())
634            }
635            WindowCommand::SetPosition(id, _, _)
636            | WindowCommand::SetResizable(id, _)
637            | WindowCommand::SetDecorations(id, _)
638            | WindowCommand::SetAlwaysOnTop(id, _)
639            | WindowCommand::SetVisible(id, _)
640            | WindowCommand::SetCursor(id, _)
641            | WindowCommand::SetIme(id, _, _)
642            | WindowCommand::SetStatusBarStyle(id, _) => {
643                if !self.get_windows().contains_key(&id) {
644                    return Err(PlatformError::WindowNotFound(id.get_value()));
645                }
646                Ok(())
647            }
648        }
649    }
650}
651
652/// `PlatformBackend` implementation for `HarmonyPlatform`.
653impl PlatformBackend for HarmonyPlatform {
654    /// Returns `PlatformKind::HarmonyOs`.
655    ///
656    /// # Arguments
657    ///
658    /// - `&Self` - HarmonyOS platform reference.
659    ///
660    /// # Returns
661    ///
662    /// - `PlatformKind` - `PlatformKind::HarmonyOs`.
663    fn kind(&self) -> PlatformKind {
664        PlatformKind::HarmonyOs
665    }
666
667    /// Returns HarmonyOS capabilities refined by the concrete `HarmonyDeviceType`.
668    ///
669    /// # Arguments
670    ///
671    /// - `&Self` - HarmonyOS platform reference.
672    ///
673    /// # Returns
674    ///
675    /// - `PlatformCapabilities` - Device-specific HarmonyOS capabilities.
676    fn capabilities(&self) -> PlatformCapabilities {
677        let mut caps: PlatformCapabilities =
678            PlatformCapabilities::for_platform(PlatformKind::HarmonyOs);
679        match self.get_profile().get_device_type() {
680            HarmonyDeviceType::Phone => {
681                caps.multi_window = false;
682                caps.hover_pointer = false;
683                caps.hardware_keyboard = false;
684                caps.rotary_input = false;
685            }
686            HarmonyDeviceType::Watch => {
687                caps.multi_window = false;
688                caps.hover_pointer = false;
689                caps.stylus = false;
690                caps.hardware_keyboard = false;
691                caps.biometrics = false;
692                caps.rotary_input = true;
693            }
694            HarmonyDeviceType::Tv => {
695                caps.touch = false;
696                caps.stylus = false;
697                caps.haptics = false;
698                caps.biometrics = false;
699                caps.rotary_input = false;
700            }
701            HarmonyDeviceType::Automotive => {
702                caps.stylus = false;
703                caps.biometrics = false;
704                caps.rotary_input = true;
705            }
706            HarmonyDeviceType::Tablet | HarmonyDeviceType::Pc2In1 | HarmonyDeviceType::Foldable => {
707                caps.rotary_input = false;
708            }
709        }
710        caps
711    }
712
713    /// Creates an ArkUI XComponent window state configured for the active HarmonyOS device profile.
714    ///
715    /// # Arguments
716    ///
717    /// - `&Self` - Mutable HarmonyOS platform.
718    /// - `&WindowConfig` - Declarative window config.
719    ///
720    /// # Returns
721    ///
722    /// - `Result<WindowState, PlatformError>` - Created window state.
723    fn create_window(&mut self, config: &WindowConfig) -> Result<WindowState, PlatformError> {
724        let id: WindowId = WindowId::new(self.get_next_id());
725        self.set_next_id(self.get_next_id().wrapping_add(1));
726        let profile: HarmonyDeviceProfile = self.get_profile();
727        let mut oh_cfg: WindowConfig = config.clone();
728        oh_cfg.set_size(profile.get_logical_width(), profile.get_logical_height());
729        let mut state: WindowState = WindowState::from_config(id, &oh_cfg, profile.get_density());
730        state.set_safe_area(self.get_safe_area());
731        state.set_system_theme(self.get_theme());
732        state
733            .get_mut_display()
734            .set_refresh_rate_hz(profile.get_refresh_rate_hz().round() as u32);
735        let record: HarmonyWindowRecord = HarmonyWindowRecord {
736            config: oh_cfg,
737            state,
738            xcomponent_id: HARMONY_DEFAULT_XCOMPONENT_ID.to_string(),
739            native_window: self.get_attached_native_window(),
740            xcomponent: self.get_attached_xcomponent(),
741            graphics_api: profile.get_graphics_api(),
742            surface_width: state.get_physical_width(),
743            surface_height: state.get_physical_height(),
744            last_frame: Framebuffer::allocate(
745                state.get_physical_width(),
746                state.get_physical_height(),
747            ),
748            present_count: 0,
749        };
750        self.get_mut_windows().insert(id, record);
751        if self.primary_window_id().is_none() {
752            self.set_primary_window(Some(id));
753        }
754        Ok(state)
755    }
756
757    /// Queries live `WindowState` for `id`.
758    ///
759    /// # Arguments
760    ///
761    /// - `&Self` - HarmonyOS platform reference.
762    /// - `WindowId` - Window identifier.
763    ///
764    /// # Returns
765    ///
766    /// - `Option<WindowState>` - Window state if active.
767    fn window_state(&self, id: WindowId) -> Option<WindowState> {
768        self.get_windows()
769            .get(&id)
770            .map(HarmonyWindowRecord::get_state)
771    }
772
773    /// Returns `RawWindowHandle::HarmonyXComponent` carrying `OHNativeWindow*` and `OH_NativeXComponent*`.
774    ///
775    /// # Arguments
776    ///
777    /// - `&Self` - HarmonyOS platform reference.
778    /// - `WindowId` - Window identifier.
779    ///
780    /// # Returns
781    ///
782    /// - `RawWindowHandle` - HarmonyOS XComponent handle.
783    fn raw_window_handle(&self, id: WindowId) -> RawWindowHandle {
784        match self.get_windows().get(&id) {
785            Some(rec) => RawWindowHandle::HarmonyXComponent {
786                native_window: rec.get_native_window(),
787                xcomponent: rec.get_xcomponent(),
788            },
789            None => RawWindowHandle::Headless,
790        }
791    }
792
793    /// Drains queued HarmonyOS XComponent, avoidArea, and UIAbility lifecycle events.
794    ///
795    /// # Arguments
796    ///
797    /// - `&Self` - Mutable HarmonyOS platform.
798    ///
799    /// # Returns
800    ///
801    /// - `Vec<WindowEvent>` - Pending events.
802    fn poll_events(&mut self) -> Vec<WindowEvent> {
803        take(self.get_mut_pending_events())
804    }
805
806    /// Pauses or resumes the HarmonyOS `OH_NativeVSync` frame pump flag.
807    ///
808    /// # Arguments
809    ///
810    /// - `&Self` - Mutable HarmonyOS platform.
811    /// - `bool` - `true` to pause for background freeze.
812    fn set_frame_pump_paused(&mut self, paused: bool) {
813        self.set_pump_paused(paused);
814    }
815
816    /// Returns whether the HarmonyOS frame pump is currently paused.
817    ///
818    /// # Arguments
819    ///
820    /// - `&Self` - HarmonyOS platform reference.
821    ///
822    /// # Returns
823    ///
824    /// - `bool` - Pause state.
825    fn is_frame_pump_paused(&self) -> bool {
826        self.get_pump_paused()
827    }
828
829    /// Presents `framebuffer` to the attached `OHNativeWindow*` buffer or offscreen fallback snapshot.
830    ///
831    /// # Arguments
832    ///
833    /// - `&Self` - Mutable HarmonyOS platform.
834    /// - `WindowId` - Window identifier.
835    /// - `&Framebuffer` - Rendered RGBA8 framebuffer.
836    ///
837    /// # Returns
838    ///
839    /// - `Result<(), PlatformError>` - Presentation status.
840    fn present_framebuffer(
841        &mut self,
842        id: WindowId,
843        framebuffer: &Framebuffer,
844    ) -> Result<(), PlatformError> {
845        let rec: &mut HarmonyWindowRecord = self
846            .get_mut_windows()
847            .get_mut(&id)
848            .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
849        let nw: usize = rec.get_native_window();
850        let mut sw: u32 = rec.get_surface_width();
851        let mut sh: u32 = rec.get_surface_height();
852        let res: Result<(), PlatformError> =
853            harmony_present_native_window(nw, framebuffer, &mut sw, &mut sh);
854        rec.set_surface_width(sw);
855        rec.set_surface_height(sh);
856        rec.set_last_frame(framebuffer.clone());
857        rec.set_present_count(rec.get_present_count().wrapping_add(1));
858        res
859    }
860
861    /// Reads cached HarmonyOS pasteboard text.
862    ///
863    /// # Arguments
864    ///
865    /// - `&Self` - HarmonyOS platform reference.
866    ///
867    /// # Returns
868    ///
869    /// - `Option<String>` - Cached clipboard string.
870    fn read_clipboard(&self) -> Option<String> {
871        let Self { clipboard, .. } = self;
872        clipboard.clone()
873    }
874
875    /// Writes `text` to the HarmonyOS pasteboard cache and native action bridge.
876    ///
877    /// # Arguments
878    ///
879    /// - `&Self` - Mutable HarmonyOS platform.
880    /// - `&str` - Clipboard text.
881    ///
882    /// # Returns
883    ///
884    /// - `Result<(), PlatformError>` - Write status.
885    fn write_clipboard(&mut self, text: &str) -> Result<(), PlatformError> {
886        self.set_clipboard(Some(text.to_string()));
887        let _: bool = write_system_clipboard(text);
888        Ok(())
889    }
890
891    /// Returns the active HarmonyOS appearance mode.
892    ///
893    /// # Arguments
894    ///
895    /// - `&Self` - HarmonyOS platform reference.
896    ///
897    /// # Returns
898    ///
899    /// - `ThemeMode` - Active appearance mode.
900    fn system_theme(&self) -> ThemeMode {
901        self.get_theme()
902    }
903
904    /// Returns the active HarmonyOS hardware display refresh rate in Hertz.
905    ///
906    /// # Arguments
907    ///
908    /// - `&Self` - HarmonyOS platform reference.
909    ///
910    /// # Returns
911    ///
912    /// - `f32` - Active display refresh rate in Hertz.
913    fn display_refresh_rate_hz(&self) -> f32 {
914        self.get_profile().get_refresh_rate_hz()
915    }
916}
917
918/// `PlatformStorage` implementation for `HarmonyPlatform`.
919impl PlatformStorage for HarmonyPlatform {
920    /// Reads a key from HarmonyOS preferences storage.
921    ///
922    /// # Arguments
923    ///
924    /// - `&Self` - HarmonyOS platform reference.
925    /// - `&str` - Storage key.
926    ///
927    /// # Returns
928    ///
929    /// - `Option<String>` - Stored value, if present.
930    fn storage_get(&self, key: &str) -> Option<String> {
931        self.get_storage().get(key).cloned()
932    }
933
934    /// Writes a key-value pair into HarmonyOS preferences storage.
935    ///
936    /// # Arguments
937    ///
938    /// - `&Self` - Mutable HarmonyOS platform.
939    /// - `&str` - Storage key.
940    /// - `&str` - UTF-8 value.
941    ///
942    /// # Returns
943    ///
944    /// - `Result<(), PlatformError>` - Persistence status.
945    fn storage_set(&mut self, key: &str, value: &str) -> Result<(), PlatformError> {
946        let _: Option<String> = self
947            .get_mut_storage()
948            .insert(key.to_string(), value.to_string());
949        Ok(())
950    }
951
952    /// Removes `key` from HarmonyOS preferences storage.
953    ///
954    /// # Arguments
955    ///
956    /// - `&Self` - Mutable HarmonyOS platform.
957    /// - `&str` - Storage key.
958    ///
959    /// # Returns
960    ///
961    /// - `Result<(), PlatformError>` - Removal status.
962    fn storage_remove(&mut self, key: &str) -> Result<(), PlatformError> {
963        let _: Option<String> = self.get_mut_storage().remove(key);
964        Ok(())
965    }
966
967    /// Clears all keys from HarmonyOS preferences storage.
968    ///
969    /// # Arguments
970    ///
971    /// - `&Self` - Mutable HarmonyOS platform.
972    ///
973    /// # Returns
974    ///
975    /// - `Result<(), PlatformError>` - Clear status.
976    fn storage_clear(&mut self) -> Result<(), PlatformError> {
977        self.get_mut_storage().clear();
978        Ok(())
979    }
980}
981
982/// `PlatformNavigation` implementation for `HarmonyPlatform`.
983impl PlatformNavigation for HarmonyPlatform {
984    /// Navigates to `route` on the HarmonyOS UIAbility route stack.
985    ///
986    /// # Arguments
987    ///
988    /// - `&Self` - Mutable HarmonyOS platform.
989    /// - `&str` - Logical route path.
990    ///
991    /// # Returns
992    ///
993    /// - `Result<(), PlatformError>` - Navigation status.
994    fn navigate_to(&mut self, route: &str) -> Result<(), PlatformError> {
995        if !route.is_empty() {
996            self.get_mut_route_stack().push(route.to_string());
997        }
998        Ok(())
999    }
1000
1001    /// Pops `delta` entries from the HarmonyOS route stack.
1002    ///
1003    /// # Arguments
1004    ///
1005    /// - `&Self` - Mutable HarmonyOS platform.
1006    /// - `u32` - Pages to pop.
1007    ///
1008    /// # Returns
1009    ///
1010    /// - `Result<(), PlatformError>` - Navigation status.
1011    fn navigate_back(&mut self, delta: u32) -> Result<(), PlatformError> {
1012        for _ in 0..delta.max(1) {
1013            if self.get_route_stack().len() > 1 {
1014                let _: Option<String> = self.get_mut_route_stack().pop();
1015            }
1016        }
1017        Ok(())
1018    }
1019
1020    /// Returns the active HarmonyOS logical route path.
1021    ///
1022    /// # Arguments
1023    ///
1024    /// - `&Self` - HarmonyOS platform reference.
1025    ///
1026    /// # Returns
1027    ///
1028    /// - `&str` - Active route path.
1029    fn current_route(&self) -> &str {
1030        self.get_route_stack()
1031            .last()
1032            .map(String::as_str)
1033            .unwrap_or(HARMONY_DEFAULT_ROUTE)
1034    }
1035}
1036
1037/// `PlatformLifecycleBridge` implementation for `HarmonyPlatform`.
1038impl PlatformLifecycleBridge for HarmonyPlatform {
1039    /// Maps HarmonyOS `onBackground` into unified freeze semantics.
1040    ///
1041    /// # Arguments
1042    ///
1043    /// - `&Self` - Mutable HarmonyOS platform.
1044    ///
1045    /// # Returns
1046    ///
1047    /// - `Vec<WindowEvent>` - Normalized freeze events.
1048    fn freeze_surface(&mut self) -> Vec<WindowEvent> {
1049        self.handle_lifecycle_hook(HarmonyLifecycleHook::OnBackground)
1050    }
1051
1052    /// Maps HarmonyOS `onForeground` into unified resume semantics.
1053    ///
1054    /// # Arguments
1055    ///
1056    /// - `&Self` - Mutable HarmonyOS platform.
1057    ///
1058    /// # Returns
1059    ///
1060    /// - `Vec<WindowEvent>` - Normalized resume events.
1061    fn resume_surface(&mut self) -> Vec<WindowEvent> {
1062        self.handle_lifecycle_hook(HarmonyLifecycleHook::OnForeground)
1063    }
1064
1065    /// Maps HarmonyOS `onDestroy` into unified destroy semantics.
1066    ///
1067    /// # Arguments
1068    ///
1069    /// - `&Self` - Mutable HarmonyOS platform.
1070    ///
1071    /// # Returns
1072    ///
1073    /// - `Vec<WindowEvent>` - Normalized teardown events.
1074    fn destroy_surface(&mut self) -> Vec<WindowEvent> {
1075        self.handle_lifecycle_hook(HarmonyLifecycleHook::OnDestroy)
1076    }
1077}
1078
1079/// `PlatformHostAdapter` implementation for `HarmonyPlatform`.
1080impl PlatformHostAdapter for HarmonyPlatform {
1081    /// Returns the concrete `DeviceFormFactor` matching this HarmonyOS device category.
1082    ///
1083    /// # Arguments
1084    ///
1085    /// - `&Self` - HarmonyOS platform reference.
1086    ///
1087    /// # Returns
1088    ///
1089    /// - `DeviceFormFactor` - Active HarmonyOS form factor.
1090    fn device_form_factor(&self) -> DeviceFormFactor {
1091        self.get_profile().get_device_type().form_factor()
1092    }
1093
1094    /// Returns the canonical HarmonyOS device type string (`"phone"`, `"tablet"`, `"2in1"`, `"foldable"`, `"wearable"`, `"tv"`, `"car"`).
1095    ///
1096    /// # Arguments
1097    ///
1098    /// - `&Self` - HarmonyOS platform reference.
1099    ///
1100    /// # Returns
1101    ///
1102    /// - `&'static str` - Canonical HarmonyOS device identifier.
1103    fn host_vendor_name(&self) -> &'static str {
1104        self.get_profile().get_device_type().as_str()
1105    }
1106}