Skip to main content

euv_core/platform/wearable/
impl.rs

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