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    /// Updates the wearable interactive display refresh rate without imposing any artificial upper ceiling.
335    ///
336    /// # Arguments
337    ///
338    /// - `&Self` - Mutable wearable platform backend.
339    /// - `f32` - Reported hardware interactive display refresh rate in Hertz.
340    pub fn update_refresh_rate_hz(&mut self, hz: f32) {
341        if !hz.is_finite() || hz < MIN_REFRESH_RATE_HZ {
342            return;
343        }
344        self.get_mut_profile().set_refresh_rate_hz(hz);
345        let rounded_hz: u32 = hz.round() as u32;
346        for rec in self.get_mut_windows().values_mut() {
347            rec.get_mut_state()
348                .get_mut_display()
349                .set_refresh_rate_hz(rounded_hz);
350        }
351    }
352
353    /// Creates a `WearablePlatform` using the canonical display and hardware profile for `vendor`.
354    ///
355    /// # Arguments
356    ///
357    /// - `WearableVendor` - Target smartwatch vendor ecosystem.
358    ///
359    /// # Returns
360    ///
361    /// - `Self` - Configured wearable platform backend.
362    #[must_use]
363    pub fn for_vendor(vendor: WearableVendor) -> Self {
364        Self::from_profile(WearableProfile::for_vendor(vendor))
365    }
366
367    /// Creates a `WearablePlatform` preconfigured for vivo BlueOS Watch (466x466 round dial).
368    ///
369    /// # Returns
370    ///
371    /// - `Self` - Configured vivo BlueOS Watch platform backend.
372    #[must_use]
373    pub fn vivo_blueos() -> Self {
374        Self::from_profile(WearableProfile::vivo_watch_round())
375    }
376
377    /// Creates a `WearablePlatform` from a custom `WearableProfile`.
378    ///
379    /// # Arguments
380    ///
381    /// - `WearableProfile` - Custom smartwatch display and input profile.
382    ///
383    /// # Returns
384    ///
385    /// - `Self` - Configured wearable platform backend.
386    #[must_use]
387    pub fn from_profile(profile: WearableProfile) -> Self {
388        let safe_area: SafeAreaInsets = profile.safe_area_insets();
389        let compact_scale: f32 = profile.compact_scale();
390        Self {
391            profile,
392            ambient_mode: WearableAmbientMode::Interactive,
393            compact_scale,
394            safe_area,
395            crown_accumulator: 0.0,
396            crown_scroll_step: WEARABLE_CROWN_PIXELS_PER_DETENT,
397            next_id: 1,
398            primary_window: None,
399            windows: HashMap::new(),
400            touch_tracker: TouchPointerTracker::default(),
401            pending_events: Vec::new(),
402            storage: HashMap::new(),
403            route_stack: vec![WEARABLE_DEFAULT_ROUTE.to_string()],
404            theme: ThemeMode::Dark,
405            pump_paused: false,
406            haptic_detent_count: 0,
407            capture_last_frame: false,
408        }
409    }
410
411    /// Enables or disables retaining a cloned snapshot of the last presented framebuffer.
412    ///
413    /// # Arguments
414    ///
415    /// - `bool` - `true` to capture snapshots on each present; `false` for zero-clone production mode.
416    ///
417    /// # Returns
418    ///
419    /// - `Self` - Updated wearable platform backend.
420    #[must_use]
421    pub fn with_capture_last_frame(mut self, enabled: bool) -> Self {
422        self.set_capture_last_frame(enabled);
423        self
424    }
425
426    /// Returns the last presented framebuffer snapshot for `id` when `capture_last_frame` is enabled.
427    ///
428    /// # Arguments
429    ///
430    /// - `WindowId` - Watch window identifier.
431    ///
432    /// # Returns
433    ///
434    /// - `Option<&Framebuffer>` - Cloned framebuffer reference when capture is enabled and `id` exists.
435    #[must_use]
436    pub fn last_framebuffer(&self, id: WindowId) -> Option<&Framebuffer> {
437        if !self.get_capture_last_frame() {
438            return None;
439        }
440        self.get_windows()
441            .get(&id)
442            .map(WearableWindowRecord::get_last_frame)
443    }
444
445    /// Returns the primary watch window identifier, if created.
446    ///
447    /// # Arguments
448    ///
449    /// - `&Self` - Wearable platform reference.
450    ///
451    /// # Returns
452    ///
453    /// - `Option<WindowId>` - Primary watch window handle.
454    #[must_use]
455    pub fn primary_window_id(&self) -> Option<WindowId> {
456        let Self { primary_window, .. } = self;
457        *primary_window
458    }
459
460    /// Translates a rotary crown or rotating bezel rotation event into standard EUV scroll or focus `WindowEvent`s.
461    ///
462    /// # Arguments
463    ///
464    /// - `&Self` - Mutable wearable platform.
465    /// - `WearableCrownInput` - Raw vendor crown/bezel detent delta and mode.
466    ///
467    /// # Returns
468    ///
469    /// - `Vec<WindowEvent>` - Normalized standard EUV events also enqueued for `poll_events()`.
470    pub fn handle_crown_input(&mut self, input: WearableCrownInput) -> Vec<WindowEvent> {
471        let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
472        if !input.get_detents().is_finite() || input.get_detents().abs() < 1e-5 {
473            return Vec::new();
474        }
475        let mut emitted: Vec<WindowEvent> = Vec::new();
476        match input.get_mode() {
477            WearableCrownMode::Scroll => {
478                let dy: f32 = input.get_detents() * self.get_crown_scroll_step();
479                emitted.push(WindowEvent::Scroll(wid, Point::new(0.0, dy)));
480            }
481            WearableCrownMode::FocusStep => {
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 forward: bool = whole > 0;
492                let steps: usize = whole.unsigned_abs().min(16) as usize;
493                let mods: Modifiers = Modifiers::new(!forward, false, false, false);
494                for _ in 0..steps {
495                    emitted.push(WindowEvent::KeyDown(
496                        wid,
497                        KeyEvent::new(KeyCode::Tab, mods, false),
498                    ));
499                    emitted.push(WindowEvent::KeyUp(
500                        wid,
501                        KeyEvent::new(KeyCode::Tab, mods, false),
502                    ));
503                }
504            }
505            WearableCrownMode::DirectionalStep => {
506                let prev: f32 = self.get_crown_accumulator();
507                let base: f32 = if prev * input.get_detents() < 0.0 {
508                    0.0
509                } else {
510                    prev
511                };
512                let total: f32 = base + input.get_detents();
513                let whole: i32 = total.trunc() as i32;
514                self.set_crown_accumulator(total - (whole as f32));
515                let code: KeyCode = if whole > 0 {
516                    KeyCode::ArrowDown
517                } else {
518                    KeyCode::ArrowUp
519                };
520                let steps: usize = whole.unsigned_abs().min(16) as usize;
521                for _ in 0..steps {
522                    emitted.push(WindowEvent::KeyDown(
523                        wid,
524                        KeyEvent::new(code, Modifiers::default(), false),
525                    ));
526                    emitted.push(WindowEvent::KeyUp(
527                        wid,
528                        KeyEvent::new(code, Modifiers::default(), false),
529                    ));
530                }
531            }
532        }
533        if input.get_haptic_detent() && !emitted.is_empty() {
534            let next_h: u64 = self.get_haptic_detent_count().saturating_add(1);
535            self.set_haptic_detent_count(next_h);
536        }
537        self.get_mut_pending_events().extend(emitted.clone());
538        emitted
539    }
540
541    /// Transitions the watch into low-power Always-On Display (AOD) ambient mode, freezing interactive pumping.
542    ///
543    /// # Arguments
544    ///
545    /// - `&Self` - Mutable wearable platform.
546    ///
547    /// # Returns
548    ///
549    /// - `Vec<WindowEvent>` - Normalized ambient transition events.
550    pub fn enter_ambient(&mut self) -> Vec<WindowEvent> {
551        if !self.get_profile().get_supports_aod() {
552            return self.enter_screen_off();
553        }
554        let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
555        self.set_ambient_mode(WearableAmbientMode::AlwaysOnAmbient);
556        self.set_pump_paused(true);
557        let mut events: Vec<WindowEvent> =
558            self.get_mut_touch_tracker().cancel_all_on_focus_loss(wid);
559        events.push(WindowEvent::System(SystemEvent::LowPowerModeChanged(true)));
560        events.push(WindowEvent::System(SystemEvent::Inactive));
561        self.get_mut_pending_events().extend(events.clone());
562        events
563    }
564
565    /// Delivers a single low-power 1Hz AOD ambient redraw pulse while remaining in `AlwaysOnAmbient` mode.
566    ///
567    /// # Arguments
568    ///
569    /// - `&Self` - Mutable wearable platform.
570    ///
571    /// # Returns
572    ///
573    /// - `Option<WindowEvent>` - `RedrawRequested` event when currently in `AlwaysOnAmbient` mode.
574    pub fn pulse_ambient_tick(&mut self) -> Option<WindowEvent> {
575        if self.get_ambient_mode() != WearableAmbientMode::AlwaysOnAmbient {
576            return None;
577        }
578        let wid: WindowId = self.primary_window_id()?;
579        if let Some(rec) = self.get_mut_windows().get_mut(&wid) {
580            rec.set_ambient_tick_count(rec.get_ambient_tick_count().saturating_add(1));
581        }
582        let window_event: WindowEvent = WindowEvent::RedrawRequested(wid);
583        self.get_mut_pending_events().push(window_event.clone());
584        Some(window_event)
585    }
586
587    /// Transitions the watch into full `ScreenOff` background freeze (0% CPU/GPU).
588    ///
589    /// # Arguments
590    ///
591    /// - `&Self` - Mutable wearable platform.
592    ///
593    /// # Returns
594    ///
595    /// - `Vec<WindowEvent>` - Normalized background freeze events.
596    pub fn enter_screen_off(&mut self) -> Vec<WindowEvent> {
597        let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
598        self.set_ambient_mode(WearableAmbientMode::ScreenOff);
599        self.set_pump_paused(true);
600        let mut events: Vec<WindowEvent> =
601            self.get_mut_touch_tracker().cancel_all_on_focus_loss(wid);
602        events.push(WindowEvent::System(SystemEvent::Disappear));
603        events.push(WindowEvent::System(SystemEvent::Background));
604        self.get_mut_pending_events().extend(events.clone());
605        events
606    }
607
608    /// Wakes the watch from `AlwaysOnAmbient` or `ScreenOff` back into full interactive mode.
609    ///
610    /// # Arguments
611    ///
612    /// - `&Self` - Mutable wearable platform.
613    ///
614    /// # Returns
615    ///
616    /// - `Vec<WindowEvent>` - Normalized interactive resume events.
617    pub fn exit_ambient(&mut self) -> Vec<WindowEvent> {
618        self.set_ambient_mode(WearableAmbientMode::Interactive);
619        self.set_pump_paused(false);
620        let events: Vec<WindowEvent> = vec![
621            WindowEvent::System(SystemEvent::LowPowerModeChanged(false)),
622            WindowEvent::System(SystemEvent::Appear),
623            WindowEvent::System(SystemEvent::Foreground),
624        ];
625        self.get_mut_pending_events().extend(events.clone());
626        events
627    }
628
629    /// Translates physical wrist, palm-cover, double-pinch, and side-button hardware gestures into standard EUV events.
630    ///
631    /// # Arguments
632    ///
633    /// - `&Self` - Mutable wearable platform.
634    /// - `WearableHardwareGesture` - Hardware gesture detected by the watch OS.
635    ///
636    /// # Returns
637    ///
638    /// - `Vec<WindowEvent>` - Normalized standard EUV window/system events.
639    pub fn handle_hardware_gesture(
640        &mut self,
641        gesture: WearableHardwareGesture,
642    ) -> Vec<WindowEvent> {
643        let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
644        match gesture {
645            WearableHardwareGesture::WristRaise => self.exit_ambient(),
646            WearableHardwareGesture::WristLower => {
647                if self.get_profile().get_supports_aod() {
648                    self.enter_ambient()
649                } else {
650                    self.enter_screen_off()
651                }
652            }
653            WearableHardwareGesture::PalmCover => self.enter_screen_off(),
654            WearableHardwareGesture::DoublePinch => {
655                let events: Vec<WindowEvent> = vec![
656                    WindowEvent::KeyDown(
657                        wid,
658                        KeyEvent::new(KeyCode::Enter, Modifiers::default(), false),
659                    ),
660                    WindowEvent::KeyUp(
661                        wid,
662                        KeyEvent::new(KeyCode::Enter, Modifiers::default(), false),
663                    ),
664                ];
665                self.get_mut_pending_events().extend(events.clone());
666                events
667            }
668            WearableHardwareGesture::SideButtonPress => {
669                let events: Vec<WindowEvent> = vec![
670                    WindowEvent::KeyDown(
671                        wid,
672                        KeyEvent::new(KeyCode::Back, Modifiers::default(), false),
673                    ),
674                    WindowEvent::System(SystemEvent::BackPressed),
675                ];
676                self.get_mut_pending_events().extend(events.clone());
677                events
678            }
679            WearableHardwareGesture::SideButtonLongPress => {
680                let events: Vec<WindowEvent> = vec![WindowEvent::System(SystemEvent::Inactive)];
681                self.get_mut_pending_events().extend(events.clone());
682                events
683            }
684        }
685    }
686}
687
688/// `WindowController` implementation for `WearablePlatform`.
689impl WindowController for WearablePlatform {
690    /// Applies a `WindowCommand` against the smartwatch window record.
691    ///
692    /// # Arguments
693    ///
694    /// - `&Self` - Mutable wearable platform.
695    /// - `WindowCommand` - Command to execute.
696    ///
697    /// # Returns
698    ///
699    /// - `Result<(), PlatformError>` - Execution status.
700    fn apply_command(&mut self, command: WindowCommand) -> Result<(), PlatformError> {
701        match command {
702            WindowCommand::SetTitle(id, title) => {
703                let rec: &mut WearableWindowRecord = self
704                    .get_mut_windows()
705                    .get_mut(&id)
706                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
707                rec.get_mut_config().set_title(title);
708                Ok(())
709            }
710            WindowCommand::SetSize(id, width, height) => {
711                let shape: WearableShape = self.get_profile().get_shape();
712                let chin: f32 = self.get_profile().get_chin_height_dp();
713                let safe: SafeAreaInsets = compute_wearable_safe_area(
714                    shape,
715                    width.max(1) as f32,
716                    height.max(1) as f32,
717                    chin,
718                );
719                let compact: f32 =
720                    compute_wearable_compact_scale(width.max(1) as f32, height.max(1) as f32);
721                self.set_safe_area(safe);
722                self.set_compact_scale(compact);
723                let scale: f32 = {
724                    let rec: &mut WearableWindowRecord = self
725                        .get_mut_windows()
726                        .get_mut(&id)
727                        .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
728                    let source_val: f32 = clamp_viewport_scale(rec.get_state().get_scale_factor());
729                    let phys_w: u32 =
730                        compute_lossless_physical_dim(f64::from(width.max(1)), source_val);
731                    let phys_h: u32 =
732                        compute_lossless_physical_dim(f64::from(height.max(1)), source_val);
733                    rec.get_mut_config().set_size(width.max(1), height.max(1));
734                    rec.get_mut_state()
735                        .set_logical_width(width.max(1) as f32)
736                        .set_logical_height(height.max(1) as f32)
737                        .set_physical_width(phys_w)
738                        .set_physical_height(phys_h)
739                        .set_scale_factor(source_val)
740                        .set_safe_area(safe);
741                    source_val
742                };
743                self.get_mut_pending_events().push(WindowEvent::Resized(
744                    id,
745                    width.max(1),
746                    height.max(1),
747                    scale,
748                ));
749                self.get_mut_pending_events()
750                    .push(WindowEvent::SafeAreaChanged(id, safe));
751                Ok(())
752            }
753            WindowCommand::SetRenderMode(id, mode) => {
754                let rec: &mut WearableWindowRecord = self
755                    .get_mut_windows()
756                    .get_mut(&id)
757                    .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
758                rec.get_mut_config().get_mut_render().set_mode(mode);
759                Ok(())
760            }
761            WindowCommand::RequestRedraw(id) => {
762                if !self.get_windows().contains_key(&id) {
763                    return Err(PlatformError::WindowNotFound(id.get_value()));
764                }
765                self.get_mut_pending_events()
766                    .push(WindowEvent::RedrawRequested(id));
767                Ok(())
768            }
769            WindowCommand::Close(id) => {
770                if self.get_mut_windows().remove(&id).is_none() {
771                    return Err(PlatformError::WindowNotFound(id.get_value()));
772                }
773                Ok(())
774            }
775            WindowCommand::SetPosition(id, _, _)
776            | WindowCommand::SetResizable(id, _)
777            | WindowCommand::SetDecorations(id, _)
778            | WindowCommand::SetAlwaysOnTop(id, _)
779            | WindowCommand::SetFullscreen(id, _)
780            | WindowCommand::SetVisible(id, _)
781            | WindowCommand::SetCursor(id, _)
782            | WindowCommand::SetIme(id, _, _)
783            | WindowCommand::SetStatusBarStyle(id, _) => {
784                if !self.get_windows().contains_key(&id) {
785                    return Err(PlatformError::WindowNotFound(id.get_value()));
786                }
787                Ok(())
788            }
789        }
790    }
791}
792
793/// `PlatformBackend` implementation for `WearablePlatform`.
794impl PlatformBackend for WearablePlatform {
795    /// Returns `PlatformKind::Wearable`.
796    ///
797    /// # Arguments
798    ///
799    /// - `&Self` - Wearable platform reference.
800    ///
801    /// # Returns
802    ///
803    /// - `PlatformKind` - `PlatformKind::Wearable`.
804    fn kind(&self) -> PlatformKind {
805        PlatformKind::Wearable
806    }
807
808    /// Returns smartwatch capabilities refined by the active hardware profile.
809    ///
810    /// # Arguments
811    ///
812    /// - `&Self` - Wearable platform reference.
813    ///
814    /// # Returns
815    ///
816    /// - `PlatformCapabilities` - Wearable capability flags.
817    fn capabilities(&self) -> PlatformCapabilities {
818        let mut caps: PlatformCapabilities =
819            PlatformCapabilities::for_platform(PlatformKind::Wearable);
820        caps.rotary_input = self.get_profile().get_has_rotary_crown();
821        caps.always_on_display = self.get_profile().get_supports_aod();
822        caps
823    }
824
825    /// Creates a watch surface window with automatic round/squircle inscribed safe-area insets.
826    ///
827    /// # Arguments
828    ///
829    /// - `&Self` - Mutable wearable platform.
830    /// - `&WindowConfig` - Declarative window configuration.
831    ///
832    /// # Returns
833    ///
834    /// - `Result<WindowState, PlatformError>` - Initialized watch window state.
835    fn create_window(&mut self, config: &WindowConfig) -> Result<WindowState, PlatformError> {
836        let id: WindowId = WindowId::new(self.get_next_id());
837        self.set_next_id(self.get_next_id().wrapping_add(1));
838        let profile: WearableProfile = self.get_profile();
839        let mut watch_cfg: WindowConfig = config.clone();
840        watch_cfg.set_size(profile.get_logical_width(), profile.get_logical_height());
841        let mut state: WindowState =
842            WindowState::from_config(id, &watch_cfg, profile.get_scale_factor());
843        state.set_safe_area(self.get_safe_area());
844        state.set_system_theme(self.get_theme());
845        state
846            .get_mut_display()
847            .set_refresh_rate_hz(profile.get_refresh_rate_hz().round() as u32);
848        let record: WearableWindowRecord = WearableWindowRecord {
849            config: watch_cfg,
850            state,
851            native_surface: 0,
852            last_frame: Framebuffer::allocate(1, 1),
853            present_count: 0,
854            ambient_tick_count: 0,
855        };
856        self.get_mut_windows().insert(id, record);
857        if self.primary_window_id().is_none() {
858            self.set_primary_window(Some(id));
859        }
860        Ok(state)
861    }
862
863    /// Queries live `WindowState` for `id`.
864    ///
865    /// # Arguments
866    ///
867    /// - `&Self` - Wearable platform reference.
868    /// - `WindowId` - Window identifier.
869    ///
870    /// # Returns
871    ///
872    /// - `Option<WindowState>` - Window state if alive.
873    fn window_state(&self, id: WindowId) -> Option<WindowState> {
874        self.get_windows()
875            .get(&id)
876            .map(WearableWindowRecord::get_state)
877    }
878
879    /// Returns `RawWindowHandle::WearableSurface` tagged with the active `WearableVendor`.
880    ///
881    /// # Arguments
882    ///
883    /// - `&Self` - Wearable platform reference.
884    /// - `WindowId` - Window identifier.
885    ///
886    /// # Returns
887    ///
888    /// - `RawWindowHandle` - Wearable surface handle.
889    fn raw_window_handle(&self, id: WindowId) -> RawWindowHandle {
890        match self.get_windows().get(&id) {
891            Some(rec) => RawWindowHandle::WearableSurface {
892                native_handle: rec.get_native_surface(),
893                vendor_tag: self.get_profile().get_vendor().tag(),
894            },
895            None => RawWindowHandle::Headless,
896        }
897    }
898
899    /// Drains queued wearable input, rotary crown, gesture, and AOD lifecycle events.
900    ///
901    /// # Arguments
902    ///
903    /// - `&Self` - Mutable wearable platform.
904    ///
905    /// # Returns
906    ///
907    /// - `Vec<WindowEvent>` - Pending events.
908    fn poll_events(&mut self) -> Vec<WindowEvent> {
909        take(self.get_mut_pending_events())
910    }
911
912    /// Updates frame pump pause state for AOD / screen-off freeze.
913    ///
914    /// # Arguments
915    ///
916    /// - `&Self` - Mutable wearable platform.
917    /// - `bool` - `true` to pause frame pumping.
918    fn set_frame_pump_paused(&mut self, paused: bool) {
919        self.set_pump_paused(paused);
920    }
921
922    /// Returns whether the watch frame pump is paused.
923    ///
924    /// # Arguments
925    ///
926    /// - `&Self` - Wearable platform reference.
927    ///
928    /// # Returns
929    ///
930    /// - `bool` - Pause state.
931    fn is_frame_pump_paused(&self) -> bool {
932        self.get_pump_paused()
933    }
934
935    /// Presents `framebuffer` to the active watch window record.
936    ///
937    /// # Arguments
938    ///
939    /// - `&Self` - Mutable wearable platform.
940    /// - `WindowId` - Target window handle.
941    /// - `&Framebuffer` - Rendered RGBA8 framebuffer.
942    ///
943    /// # Returns
944    ///
945    /// - `Result<(), PlatformError>` - Presentation status.
946    fn present_framebuffer(
947        &mut self,
948        id: WindowId,
949        framebuffer: &Framebuffer,
950    ) -> Result<(), PlatformError> {
951        let capture: bool = self.get_capture_last_frame();
952        let rec: &mut WearableWindowRecord = self
953            .get_mut_windows()
954            .get_mut(&id)
955            .ok_or(PlatformError::WindowNotFound(id.get_value()))?;
956        if capture {
957            rec.set_last_frame(framebuffer.clone());
958        }
959        rec.set_present_count(rec.get_present_count().wrapping_add(1));
960        Ok(())
961    }
962
963    /// Returns `None` because smartwatches do not expose a system clipboard.
964    ///
965    /// # Arguments
966    ///
967    /// - `&Self` - Wearable platform reference.
968    ///
969    /// # Returns
970    ///
971    /// - `Option<String>` - Always `None`.
972    fn read_clipboard(&self) -> Option<String> {
973        None
974    }
975
976    /// Rejects clipboard writes cleanly as `Unsupported` on smartwatches.
977    ///
978    /// # Arguments
979    ///
980    /// - `&Self` - Mutable wearable platform.
981    /// - `&str` - Ignored clipboard text.
982    ///
983    /// # Returns
984    ///
985    /// - `Result<(), PlatformError>` - `Err(PlatformError::Unsupported(_))`.
986    fn write_clipboard(&mut self, _text: &str) -> Result<(), PlatformError> {
987        Err(PlatformError::Unsupported(format!(
988            "Clipboard is unsupported on {}",
989            self.get_profile().get_vendor().as_str()
990        )))
991    }
992
993    /// Returns the active wearable OLED theme mode.
994    ///
995    /// # Arguments
996    ///
997    /// - `&Self` - Wearable platform reference.
998    ///
999    /// # Returns
1000    ///
1001    /// - `ThemeMode` - Active watch theme mode.
1002    fn system_theme(&self) -> ThemeMode {
1003        self.get_theme()
1004    }
1005
1006    /// Returns `1.0` Hz during AOD ambient mode or the watch profile's interactive refresh rate otherwise.
1007    ///
1008    /// # Arguments
1009    ///
1010    /// - `&Self` - Wearable platform reference.
1011    ///
1012    /// # Returns
1013    ///
1014    /// - `f32` - Active watch refresh rate in Hertz.
1015    fn display_refresh_rate_hz(&self) -> f32 {
1016        if self.get_ambient_mode() == WearableAmbientMode::AlwaysOnAmbient {
1017            WEARABLE_AOD_REFRESH_HZ
1018        } else {
1019            self.get_profile().get_refresh_rate_hz()
1020        }
1021    }
1022}
1023
1024/// `PlatformStorage` implementation for `WearablePlatform`.
1025impl PlatformStorage for WearablePlatform {
1026    /// Reads a key from wearable local sandbox storage.
1027    ///
1028    /// # Arguments
1029    ///
1030    /// - `&Self` - Wearable platform reference.
1031    /// - `&str` - Storage key.
1032    ///
1033    /// # Returns
1034    ///
1035    /// - `Option<String>` - Stored value, if present.
1036    fn storage_get(&self, key: &str) -> Option<String> {
1037        self.get_storage().get(key).cloned()
1038    }
1039
1040    /// Stores a key-value pair in wearable sandbox storage.
1041    ///
1042    /// # Arguments
1043    ///
1044    /// - `&Self` - Mutable wearable platform.
1045    /// - `&str` - Storage key.
1046    /// - `&str` - UTF-8 value.
1047    ///
1048    /// # Returns
1049    ///
1050    /// - `Result<(), PlatformError>` - Persistence status.
1051    fn storage_set(&mut self, key: &str, value: &str) -> Result<(), PlatformError> {
1052        let _: Option<String> = self
1053            .get_mut_storage()
1054            .insert(key.to_string(), value.to_string());
1055        Ok(())
1056    }
1057
1058    /// Removes `key` from wearable sandbox storage.
1059    ///
1060    /// # Arguments
1061    ///
1062    /// - `&Self` - Mutable wearable platform.
1063    /// - `&str` - Storage key.
1064    ///
1065    /// # Returns
1066    ///
1067    /// - `Result<(), PlatformError>` - Removal status.
1068    fn storage_remove(&mut self, key: &str) -> Result<(), PlatformError> {
1069        let _: Option<String> = self.get_mut_storage().remove(key);
1070        Ok(())
1071    }
1072
1073    /// Clears all keys from wearable sandbox storage.
1074    ///
1075    /// # Arguments
1076    ///
1077    /// - `&Self` - Mutable wearable platform.
1078    ///
1079    /// # Returns
1080    ///
1081    /// - `Result<(), PlatformError>` - Clear status.
1082    fn storage_clear(&mut self) -> Result<(), PlatformError> {
1083        self.get_mut_storage().clear();
1084        Ok(())
1085    }
1086}
1087
1088/// `PlatformNavigation` implementation for `WearablePlatform`.
1089impl PlatformNavigation for WearablePlatform {
1090    /// Navigates to `route` on the wearable page stack.
1091    ///
1092    /// # Arguments
1093    ///
1094    /// - `&Self` - Mutable wearable platform.
1095    /// - `&str` - Target route path.
1096    ///
1097    /// # Returns
1098    ///
1099    /// - `Result<(), PlatformError>` - Navigation status.
1100    fn navigate_to(&mut self, route: &str) -> Result<(), PlatformError> {
1101        if !route.is_empty() {
1102            self.get_mut_route_stack().push(route.to_string());
1103        }
1104        Ok(())
1105    }
1106
1107    /// Pops `delta` entries from the wearable navigation stack, keeping the root watch screen.
1108    ///
1109    /// # Arguments
1110    ///
1111    /// - `&Self` - Mutable wearable platform.
1112    /// - `u32` - Pages to pop.
1113    ///
1114    /// # Returns
1115    ///
1116    /// - `Result<(), PlatformError>` - Navigation status.
1117    fn navigate_back(&mut self, delta: u32) -> Result<(), PlatformError> {
1118        for _ in 0..delta.max(1) {
1119            if self.get_route_stack().len() > 1 {
1120                let _: Option<String> = self.get_mut_route_stack().pop();
1121            }
1122        }
1123        Ok(())
1124    }
1125
1126    /// Returns the active wearable logical route path.
1127    ///
1128    /// # Arguments
1129    ///
1130    /// - `&Self` - Wearable platform reference.
1131    ///
1132    /// # Returns
1133    ///
1134    /// - `&str` - Active route string.
1135    fn current_route(&self) -> &str {
1136        self.get_route_stack()
1137            .last()
1138            .map(String::as_str)
1139            .unwrap_or(WEARABLE_DEFAULT_ROUTE)
1140    }
1141}
1142
1143/// `PlatformLifecycleBridge` implementation for `WearablePlatform`.
1144impl PlatformLifecycleBridge for WearablePlatform {
1145    /// Freezes the watch surface into `ScreenOff` or `AlwaysOnAmbient` freeze state.
1146    ///
1147    /// # Arguments
1148    ///
1149    /// - `&Self` - Mutable wearable platform.
1150    ///
1151    /// # Returns
1152    ///
1153    /// - `Vec<WindowEvent>` - Normalized freeze events.
1154    fn freeze_surface(&mut self) -> Vec<WindowEvent> {
1155        self.enter_screen_off()
1156    }
1157
1158    /// Wakes and resumes the watch surface into full interactive mode.
1159    ///
1160    /// # Arguments
1161    ///
1162    /// - `&Self` - Mutable wearable platform.
1163    ///
1164    /// # Returns
1165    ///
1166    /// - `Vec<WindowEvent>` - Normalized resume events.
1167    fn resume_surface(&mut self) -> Vec<WindowEvent> {
1168        self.exit_ambient()
1169    }
1170
1171    /// Cancels touches, pauses frame pumping, and emits `Terminate`.
1172    ///
1173    /// # Arguments
1174    ///
1175    /// - `&Self` - Mutable wearable platform.
1176    ///
1177    /// # Returns
1178    ///
1179    /// - `Vec<WindowEvent>` - Normalized destroy events.
1180    fn destroy_surface(&mut self) -> Vec<WindowEvent> {
1181        let wid: WindowId = self.primary_window_id().unwrap_or(WindowId::new(1));
1182        self.set_ambient_mode(WearableAmbientMode::ScreenOff);
1183        self.set_pump_paused(true);
1184        let mut events: Vec<WindowEvent> =
1185            self.get_mut_touch_tracker().cancel_all_on_focus_loss(wid);
1186        events.push(WindowEvent::System(SystemEvent::Terminate));
1187        events
1188    }
1189}
1190
1191/// `PlatformHostAdapter` implementation for `WearablePlatform`.
1192impl PlatformHostAdapter for WearablePlatform {
1193    /// Returns `DeviceFormFactor::Watch`.
1194    ///
1195    /// # Arguments
1196    ///
1197    /// - `&Self` - Wearable platform reference.
1198    ///
1199    /// # Returns
1200    ///
1201    /// - `DeviceFormFactor` - `DeviceFormFactor::Watch`.
1202    fn device_form_factor(&self) -> DeviceFormFactor {
1203        DeviceFormFactor::Watch
1204    }
1205
1206    /// Returns the canonical vendor identifier string (e.g. `"wearos"`, `"watchos"`, `"harmony-watch"`, `"hyperos-vela"`).
1207    ///
1208    /// # Arguments
1209    ///
1210    /// - `&Self` - Wearable platform reference.
1211    ///
1212    /// # Returns
1213    ///
1214    /// - `&'static str` - Vendor string identifier.
1215    fn host_vendor_name(&self) -> &'static str {
1216        self.get_profile().get_vendor().as_str()
1217    }
1218}
1219
1220/// Unified host-channel capability and visual-equivalence queries for `WearablePlatform`.
1221impl WearablePlatform {
1222    /// Returns the truthful `HostChannelCapabilities` for this smartwatch vendor profile.
1223    ///
1224    /// Single-channel wearable hosts (`GarminConnectIq`, `AmazfitZeppOs`, `HyperOsVela`, `VivoBlueOsWatch`, `GenericWearable`)
1225    /// declare a single channel and NEVER probe alternate modes; simulated/off-device profiles always report
1226    /// `simulated_profile = true` and `direct_gpu_verified_on_device = false`.
1227    ///
1228    /// # Returns
1229    ///
1230    /// - `HostChannelCapabilities` - Declared wearable channels, visual gate, and honesty flags.
1231    #[must_use]
1232    pub fn host_channel_capabilities(&self) -> HostChannelCapabilities {
1233        let has_live_surface: bool = self
1234            .get_windows()
1235            .values()
1236            .any(|rec: &WearableWindowRecord| rec.get_native_surface() != 0);
1237        let simulated: bool = !has_live_surface;
1238        let vendor: WearableVendor = self.get_profile().get_vendor();
1239        let (channels, preferred): (Vec<HostRenderChannel>, HostRenderChannel) = match vendor {
1240            WearableVendor::WearOs
1241            | WearableVendor::WatchOs
1242            | WearableVendor::HarmonyWatch
1243            | WearableVendor::OppoColorOsWatch => (
1244                vec![
1245                    HostRenderChannel::GpuDirect,
1246                    HostRenderChannel::SoftwareBuffer,
1247                ],
1248                if has_live_surface {
1249                    HostRenderChannel::GpuDirect
1250                } else {
1251                    HostRenderChannel::SoftwareBuffer
1252                },
1253            ),
1254            WearableVendor::HyperOsVela
1255            | WearableVendor::VivoBlueOsWatch
1256            | WearableVendor::GarminConnectIq
1257            | WearableVendor::AmazfitZeppOs
1258            | WearableVendor::GenericWearable => (
1259                vec![HostRenderChannel::SoftwareBuffer],
1260                HostRenderChannel::SoftwareBuffer,
1261            ),
1262        };
1263        let gpu_verified: bool =
1264            !simulated && channels.contains(&HostRenderChannel::GpuDirect) && has_live_surface;
1265        HostChannelCapabilities::from_host_declaration(
1266            self.host_vendor_name(),
1267            channels,
1268            preferred,
1269            HostVisualEquivalenceGate::default(),
1270            simulated,
1271            gpu_verified,
1272        )
1273    }
1274
1275    /// Resolves the wearable rendering channel under unified visual-equivalence and single-channel non-probing rules.
1276    ///
1277    /// # Arguments
1278    ///
1279    /// - `Option<HostRenderChannel>` - Optional requested channel.
1280    ///
1281    /// # Returns
1282    ///
1283    /// - `HostChannelSelection` - Resolved channel decision.
1284    #[must_use]
1285    pub fn select_render_channel(
1286        &self,
1287        requested: Option<HostRenderChannel>,
1288    ) -> HostChannelSelection {
1289        self.host_channel_capabilities().select_channel(requested)
1290    }
1291}