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