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