Skip to main content

euv_core/platform/wearable/
impl.rs

1use super::*;
2
3/// Canonical identifier and discriminant helpers for `WearableVendor`.
4impl WearableVendor {
5    /// Returns the canonical lowercase vendor string identifier.
6    ///
7    /// # Arguments
8    ///
9    /// - `&Self` - Wearable vendor variant.
10    ///
11    /// # Returns
12    ///
13    /// - `&'static str` - Vendor identifier string.
14    #[must_use]
15    pub const fn as_str(&self) -> &'static str {
16        match *self {
17            Self::WearOs => WEARABLE_VENDOR_WEAR_OS,
18            Self::WatchOs => WEARABLE_VENDOR_WATCH_OS,
19            Self::HarmonyWatch => WEARABLE_VENDOR_HARMONY_WATCH,
20            Self::HyperOsVela => WEARABLE_VENDOR_HYPEROS_VELA,
21            Self::OppoColorOsWatch => WEARABLE_VENDOR_OPPO_WATCH,
22            Self::VivoBlueOsWatch => WEARABLE_VENDOR_VIVO_WATCH,
23            Self::GarminConnectIq => WEARABLE_VENDOR_GARMIN,
24            Self::AmazfitZeppOs => WEARABLE_VENDOR_ZEPP_OS,
25            Self::GenericWearable => WEARABLE_VENDOR_GENERIC,
26        }
27    }
28
29    /// Parses a canonical wearable vendor identifier or ecosystem alias into a `WearableVendor`.
30    ///
31    /// # Arguments
32    ///
33    /// - `&str` - Wearable vendor identifier or alias (case-insensitive).
34    ///
35    /// # Returns
36    ///
37    /// - `Option<Self>` - Matching `WearableVendor`, if recognized.
38    #[must_use]
39    pub fn from_str_id(name: &str) -> Option<Self> {
40        let lower: String = name.trim().to_ascii_lowercase();
41        match lower.as_str() {
42            WEARABLE_VENDOR_WEAR_OS => Some(Self::WearOs),
43            WEARABLE_VENDOR_WATCH_OS => Some(Self::WatchOs),
44            WEARABLE_VENDOR_HARMONY_WATCH | WEARABLE_ALIAS_HARMONY_WEARABLE => {
45                Some(Self::HarmonyWatch)
46            }
47            WEARABLE_VENDOR_HYPEROS_VELA | WEARABLE_ALIAS_VELA => Some(Self::HyperOsVela),
48            WEARABLE_VENDOR_OPPO_WATCH | WEARABLE_ALIAS_OPPO | WEARABLE_ALIAS_COLOROS_WATCH => {
49                Some(Self::OppoColorOsWatch)
50            }
51            WEARABLE_VENDOR_VIVO_WATCH
52            | WEARABLE_ALIAS_VIVO
53            | WEARABLE_ALIAS_BLUEOS
54            | WEARABLE_ALIAS_BLUEOS_WATCH
55            | WEARABLE_ALIAS_VIVO_BLUEOS => Some(Self::VivoBlueOsWatch),
56            WEARABLE_VENDOR_GARMIN => Some(Self::GarminConnectIq),
57            WEARABLE_VENDOR_ZEPP_OS | WEARABLE_ALIAS_AMAZFIT => Some(Self::AmazfitZeppOs),
58            WEARABLE_VENDOR_GENERIC | WEARABLE_ALIAS_GENERIC => Some(Self::GenericWearable),
59            _ => None,
60        }
61    }
62
63    /// Returns the target runtime and host ecosystem description for this smartwatch vendor.
64    ///
65    /// # Arguments
66    ///
67    /// - `&Self` - Wearable vendor variant.
68    ///
69    /// # Returns
70    ///
71    /// - `&'static str` - Runtime ecosystem descriptor string.
72    #[must_use]
73    pub const fn runtime_ecosystem(&self) -> &'static str {
74        match *self {
75            Self::WearOs => WEARABLE_RUNTIME_WEAR_OS,
76            Self::WatchOs => WEARABLE_RUNTIME_WATCH_OS,
77            Self::HarmonyWatch => WEARABLE_RUNTIME_HARMONY_WATCH,
78            Self::HyperOsVela => WEARABLE_RUNTIME_HYPEROS_VELA,
79            Self::OppoColorOsWatch => WEARABLE_RUNTIME_OPPO_WATCH,
80            Self::VivoBlueOsWatch => WEARABLE_RUNTIME_VIVO_WATCH,
81            Self::GarminConnectIq => WEARABLE_RUNTIME_GARMIN,
82            Self::AmazfitZeppOs => WEARABLE_RUNTIME_ZEPP_OS,
83            Self::GenericWearable => WEARABLE_RUNTIME_GENERIC,
84        }
85    }
86
87    /// Returns a compact ABI tag byte identifying this vendor inside `RawWindowHandle::WearableSurface`.
88    ///
89    /// # Arguments
90    ///
91    /// - `&Self` - Wearable vendor variant.
92    ///
93    /// # Returns
94    ///
95    /// - `u8` - Stable numeric vendor tag.
96    #[must_use]
97    pub const fn tag(&self) -> u8 {
98        match *self {
99            Self::WearOs => 1,
100            Self::WatchOs => 2,
101            Self::HarmonyWatch => 3,
102            Self::HyperOsVela => 4,
103            Self::OppoColorOsWatch => 5,
104            Self::VivoBlueOsWatch => 6,
105            Self::GarminConnectIq => 7,
106            Self::AmazfitZeppOs => 8,
107            Self::GenericWearable => 9,
108        }
109    }
110
111    /// Returns all supported smartwatch vendor adapters.
112    ///
113    /// # Returns
114    ///
115    /// - `[Self; 9]` - Complete array of wearable vendor variants.
116    #[must_use]
117    pub const fn all_vendors() -> [Self; 9] {
118        [
119            Self::WearOs,
120            Self::WatchOs,
121            Self::HarmonyWatch,
122            Self::HyperOsVela,
123            Self::OppoColorOsWatch,
124            Self::VivoBlueOsWatch,
125            Self::GarminConnectIq,
126            Self::AmazfitZeppOs,
127            Self::GenericWearable,
128        ]
129    }
130}
131
132/// Hardware preset factory and geometry helpers for `WearableProfile`.
133impl WearableProfile {
134    /// Returns a realistic canonical display and hardware profile preset for `vendor`.
135    ///
136    /// # Arguments
137    ///
138    /// - `WearableVendor` - Target smartwatch vendor ecosystem.
139    ///
140    /// # Returns
141    ///
142    /// - `Self` - Preconfigured wearable hardware profile.
143    #[must_use]
144    pub const fn for_vendor(vendor: WearableVendor) -> Self {
145        match vendor {
146            WearableVendor::WearOs => Self {
147                vendor,
148                shape: WearableShape::Round,
149                logical_width: 227,
150                logical_height: 227,
151                scale_factor: 2.0,
152                chin_height_dp: 0.0,
153                refresh_rate_hz: WEARABLE_INTERACTIVE_REFRESH_HZ,
154                has_rotary_crown: true,
155                supports_aod: true,
156            },
157            WearableVendor::WatchOs => Self {
158                vendor,
159                shape: WearableShape::Squircle,
160                logical_width: 205,
161                logical_height: 251,
162                scale_factor: 2.0,
163                chin_height_dp: 0.0,
164                refresh_rate_hz: WEARABLE_INTERACTIVE_REFRESH_HZ,
165                has_rotary_crown: true,
166                supports_aod: true,
167            },
168            WearableVendor::HarmonyWatch => Self {
169                vendor,
170                shape: WearableShape::Round,
171                logical_width: 233,
172                logical_height: 233,
173                scale_factor: 2.0,
174                chin_height_dp: 0.0,
175                refresh_rate_hz: WEARABLE_INTERACTIVE_REFRESH_HZ,
176                has_rotary_crown: true,
177                supports_aod: true,
178            },
179            WearableVendor::HyperOsVela => Self {
180                vendor,
181                shape: WearableShape::Round,
182                logical_width: 233,
183                logical_height: 233,
184                scale_factor: 2.0,
185                chin_height_dp: 0.0,
186                refresh_rate_hz: WEARABLE_INTERACTIVE_REFRESH_HZ,
187                has_rotary_crown: true,
188                supports_aod: true,
189            },
190            WearableVendor::OppoColorOsWatch => Self {
191                vendor,
192                shape: WearableShape::Squircle,
193                logical_width: 201,
194                logical_height: 238,
195                scale_factor: 2.0,
196                chin_height_dp: 0.0,
197                refresh_rate_hz: WEARABLE_INTERACTIVE_REFRESH_HZ,
198                has_rotary_crown: true,
199                supports_aod: true,
200            },
201            WearableVendor::VivoBlueOsWatch => Self::vivo_watch_round(),
202            WearableVendor::GarminConnectIq => Self {
203                vendor,
204                shape: WearableShape::Round,
205                logical_width: 208,
206                logical_height: 208,
207                scale_factor: 2.0,
208                chin_height_dp: 0.0,
209                refresh_rate_hz: 30.0,
210                has_rotary_crown: false,
211                supports_aod: true,
212            },
213            WearableVendor::AmazfitZeppOs => Self {
214                vendor,
215                shape: WearableShape::Round,
216                logical_width: 240,
217                logical_height: 240,
218                scale_factor: 2.0,
219                chin_height_dp: 0.0,
220                refresh_rate_hz: WEARABLE_INTERACTIVE_REFRESH_HZ,
221                has_rotary_crown: true,
222                supports_aod: true,
223            },
224            WearableVendor::GenericWearable => Self {
225                vendor,
226                shape: WearableShape::Rectangular,
227                logical_width: 184,
228                logical_height: 224,
229                scale_factor: 2.0,
230                chin_height_dp: 0.0,
231                refresh_rate_hz: WEARABLE_INTERACTIVE_REFRESH_HZ,
232                has_rotary_crown: false,
233                supports_aod: true,
234            },
235        }
236    }
237
238    /// Returns the hardware display profile for circular vivo BlueOS Watch models (vivo Watch 3 / 5, 466x466px @ 2.0x).
239    ///
240    /// # Returns
241    ///
242    /// - `Self` - Preconfigured circular vivo BlueOS Watch profile.
243    #[must_use]
244    pub const fn vivo_watch_round() -> Self {
245        Self {
246            vendor: WearableVendor::VivoBlueOsWatch,
247            shape: WearableShape::Round,
248            logical_width: 233,
249            logical_height: 233,
250            scale_factor: 2.0,
251            chin_height_dp: 0.0,
252            refresh_rate_hz: WEARABLE_INTERACTIVE_REFRESH_HZ,
253            has_rotary_crown: true,
254            supports_aod: true,
255        }
256    }
257
258    /// Returns the hardware display profile for squircle vivo BlueOS Watch GT models (390x450px @ 2.0x).
259    ///
260    /// # Returns
261    ///
262    /// - `Self` - Preconfigured squircle vivo BlueOS Watch GT profile.
263    #[must_use]
264    pub const fn vivo_watch_gt() -> Self {
265        Self {
266            vendor: WearableVendor::VivoBlueOsWatch,
267            shape: WearableShape::Squircle,
268            logical_width: 195,
269            logical_height: 225,
270            scale_factor: 2.0,
271            chin_height_dp: 0.0,
272            refresh_rate_hz: WEARABLE_INTERACTIVE_REFRESH_HZ,
273            has_rotary_crown: true,
274            supports_aod: true,
275        }
276    }
277
278    /// Computes inscribed safe-area insets for this wearable display profile.
279    ///
280    /// # Arguments
281    ///
282    /// - `&Self` - Wearable profile reference.
283    ///
284    /// # Returns
285    ///
286    /// - `SafeAreaInsets` - Shape-aware safe-area insets in logical dp.
287    #[must_use]
288    pub fn safe_area_insets(&self) -> SafeAreaInsets {
289        compute_wearable_safe_area(
290            self.get_shape(),
291            self.get_logical_width() as f32,
292            self.get_logical_height() as f32,
293            self.get_chin_height_dp(),
294        )
295    }
296
297    /// Computes compact viewport UI scale for this wearable display profile.
298    ///
299    /// # Arguments
300    ///
301    /// - `&Self` - Wearable profile reference.
302    ///
303    /// # Returns
304    ///
305    /// - `f32` - Compact viewport scaling multiplier.
306    #[must_use]
307    pub fn compact_scale(&self) -> f32 {
308        compute_wearable_compact_scale(
309            self.get_logical_width() as f32,
310            self.get_logical_height() as f32,
311        )
312    }
313}
314
315/// Default `WearablePlatform` configured for `WearableVendor::WearOs`.
316impl Default for WearablePlatform {
317    /// Creates a default Wear OS circular smartwatch platform backend.
318    ///
319    /// # Returns
320    ///
321    /// - `Self` - Default wearable platform backend.
322    fn default() -> Self {
323        Self::for_vendor(WearableVendor::WearOs)
324    }
325}
326
327/// Vendor constructors, rotary crown translation, AOD lifecycle, and wrist/palm gesture handling for `WearablePlatform`.
328impl WearablePlatform {
329    /// Creates a `WearablePlatform` using the canonical display and hardware profile for `vendor`.
330    ///
331    /// # Arguments
332    ///
333    /// - `WearableVendor` - Target smartwatch vendor ecosystem.
334    ///
335    /// # Returns
336    ///
337    /// - `Self` - Configured wearable platform backend.
338    #[must_use]
339    pub fn for_vendor(vendor: WearableVendor) -> Self {
340        Self::from_profile(WearableProfile::for_vendor(vendor))
341    }
342
343    /// Creates a `WearablePlatform` preconfigured for vivo BlueOS Watch (466x466 round dial).
344    ///
345    /// # Returns
346    ///
347    /// - `Self` - Configured vivo BlueOS Watch platform backend.
348    #[must_use]
349    pub fn vivo_blueos() -> Self {
350        Self::from_profile(WearableProfile::vivo_watch_round())
351    }
352
353    /// Creates a `WearablePlatform` from a custom `WearableProfile`.
354    ///
355    /// # Arguments
356    ///
357    /// - `WearableProfile` - Custom smartwatch display and input profile.
358    ///
359    /// # Returns
360    ///
361    /// - `Self` - Configured wearable platform backend.
362    #[must_use]
363    pub fn from_profile(profile: WearableProfile) -> Self {
364        let safe_area: SafeAreaInsets = profile.safe_area_insets();
365        let compact_scale: f32 = profile.compact_scale();
366        Self {
367            profile,
368            ambient_mode: WearableAmbientMode::Interactive,
369            compact_scale,
370            safe_area,
371            crown_accumulator: 0.0,
372            crown_scroll_step: WEARABLE_CROWN_PIXELS_PER_DETENT,
373            next_id: 1,
374            primary_window: None,
375            windows: HashMap::new(),
376            touch_tracker: TouchPointerTracker::default(),
377            pending_events: Vec::new(),
378            storage: HashMap::new(),
379            route_stack: vec![WEARABLE_DEFAULT_ROUTE.to_string()],
380            theme: ThemeMode::Dark,
381            pump_paused: false,
382            haptic_detent_count: 0,
383            capture_last_frame: false,
384        }
385    }
386
387    /// Enables or disables retaining a cloned snapshot of the last presented framebuffer.
388    ///
389    /// # Arguments
390    ///
391    /// - `bool` - `true` to capture snapshots on each present; `false` for zero-clone production mode.
392    ///
393    /// # Returns
394    ///
395    /// - `Self` - Updated wearable platform backend.
396    #[must_use]
397    pub fn with_capture_last_frame(mut self, enabled: bool) -> Self {
398        self.set_capture_last_frame(enabled);
399        self
400    }
401
402    /// Returns the last presented framebuffer snapshot for `id` when `capture_last_frame` is enabled.
403    ///
404    /// # Arguments
405    ///
406    /// - `WindowId` - Watch window identifier.
407    ///
408    /// # Returns
409    ///
410    /// - `Option<&Framebuffer>` - Cloned framebuffer reference when capture is enabled and `id` exists.
411    #[must_use]
412    pub fn last_framebuffer(&self, id: WindowId) -> Option<&Framebuffer> {
413        if !self.get_capture_last_frame() {
414            return None;
415        }
416        self.get_windows()
417            .get(&id)
418            .map(WearableWindowRecord::get_last_frame)
419    }
420
421    /// Returns the primary watch window identifier, if created.
422    ///
423    /// # Arguments
424    ///
425    /// - `&Self` - Wearable platform reference.
426    ///
427    /// # Returns
428    ///
429    /// - `Option<WindowId>` - Primary watch window handle.
430    #[must_use]
431    pub fn primary_window_id(&self) -> Option<WindowId> {
432        let Self { primary_window, .. } = self;
433        *primary_window
434    }
435
436    /// Translates a rotary crown or rotating bezel rotation event into standard EUV scroll or focus `WindowEvent`s.
437    ///
438    /// # Arguments
439    ///
440    /// - `&Self` - Mutable wearable platform.
441    /// - `WearableCrownInput` - Raw vendor crown/bezel detent delta and mode.
442    ///
443    /// # Returns
444    ///
445    /// - `Vec<WindowEvent>` - Normalized standard EUV events also enqueued for `poll_events()`.
446    pub fn handle_crown_input(&mut self, input: WearableCrownInput) -> Vec<WindowEvent> {
447        let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
448        if !input.get_detents().is_finite() || input.get_detents().abs() < 1e-5 {
449            return Vec::new();
450        }
451        let mut emitted: Vec<WindowEvent> = Vec::new();
452        match input.get_mode() {
453            WearableCrownMode::Scroll => {
454                let dy: f32 = input.get_detents() * self.get_crown_scroll_step();
455                emitted.push(WindowEvent::Scroll(wid, Point::new(0.0, dy)));
456            }
457            WearableCrownMode::FocusStep => {
458                let prev: f32 = self.get_crown_accumulator();
459                let base: f32 = if prev * input.get_detents() < 0.0 {
460                    0.0
461                } else {
462                    prev
463                };
464                let total: f32 = base + input.get_detents();
465                let whole: i32 = total.trunc() as i32;
466                self.set_crown_accumulator(total - (whole as f32));
467                let forward: bool = whole > 0;
468                let steps: usize = whole.unsigned_abs().min(16) as usize;
469                let mods: Modifiers = Modifiers::new(!forward, false, false, false);
470                for _ in 0..steps {
471                    emitted.push(WindowEvent::KeyDown(
472                        wid,
473                        KeyEvent::new(KeyCode::Tab, mods, false),
474                    ));
475                    emitted.push(WindowEvent::KeyUp(
476                        wid,
477                        KeyEvent::new(KeyCode::Tab, mods, false),
478                    ));
479                }
480            }
481            WearableCrownMode::DirectionalStep => {
482                let prev: f32 = self.get_crown_accumulator();
483                let base: f32 = if prev * input.get_detents() < 0.0 {
484                    0.0
485                } else {
486                    prev
487                };
488                let total: f32 = base + input.get_detents();
489                let whole: i32 = total.trunc() as i32;
490                self.set_crown_accumulator(total - (whole as f32));
491                let code: KeyCode = if whole > 0 {
492                    KeyCode::ArrowDown
493                } else {
494                    KeyCode::ArrowUp
495                };
496                let steps: usize = whole.unsigned_abs().min(16) as usize;
497                for _ in 0..steps {
498                    emitted.push(WindowEvent::KeyDown(
499                        wid,
500                        KeyEvent::new(code, Modifiers::default(), false),
501                    ));
502                    emitted.push(WindowEvent::KeyUp(
503                        wid,
504                        KeyEvent::new(code, Modifiers::default(), false),
505                    ));
506                }
507            }
508        }
509        if input.get_haptic_detent() && !emitted.is_empty() {
510            let next_h: u64 = self.get_haptic_detent_count().saturating_add(1);
511            self.set_haptic_detent_count(next_h);
512        }
513        self.get_mut_pending_events().extend(emitted.clone());
514        emitted
515    }
516
517    /// Transitions the watch into low-power Always-On Display (AOD) ambient mode, freezing interactive pumping.
518    ///
519    /// # Arguments
520    ///
521    /// - `&Self` - Mutable wearable platform.
522    ///
523    /// # Returns
524    ///
525    /// - `Vec<WindowEvent>` - Normalized ambient transition events.
526    pub fn enter_ambient(&mut self) -> Vec<WindowEvent> {
527        if !self.get_profile().get_supports_aod() {
528            return self.enter_screen_off();
529        }
530        let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
531        self.set_ambient_mode(WearableAmbientMode::AlwaysOnAmbient);
532        self.set_pump_paused(true);
533        let mut events: Vec<WindowEvent> =
534            self.get_mut_touch_tracker().cancel_all_on_focus_loss(wid);
535        events.push(WindowEvent::System(SystemEvent::LowPowerModeChanged(true)));
536        events.push(WindowEvent::System(SystemEvent::Inactive));
537        self.get_mut_pending_events().extend(events.clone());
538        events
539    }
540
541    /// Delivers a single low-power 1Hz AOD ambient redraw pulse while remaining in `AlwaysOnAmbient` mode.
542    ///
543    /// # Arguments
544    ///
545    /// - `&Self` - Mutable wearable platform.
546    ///
547    /// # Returns
548    ///
549    /// - `Option<WindowEvent>` - `RedrawRequested` event when currently in `AlwaysOnAmbient` mode.
550    pub fn pulse_ambient_tick(&mut self) -> Option<WindowEvent> {
551        if self.get_ambient_mode() != WearableAmbientMode::AlwaysOnAmbient {
552            return None;
553        }
554        let wid: WindowId = self.primary_window_id()?;
555        if let Some(rec) = self.get_mut_windows().get_mut(&wid) {
556            rec.set_ambient_tick_count(rec.get_ambient_tick_count().saturating_add(1));
557        }
558        let ev: WindowEvent = WindowEvent::RedrawRequested(wid);
559        self.get_mut_pending_events().push(ev.clone());
560        Some(ev)
561    }
562
563    /// Transitions the watch into full `ScreenOff` background freeze (0% CPU/GPU).
564    ///
565    /// # Arguments
566    ///
567    /// - `&Self` - Mutable wearable platform.
568    ///
569    /// # Returns
570    ///
571    /// - `Vec<WindowEvent>` - Normalized background freeze events.
572    pub fn enter_screen_off(&mut self) -> Vec<WindowEvent> {
573        let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
574        self.set_ambient_mode(WearableAmbientMode::ScreenOff);
575        self.set_pump_paused(true);
576        let mut events: Vec<WindowEvent> =
577            self.get_mut_touch_tracker().cancel_all_on_focus_loss(wid);
578        events.push(WindowEvent::System(SystemEvent::Disappear));
579        events.push(WindowEvent::System(SystemEvent::Background));
580        self.get_mut_pending_events().extend(events.clone());
581        events
582    }
583
584    /// Wakes the watch from `AlwaysOnAmbient` or `ScreenOff` back into full interactive mode.
585    ///
586    /// # Arguments
587    ///
588    /// - `&Self` - Mutable wearable platform.
589    ///
590    /// # Returns
591    ///
592    /// - `Vec<WindowEvent>` - Normalized interactive resume events.
593    pub fn exit_ambient(&mut self) -> Vec<WindowEvent> {
594        self.set_ambient_mode(WearableAmbientMode::Interactive);
595        self.set_pump_paused(false);
596        let events: Vec<WindowEvent> = vec![
597            WindowEvent::System(SystemEvent::LowPowerModeChanged(false)),
598            WindowEvent::System(SystemEvent::Appear),
599            WindowEvent::System(SystemEvent::Foreground),
600        ];
601        self.get_mut_pending_events().extend(events.clone());
602        events
603    }
604
605    /// Translates physical wrist, palm-cover, double-pinch, and side-button hardware gestures into standard EUV events.
606    ///
607    /// # Arguments
608    ///
609    /// - `&Self` - Mutable wearable platform.
610    /// - `WearableHardwareGesture` - Hardware gesture detected by the watch OS.
611    ///
612    /// # Returns
613    ///
614    /// - `Vec<WindowEvent>` - Normalized standard EUV window/system events.
615    pub fn handle_hardware_gesture(
616        &mut self,
617        gesture: WearableHardwareGesture,
618    ) -> Vec<WindowEvent> {
619        let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
620        match gesture {
621            WearableHardwareGesture::WristRaise => self.exit_ambient(),
622            WearableHardwareGesture::WristLower => {
623                if self.get_profile().get_supports_aod() {
624                    self.enter_ambient()
625                } else {
626                    self.enter_screen_off()
627                }
628            }
629            WearableHardwareGesture::PalmCover => self.enter_screen_off(),
630            WearableHardwareGesture::DoublePinch => {
631                let events: Vec<WindowEvent> = vec![
632                    WindowEvent::KeyDown(
633                        wid,
634                        KeyEvent::new(KeyCode::Enter, Modifiers::default(), false),
635                    ),
636                    WindowEvent::KeyUp(
637                        wid,
638                        KeyEvent::new(KeyCode::Enter, Modifiers::default(), false),
639                    ),
640                ];
641                self.get_mut_pending_events().extend(events.clone());
642                events
643            }
644            WearableHardwareGesture::SideButtonPress => {
645                let events: Vec<WindowEvent> = vec![
646                    WindowEvent::KeyDown(
647                        wid,
648                        KeyEvent::new(KeyCode::Back, Modifiers::default(), false),
649                    ),
650                    WindowEvent::System(SystemEvent::BackPressed),
651                ];
652                self.get_mut_pending_events().extend(events.clone());
653                events
654            }
655            WearableHardwareGesture::SideButtonLongPress => {
656                let events: Vec<WindowEvent> = vec![WindowEvent::System(SystemEvent::Inactive)];
657                self.get_mut_pending_events().extend(events.clone());
658                events
659            }
660        }
661    }
662}
663
664/// `WindowController` implementation for `WearablePlatform`.
665impl WindowController for WearablePlatform {
666    /// Applies a `WindowCommand` against the smartwatch window record.
667    ///
668    /// # Arguments
669    ///
670    /// - `&Self` - Mutable wearable platform.
671    /// - `WindowCommand` - Command to execute.
672    ///
673    /// # Returns
674    ///
675    /// - `Result<(), PlatformError>` - Execution status.
676    fn apply_command(&mut self, command: WindowCommand) -> Result<(), PlatformError> {
677        match command {
678            WindowCommand::SetTitle(id, title) => {
679                let rec: &mut WearableWindowRecord = self
680                    .get_mut_windows()
681                    .get_mut(&id)
682                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
683                rec.get_mut_config().set_title(title);
684                Ok(())
685            }
686            WindowCommand::SetSize(id, width, height) => {
687                let shape: WearableShape = self.get_profile().get_shape();
688                let chin: f32 = self.get_profile().get_chin_height_dp();
689                let safe: SafeAreaInsets = compute_wearable_safe_area(
690                    shape,
691                    width.max(1) as f32,
692                    height.max(1) as f32,
693                    chin,
694                );
695                let compact: f32 =
696                    compute_wearable_compact_scale(width.max(1) as f32, height.max(1) as f32);
697                self.set_safe_area(safe);
698                self.set_compact_scale(compact);
699                let scale: f32 = {
700                    let rec: &mut WearableWindowRecord = self
701                        .get_mut_windows()
702                        .get_mut(&id)
703                        .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
704                    let s: f32 = rec.get_state().get_scale_factor();
705                    rec.get_mut_config().set_size(width.max(1), height.max(1));
706                    rec.get_mut_state()
707                        .set_logical_width(width.max(1) as f32)
708                        .set_logical_height(height.max(1) as f32)
709                        .set_physical_width(((width.max(1) as f32) * s).round() as u32)
710                        .set_physical_height(((height.max(1) as f32) * s).round() as u32)
711                        .set_safe_area(safe);
712                    s
713                };
714                self.get_mut_pending_events().push(WindowEvent::Resized(
715                    id,
716                    width.max(1),
717                    height.max(1),
718                    scale,
719                ));
720                self.get_mut_pending_events()
721                    .push(WindowEvent::SafeAreaChanged(id, safe));
722                Ok(())
723            }
724            WindowCommand::SetRenderMode(id, mode) => {
725                let rec: &mut WearableWindowRecord = self
726                    .get_mut_windows()
727                    .get_mut(&id)
728                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
729                rec.get_mut_config().get_mut_render().set_mode(mode);
730                Ok(())
731            }
732            WindowCommand::RequestRedraw(id) => {
733                if !self.get_windows().contains_key(&id) {
734                    return Err(PlatformError::WindowNotFound(id.get_value()));
735                }
736                self.get_mut_pending_events()
737                    .push(WindowEvent::RedrawRequested(id));
738                Ok(())
739            }
740            WindowCommand::Close(id) => {
741                if self.get_mut_windows().remove(&id).is_none() {
742                    return Err(PlatformError::WindowNotFound(id.get_value()));
743                }
744                Ok(())
745            }
746            WindowCommand::SetPosition(id, _, _)
747            | WindowCommand::SetResizable(id, _)
748            | WindowCommand::SetDecorations(id, _)
749            | WindowCommand::SetAlwaysOnTop(id, _)
750            | WindowCommand::SetFullscreen(id, _)
751            | WindowCommand::SetVisible(id, _)
752            | WindowCommand::SetCursor(id, _)
753            | WindowCommand::SetIme(id, _, _)
754            | WindowCommand::SetStatusBarStyle(id, _) => {
755                if !self.get_windows().contains_key(&id) {
756                    return Err(PlatformError::WindowNotFound(id.get_value()));
757                }
758                Ok(())
759            }
760        }
761    }
762}
763
764/// `PlatformBackend` implementation for `WearablePlatform`.
765impl PlatformBackend for WearablePlatform {
766    /// Returns `PlatformKind::Wearable`.
767    ///
768    /// # Arguments
769    ///
770    /// - `&Self` - Wearable platform reference.
771    ///
772    /// # Returns
773    ///
774    /// - `PlatformKind` - `PlatformKind::Wearable`.
775    fn kind(&self) -> PlatformKind {
776        PlatformKind::Wearable
777    }
778
779    /// Returns smartwatch capabilities refined by the active hardware profile.
780    ///
781    /// # Arguments
782    ///
783    /// - `&Self` - Wearable platform reference.
784    ///
785    /// # Returns
786    ///
787    /// - `PlatformCapabilities` - Wearable capability flags.
788    fn capabilities(&self) -> PlatformCapabilities {
789        let mut caps: PlatformCapabilities =
790            PlatformCapabilities::for_platform(PlatformKind::Wearable);
791        caps.rotary_input = self.get_profile().get_has_rotary_crown();
792        caps.always_on_display = self.get_profile().get_supports_aod();
793        caps
794    }
795
796    /// Creates a watch surface window with automatic round/squircle inscribed safe-area insets.
797    ///
798    /// # Arguments
799    ///
800    /// - `&Self` - Mutable wearable platform.
801    /// - `&WindowConfig` - Declarative window configuration.
802    ///
803    /// # Returns
804    ///
805    /// - `Result<WindowState, PlatformError>` - Initialized watch window state.
806    fn create_window(&mut self, config: &WindowConfig) -> Result<WindowState, PlatformError> {
807        let id: WindowId = WindowId::new(self.get_next_id());
808        self.set_next_id(self.get_next_id().wrapping_add(1));
809        let profile: WearableProfile = self.get_profile();
810        let mut watch_cfg: WindowConfig = config.clone();
811        watch_cfg.set_size(profile.get_logical_width(), profile.get_logical_height());
812        let mut state: WindowState =
813            WindowState::from_config(id, &watch_cfg, profile.get_scale_factor());
814        state.set_safe_area(self.get_safe_area());
815        state.set_system_theme(self.get_theme());
816        state
817            .get_mut_display()
818            .set_refresh_rate_hz(profile.get_refresh_rate_hz().round() as u32);
819        let record: WearableWindowRecord = WearableWindowRecord {
820            config: watch_cfg,
821            state,
822            native_surface: 0,
823            last_frame: Framebuffer::allocate(1, 1),
824            present_count: 0,
825            ambient_tick_count: 0,
826        };
827        self.get_mut_windows().insert(id, record);
828        if self.primary_window_id().is_none() {
829            self.set_primary_window(Some(id));
830        }
831        Ok(state)
832    }
833
834    /// Queries live `WindowState` for `id`.
835    ///
836    /// # Arguments
837    ///
838    /// - `&Self` - Wearable platform reference.
839    /// - `WindowId` - Window identifier.
840    ///
841    /// # Returns
842    ///
843    /// - `Option<WindowState>` - Window state if alive.
844    fn window_state(&self, id: WindowId) -> Option<WindowState> {
845        self.get_windows()
846            .get(&id)
847            .map(WearableWindowRecord::get_state)
848    }
849
850    /// Returns `RawWindowHandle::WearableSurface` tagged with the active `WearableVendor`.
851    ///
852    /// # Arguments
853    ///
854    /// - `&Self` - Wearable platform reference.
855    /// - `WindowId` - Window identifier.
856    ///
857    /// # Returns
858    ///
859    /// - `RawWindowHandle` - Wearable surface handle.
860    fn raw_window_handle(&self, id: WindowId) -> RawWindowHandle {
861        match self.get_windows().get(&id) {
862            Some(rec) => RawWindowHandle::WearableSurface {
863                native_handle: rec.get_native_surface(),
864                vendor_tag: self.get_profile().get_vendor().tag(),
865            },
866            None => RawWindowHandle::Headless,
867        }
868    }
869
870    /// Drains queued wearable input, rotary crown, gesture, and AOD lifecycle events.
871    ///
872    /// # Arguments
873    ///
874    /// - `&Self` - Mutable wearable platform.
875    ///
876    /// # Returns
877    ///
878    /// - `Vec<WindowEvent>` - Pending events.
879    fn poll_events(&mut self) -> Vec<WindowEvent> {
880        take(self.get_mut_pending_events())
881    }
882
883    /// Updates frame pump pause state for AOD / screen-off freeze.
884    ///
885    /// # Arguments
886    ///
887    /// - `&Self` - Mutable wearable platform.
888    /// - `bool` - `true` to pause frame pumping.
889    fn set_frame_pump_paused(&mut self, paused: bool) {
890        self.set_pump_paused(paused);
891    }
892
893    /// Returns whether the watch frame pump is paused.
894    ///
895    /// # Arguments
896    ///
897    /// - `&Self` - Wearable platform reference.
898    ///
899    /// # Returns
900    ///
901    /// - `bool` - Pause state.
902    fn is_frame_pump_paused(&self) -> bool {
903        self.get_pump_paused()
904    }
905
906    /// Presents `framebuffer` to the active watch window record.
907    ///
908    /// # Arguments
909    ///
910    /// - `&Self` - Mutable wearable platform.
911    /// - `WindowId` - Target window handle.
912    /// - `&Framebuffer` - Rendered RGBA8 framebuffer.
913    ///
914    /// # Returns
915    ///
916    /// - `Result<(), PlatformError>` - Presentation status.
917    fn present_framebuffer(
918        &mut self,
919        id: WindowId,
920        framebuffer: &Framebuffer,
921    ) -> Result<(), PlatformError> {
922        let capture: bool = self.get_capture_last_frame();
923        let rec: &mut WearableWindowRecord = self
924            .get_mut_windows()
925            .get_mut(&id)
926            .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
927        if capture {
928            rec.set_last_frame(framebuffer.clone());
929        }
930        rec.set_present_count(rec.get_present_count().wrapping_add(1));
931        Ok(())
932    }
933
934    /// Returns `None` because smartwatches do not expose a system clipboard.
935    ///
936    /// # Arguments
937    ///
938    /// - `&Self` - Wearable platform reference.
939    ///
940    /// # Returns
941    ///
942    /// - `Option<String>` - Always `None`.
943    fn read_clipboard(&self) -> Option<String> {
944        None
945    }
946
947    /// Rejects clipboard writes cleanly as `Unsupported` on smartwatches.
948    ///
949    /// # Arguments
950    ///
951    /// - `&Self` - Mutable wearable platform.
952    /// - `&str` - Ignored clipboard text.
953    ///
954    /// # Returns
955    ///
956    /// - `Result<(), PlatformError>` - `Err(PlatformError::Unsupported(_))`.
957    fn write_clipboard(&mut self, _text: &str) -> Result<(), PlatformError> {
958        Err(PlatformError::Unsupported(format!(
959            "Clipboard is unsupported on {}",
960            self.get_profile().get_vendor().as_str()
961        )))
962    }
963
964    /// Returns the active wearable OLED theme mode.
965    ///
966    /// # Arguments
967    ///
968    /// - `&Self` - Wearable platform reference.
969    ///
970    /// # Returns
971    ///
972    /// - `ThemeMode` - Active watch theme mode.
973    fn system_theme(&self) -> ThemeMode {
974        self.get_theme()
975    }
976
977    /// Returns `1.0` Hz during AOD ambient mode or the watch profile's interactive refresh rate otherwise.
978    ///
979    /// # Arguments
980    ///
981    /// - `&Self` - Wearable platform reference.
982    ///
983    /// # Returns
984    ///
985    /// - `f32` - Active watch refresh rate in Hertz.
986    fn display_refresh_rate_hz(&self) -> f32 {
987        if self.get_ambient_mode() == WearableAmbientMode::AlwaysOnAmbient {
988            WEARABLE_AOD_REFRESH_HZ
989        } else {
990            self.get_profile().get_refresh_rate_hz()
991        }
992    }
993}
994
995/// `PlatformStorage` implementation for `WearablePlatform`.
996impl PlatformStorage for WearablePlatform {
997    /// Reads a key from wearable local sandbox storage.
998    ///
999    /// # Arguments
1000    ///
1001    /// - `&Self` - Wearable platform reference.
1002    /// - `&str` - Storage key.
1003    ///
1004    /// # Returns
1005    ///
1006    /// - `Option<String>` - Stored value, if present.
1007    fn storage_get(&self, key: &str) -> Option<String> {
1008        self.get_storage().get(key).cloned()
1009    }
1010
1011    /// Stores a key-value pair in wearable sandbox storage.
1012    ///
1013    /// # Arguments
1014    ///
1015    /// - `&Self` - Mutable wearable platform.
1016    /// - `&str` - Storage key.
1017    /// - `&str` - UTF-8 value.
1018    ///
1019    /// # Returns
1020    ///
1021    /// - `Result<(), PlatformError>` - Persistence status.
1022    fn storage_set(&mut self, key: &str, value: &str) -> Result<(), PlatformError> {
1023        let _: Option<String> = self
1024            .get_mut_storage()
1025            .insert(key.to_string(), value.to_string());
1026        Ok(())
1027    }
1028
1029    /// Removes `key` from wearable sandbox storage.
1030    ///
1031    /// # Arguments
1032    ///
1033    /// - `&Self` - Mutable wearable platform.
1034    /// - `&str` - Storage key.
1035    ///
1036    /// # Returns
1037    ///
1038    /// - `Result<(), PlatformError>` - Removal status.
1039    fn storage_remove(&mut self, key: &str) -> Result<(), PlatformError> {
1040        let _: Option<String> = self.get_mut_storage().remove(key);
1041        Ok(())
1042    }
1043
1044    /// Clears all keys from wearable sandbox storage.
1045    ///
1046    /// # Arguments
1047    ///
1048    /// - `&Self` - Mutable wearable platform.
1049    ///
1050    /// # Returns
1051    ///
1052    /// - `Result<(), PlatformError>` - Clear status.
1053    fn storage_clear(&mut self) -> Result<(), PlatformError> {
1054        self.get_mut_storage().clear();
1055        Ok(())
1056    }
1057}
1058
1059/// `PlatformNavigation` implementation for `WearablePlatform`.
1060impl PlatformNavigation for WearablePlatform {
1061    /// Navigates to `route` on the wearable page stack.
1062    ///
1063    /// # Arguments
1064    ///
1065    /// - `&Self` - Mutable wearable platform.
1066    /// - `&str` - Target route path.
1067    ///
1068    /// # Returns
1069    ///
1070    /// - `Result<(), PlatformError>` - Navigation status.
1071    fn navigate_to(&mut self, route: &str) -> Result<(), PlatformError> {
1072        if !route.is_empty() {
1073            self.get_mut_route_stack().push(route.to_string());
1074        }
1075        Ok(())
1076    }
1077
1078    /// Pops `delta` entries from the wearable navigation stack, keeping the root watch screen.
1079    ///
1080    /// # Arguments
1081    ///
1082    /// - `&Self` - Mutable wearable platform.
1083    /// - `u32` - Pages to pop.
1084    ///
1085    /// # Returns
1086    ///
1087    /// - `Result<(), PlatformError>` - Navigation status.
1088    fn navigate_back(&mut self, delta: u32) -> Result<(), PlatformError> {
1089        for _ in 0..delta.max(1) {
1090            if self.get_route_stack().len() > 1 {
1091                let _: Option<String> = self.get_mut_route_stack().pop();
1092            }
1093        }
1094        Ok(())
1095    }
1096
1097    /// Returns the active wearable logical route path.
1098    ///
1099    /// # Arguments
1100    ///
1101    /// - `&Self` - Wearable platform reference.
1102    ///
1103    /// # Returns
1104    ///
1105    /// - `&str` - Active route string.
1106    fn current_route(&self) -> &str {
1107        self.get_route_stack()
1108            .last()
1109            .map(String::as_str)
1110            .unwrap_or(WEARABLE_DEFAULT_ROUTE)
1111    }
1112}
1113
1114/// `PlatformLifecycleBridge` implementation for `WearablePlatform`.
1115impl PlatformLifecycleBridge for WearablePlatform {
1116    /// Freezes the watch surface into `ScreenOff` or `AlwaysOnAmbient` freeze state.
1117    ///
1118    /// # Arguments
1119    ///
1120    /// - `&Self` - Mutable wearable platform.
1121    ///
1122    /// # Returns
1123    ///
1124    /// - `Vec<WindowEvent>` - Normalized freeze events.
1125    fn freeze_surface(&mut self) -> Vec<WindowEvent> {
1126        self.enter_screen_off()
1127    }
1128
1129    /// Wakes and resumes the watch surface into full interactive mode.
1130    ///
1131    /// # Arguments
1132    ///
1133    /// - `&Self` - Mutable wearable platform.
1134    ///
1135    /// # Returns
1136    ///
1137    /// - `Vec<WindowEvent>` - Normalized resume events.
1138    fn resume_surface(&mut self) -> Vec<WindowEvent> {
1139        self.exit_ambient()
1140    }
1141
1142    /// Cancels touches, pauses frame pumping, and emits `Terminate`.
1143    ///
1144    /// # Arguments
1145    ///
1146    /// - `&Self` - Mutable wearable platform.
1147    ///
1148    /// # Returns
1149    ///
1150    /// - `Vec<WindowEvent>` - Normalized destroy events.
1151    fn destroy_surface(&mut self) -> Vec<WindowEvent> {
1152        let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
1153        self.set_ambient_mode(WearableAmbientMode::ScreenOff);
1154        self.set_pump_paused(true);
1155        let mut events: Vec<WindowEvent> =
1156            self.get_mut_touch_tracker().cancel_all_on_focus_loss(wid);
1157        events.push(WindowEvent::System(SystemEvent::Terminate));
1158        events
1159    }
1160}
1161
1162/// `PlatformHostAdapter` implementation for `WearablePlatform`.
1163impl PlatformHostAdapter for WearablePlatform {
1164    /// Returns `DeviceFormFactor::Watch`.
1165    ///
1166    /// # Arguments
1167    ///
1168    /// - `&Self` - Wearable platform reference.
1169    ///
1170    /// # Returns
1171    ///
1172    /// - `DeviceFormFactor` - `DeviceFormFactor::Watch`.
1173    fn device_form_factor(&self) -> DeviceFormFactor {
1174        DeviceFormFactor::Watch
1175    }
1176
1177    /// Returns the canonical vendor identifier string (e.g. `"wearos"`, `"watchos"`, `"harmony-watch"`, `"hyperos-vela"`).
1178    ///
1179    /// # Arguments
1180    ///
1181    /// - `&Self` - Wearable platform reference.
1182    ///
1183    /// # Returns
1184    ///
1185    /// - `&'static str` - Vendor string identifier.
1186    fn host_vendor_name(&self) -> &'static str {
1187        self.get_profile().get_vendor().as_str()
1188    }
1189}
1190
1191/// Unified host-channel capability and visual-equivalence queries for `WearablePlatform`.
1192impl WearablePlatform {
1193    /// Returns the truthful `HostChannelCapabilities` for this smartwatch vendor profile.
1194    ///
1195    /// Single-channel wearable hosts (`GarminConnectIq`, `AmazfitZeppOs`, `HyperOsVela`, `VivoBlueOsWatch`, `GenericWearable`)
1196    /// declare a single channel and NEVER probe alternate modes; simulated/off-device profiles always report
1197    /// `simulated_profile = true` and `direct_gpu_verified_on_device = false`.
1198    ///
1199    /// # Returns
1200    ///
1201    /// - `HostChannelCapabilities` - Declared wearable channels, visual gate, and honesty flags.
1202    #[must_use]
1203    pub fn host_channel_capabilities(&self) -> HostChannelCapabilities {
1204        let has_live_surface: bool = self
1205            .get_windows()
1206            .values()
1207            .any(|rec: &WearableWindowRecord| rec.get_native_surface() != 0);
1208        let simulated: bool = !has_live_surface;
1209        let vendor: WearableVendor = self.get_profile().get_vendor();
1210        let (channels, preferred): (Vec<HostRenderChannel>, HostRenderChannel) = match vendor {
1211            WearableVendor::WearOs
1212            | WearableVendor::WatchOs
1213            | WearableVendor::HarmonyWatch
1214            | WearableVendor::OppoColorOsWatch => (
1215                vec![
1216                    HostRenderChannel::GpuDirect,
1217                    HostRenderChannel::SoftwareBuffer,
1218                ],
1219                if has_live_surface {
1220                    HostRenderChannel::GpuDirect
1221                } else {
1222                    HostRenderChannel::SoftwareBuffer
1223                },
1224            ),
1225            WearableVendor::HyperOsVela
1226            | WearableVendor::VivoBlueOsWatch
1227            | WearableVendor::GarminConnectIq
1228            | WearableVendor::AmazfitZeppOs
1229            | WearableVendor::GenericWearable => (
1230                vec![HostRenderChannel::SoftwareBuffer],
1231                HostRenderChannel::SoftwareBuffer,
1232            ),
1233        };
1234        let gpu_verified: bool =
1235            !simulated && channels.contains(&HostRenderChannel::GpuDirect) && has_live_surface;
1236        HostChannelCapabilities::from_host_declaration(
1237            self.host_vendor_name(),
1238            channels,
1239            preferred,
1240            HostVisualEquivalenceGate::default(),
1241            simulated,
1242            gpu_verified,
1243        )
1244    }
1245
1246    /// Resolves the wearable rendering channel under unified visual-equivalence and single-channel non-probing rules.
1247    ///
1248    /// # Arguments
1249    ///
1250    /// - `Option<HostRenderChannel>` - Optional requested channel.
1251    ///
1252    /// # Returns
1253    ///
1254    /// - `HostChannelSelection` - Resolved channel decision.
1255    #[must_use]
1256    pub fn select_render_channel(
1257        &self,
1258        requested: Option<HostRenderChannel>,
1259    ) -> HostChannelSelection {
1260        self.host_channel_capabilities().select_channel(requested)
1261    }
1262}