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