Skip to main content

euv_core/platform/info/
impl.rs

1use super::*;
2
3/// Metadata queries for `PlatformKind`.
4impl PlatformKind {
5    /// Returns the canonical lowercase name of this platform.
6    ///
7    /// # Arguments
8    ///
9    /// - `&Self` - Platform kind.
10    ///
11    /// # Returns
12    ///
13    /// - `&'static str` - Canonical platform name string.
14    #[must_use]
15    pub const fn as_str(&self) -> &'static str {
16        match *self {
17            Self::Web => PLATFORM_NAME_WEB,
18            Self::Android => PLATFORM_NAME_ANDROID,
19            Self::Ios => PLATFORM_NAME_IOS,
20            Self::IpadOs => PLATFORM_NAME_IPADOS,
21            Self::MacOs => PLATFORM_NAME_MACOS,
22            Self::Windows => PLATFORM_NAME_WINDOWS,
23            Self::Linux => PLATFORM_NAME_LINUX,
24            Self::HarmonyOs => PLATFORM_NAME_HARMONY_OS,
25            Self::Wearable => PLATFORM_NAME_WEARABLE,
26            Self::MiniApp => PLATFORM_NAME_MINIAPP,
27            Self::QuickApp => PLATFORM_NAME_QUICKAPP,
28            Self::Terminal => PLATFORM_NAME_TERMINAL,
29            Self::TerminalCli => PLATFORM_NAME_TERMINAL_CLI,
30            Self::Headless => PLATFORM_NAME_HEADLESS,
31        }
32    }
33
34    /// Parses a canonical platform identifier string into a `PlatformKind`.
35    ///
36    /// # Arguments
37    ///
38    /// - `&str` - Platform identifier string (case-insensitive).
39    ///
40    /// # Returns
41    ///
42    /// - `Option<Self>` - Matching `PlatformKind`, if recognized.
43    #[must_use]
44    pub fn from_str_id(name: &str) -> Option<Self> {
45        let lower: String = name.trim().to_ascii_lowercase();
46        match lower.as_str() {
47            PLATFORM_NAME_WEB => Some(Self::Web),
48            PLATFORM_NAME_ANDROID => Some(Self::Android),
49            PLATFORM_NAME_IOS => Some(Self::Ios),
50            PLATFORM_NAME_IPADOS => Some(Self::IpadOs),
51            PLATFORM_NAME_MACOS => Some(Self::MacOs),
52            PLATFORM_NAME_WINDOWS => Some(Self::Windows),
53            PLATFORM_NAME_LINUX => Some(Self::Linux),
54            PLATFORM_NAME_HARMONY_OS | PLATFORM_ALIAS_OHOS | PLATFORM_ALIAS_OPENHARMONY => {
55                Some(Self::HarmonyOs)
56            }
57            PLATFORM_NAME_WEARABLE | PLATFORM_ALIAS_WATCH => Some(Self::Wearable),
58            PLATFORM_NAME_MINIAPP => Some(Self::MiniApp),
59            PLATFORM_NAME_QUICKAPP => Some(Self::QuickApp),
60            PLATFORM_NAME_TERMINAL | PLATFORM_ALIAS_TUI => Some(Self::Terminal),
61            PLATFORM_NAME_TERMINAL_CLI | PLATFORM_ALIAS_CLI => Some(Self::TerminalCli),
62            PLATFORM_NAME_HEADLESS => Some(Self::Headless),
63            _ => None,
64        }
65    }
66
67    /// Returns the default `DeviceFormFactor` associated with this platform.
68    ///
69    /// # Arguments
70    ///
71    /// - `&Self` - Platform kind.
72    ///
73    /// # Returns
74    ///
75    /// - `DeviceFormFactor` - Device form factor.
76    #[must_use]
77    pub const fn form_factor(&self) -> DeviceFormFactor {
78        match *self {
79            Self::MacOs | Self::Windows | Self::Linux => DeviceFormFactor::Desktop,
80            Self::IpadOs => DeviceFormFactor::Tablet,
81            Self::Ios | Self::Android | Self::HarmonyOs => DeviceFormFactor::Phone,
82            Self::Wearable => DeviceFormFactor::Watch,
83            Self::MiniApp | Self::QuickApp => DeviceFormFactor::MiniProgram,
84            Self::Terminal | Self::TerminalCli => DeviceFormFactor::Terminal,
85            Self::Web => DeviceFormFactor::Browser,
86            Self::Headless => DeviceFormFactor::Headless,
87        }
88    }
89
90    /// Returns the default hardware or software `GraphicsBackend` associated with this platform.
91    ///
92    /// # Arguments
93    ///
94    /// - `&Self` - Platform kind.
95    ///
96    /// # Returns
97    ///
98    /// - `GraphicsBackend` - Preferred graphics backend.
99    #[must_use]
100    pub const fn default_graphics_backend(&self) -> GraphicsBackend {
101        match *self {
102            Self::MacOs | Self::Ios | Self::IpadOs => GraphicsBackend::Metal,
103            Self::Windows => GraphicsBackend::Direct3D12,
104            Self::Linux | Self::Android | Self::HarmonyOs | Self::Wearable => {
105                GraphicsBackend::Vulkan
106            }
107            Self::Web => GraphicsBackend::WebGpu,
108            Self::MiniApp | Self::QuickApp => GraphicsBackend::WebGl2,
109            Self::Terminal | Self::TerminalCli => GraphicsBackend::SoftwareCpu,
110            Self::Headless => GraphicsBackend::Headless,
111        }
112    }
113
114    /// Returns the initial display refresh rate heuristic in Hertz before live OS display polling completes.
115    ///
116    /// # Arguments
117    ///
118    /// - `&Self` - Platform kind.
119    ///
120    /// # Returns
121    ///
122    /// - `f32` - Initial display refresh rate in Hertz clamped to `MIN_REFRESH_RATE_HZ..=MAX_REFRESH_RATE_HZ`.
123    #[must_use]
124    pub const fn default_refresh_rate_hz(&self) -> f32 {
125        match *self {
126            Self::MacOs
127            | Self::Ios
128            | Self::IpadOs
129            | Self::Android
130            | Self::Windows
131            | Self::Linux
132            | Self::HarmonyOs
133            | Self::Web => HIGH_REFRESH_DEFAULT_HZ,
134            Self::Wearable
135            | Self::MiniApp
136            | Self::QuickApp
137            | Self::Terminal
138            | Self::TerminalCli
139            | Self::Headless => FALLBACK_REFRESH_RATE_HZ,
140        }
141    }
142
143    /// Returns true for mobile or tablet touch-first platforms (`Android`, `Ios`, `IpadOs`, `HarmonyOs`).
144    ///
145    /// # Arguments
146    ///
147    /// - `&Self` - Platform kind.
148    ///
149    /// # Returns
150    ///
151    /// - `bool` - True for mobile/tablet targets.
152    #[must_use]
153    pub const fn is_mobile_or_tablet(&self) -> bool {
154        matches!(
155            *self,
156            Self::Android | Self::Ios | Self::IpadOs | Self::HarmonyOs
157        )
158    }
159
160    /// Returns true when this platform renders to an interactive terminal or CLI stream.
161    ///
162    /// # Arguments
163    ///
164    /// - `&Self` - Platform kind.
165    ///
166    /// # Returns
167    ///
168    /// - `bool` - True for `Terminal` or `TerminalCli`.
169    #[must_use]
170    pub const fn is_terminal(&self) -> bool {
171        matches!(*self, Self::Terminal | Self::TerminalCli)
172    }
173
174    /// Returns true when this platform targets smartwatches or wrist wearables.
175    ///
176    /// # Arguments
177    ///
178    /// - `&Self` - Platform kind.
179    ///
180    /// # Returns
181    ///
182    /// - `bool` - True for `Wearable`.
183    #[must_use]
184    pub const fn is_wearable(&self) -> bool {
185        matches!(*self, Self::Wearable)
186    }
187
188    /// Returns true when this platform runs inside a Mini-Program or QuickApp container.
189    ///
190    /// # Arguments
191    ///
192    /// - `&Self` - Platform kind.
193    ///
194    /// # Returns
195    ///
196    /// - `bool` - True for `MiniApp` or `QuickApp`.
197    #[must_use]
198    pub const fn is_mini_container(&self) -> bool {
199        matches!(*self, Self::MiniApp | Self::QuickApp)
200    }
201
202    /// Returns true when this platform targets HarmonyOS / OpenHarmony.
203    ///
204    /// # Arguments
205    ///
206    /// - `&Self` - Platform kind.
207    ///
208    /// # Returns
209    ///
210    /// - `bool` - True for `HarmonyOs`.
211    #[must_use]
212    pub const fn is_harmony(&self) -> bool {
213        matches!(*self, Self::HarmonyOs)
214    }
215
216    /// Returns the list of all 7 classic desktop, mobile, and web targets supported by euv.
217    ///
218    /// # Returns
219    ///
220    /// - `[Self; 7]` - Array containing Web, Android, iOS, iPadOS, macOS, Windows, and Linux.
221    #[must_use]
222    pub const fn all_targets() -> [Self; 7] {
223        [
224            Self::Web,
225            Self::Android,
226            Self::Ios,
227            Self::IpadOs,
228            Self::MacOs,
229            Self::Windows,
230            Self::Linux,
231        ]
232    }
233
234    /// Returns the complete list of all 13 production execution targets across Desktop, Mobile, HarmonyOS, Wearables, Mini-Programs, QuickApps, and Terminal.
235    ///
236    /// # Returns
237    ///
238    /// - `[Self; 13]` - Complete production platform target list.
239    #[must_use]
240    pub const fn all_supported_targets() -> [Self; 13] {
241        [
242            Self::Web,
243            Self::Android,
244            Self::Ios,
245            Self::IpadOs,
246            Self::MacOs,
247            Self::Windows,
248            Self::Linux,
249            Self::HarmonyOs,
250            Self::Wearable,
251            Self::MiniApp,
252            Self::QuickApp,
253            Self::Terminal,
254            Self::TerminalCli,
255        ]
256    }
257}
258
259/// Capability matrix factory for `PlatformCapabilities`.
260impl PlatformCapabilities {
261    /// Returns the canonical capability matrix for `platform`.
262    ///
263    /// # Arguments
264    ///
265    /// - `PlatformKind` - Target platform.
266    ///
267    /// # Returns
268    ///
269    /// - `Self` - Normalized platform capabilities.
270    #[must_use]
271    pub fn for_platform(platform: PlatformKind) -> Self {
272        match platform {
273            PlatformKind::MacOs => Self {
274                multi_window: true,
275                hover_pointer: true,
276                touch: false,
277                stylus: false,
278                hardware_keyboard: true,
279                safe_area_insets: false,
280                hardware_gpu: true,
281                software_blit: true,
282                clipboard: true,
283                ime: true,
284                dynamic_island: false,
285                live_activities: false,
286                system_tray: true,
287                biometrics: true,
288                haptics: true,
289                protocol_handler: true,
290                accessibility_bridge: true,
291                rotary_input: false,
292                always_on_display: false,
293                capsule_chrome: false,
294                terminal_cells: false,
295                distributed_continuation: false,
296                local_storage: true,
297            },
298            PlatformKind::Windows => Self {
299                multi_window: true,
300                hover_pointer: true,
301                touch: false,
302                stylus: false,
303                hardware_keyboard: true,
304                safe_area_insets: false,
305                hardware_gpu: true,
306                software_blit: true,
307                clipboard: true,
308                ime: true,
309                dynamic_island: false,
310                live_activities: false,
311                system_tray: true,
312                biometrics: true,
313                haptics: false,
314                protocol_handler: true,
315                accessibility_bridge: true,
316                rotary_input: false,
317                always_on_display: false,
318                capsule_chrome: false,
319                terminal_cells: false,
320                distributed_continuation: false,
321                local_storage: true,
322            },
323            PlatformKind::Linux => Self {
324                multi_window: true,
325                hover_pointer: true,
326                touch: false,
327                stylus: false,
328                hardware_keyboard: true,
329                safe_area_insets: false,
330                hardware_gpu: true,
331                software_blit: true,
332                clipboard: true,
333                ime: true,
334                dynamic_island: false,
335                live_activities: false,
336                system_tray: true,
337                biometrics: false,
338                haptics: false,
339                protocol_handler: true,
340                accessibility_bridge: true,
341                rotary_input: false,
342                always_on_display: false,
343                capsule_chrome: false,
344                terminal_cells: false,
345                distributed_continuation: false,
346                local_storage: true,
347            },
348            PlatformKind::IpadOs => Self {
349                multi_window: true,
350                hover_pointer: true,
351                touch: true,
352                stylus: true,
353                hardware_keyboard: true,
354                safe_area_insets: true,
355                hardware_gpu: true,
356                software_blit: true,
357                clipboard: true,
358                ime: true,
359                dynamic_island: false,
360                live_activities: true,
361                system_tray: false,
362                biometrics: true,
363                haptics: true,
364                protocol_handler: true,
365                accessibility_bridge: true,
366                rotary_input: false,
367                always_on_display: false,
368                capsule_chrome: false,
369                terminal_cells: false,
370                distributed_continuation: false,
371                local_storage: true,
372            },
373            PlatformKind::Ios => Self {
374                multi_window: false,
375                hover_pointer: false,
376                touch: true,
377                stylus: true,
378                hardware_keyboard: false,
379                safe_area_insets: true,
380                hardware_gpu: true,
381                software_blit: true,
382                clipboard: true,
383                ime: true,
384                dynamic_island: true,
385                live_activities: true,
386                system_tray: false,
387                biometrics: true,
388                haptics: true,
389                protocol_handler: true,
390                accessibility_bridge: true,
391                rotary_input: false,
392                always_on_display: true,
393                capsule_chrome: false,
394                terminal_cells: false,
395                distributed_continuation: false,
396                local_storage: true,
397            },
398            PlatformKind::Android => Self {
399                multi_window: false,
400                hover_pointer: false,
401                touch: true,
402                stylus: true,
403                hardware_keyboard: false,
404                safe_area_insets: true,
405                hardware_gpu: true,
406                software_blit: true,
407                clipboard: true,
408                ime: true,
409                dynamic_island: false,
410                live_activities: true,
411                system_tray: false,
412                biometrics: true,
413                haptics: true,
414                protocol_handler: true,
415                accessibility_bridge: true,
416                rotary_input: false,
417                always_on_display: true,
418                capsule_chrome: false,
419                terminal_cells: false,
420                distributed_continuation: false,
421                local_storage: true,
422            },
423            PlatformKind::HarmonyOs => Self {
424                multi_window: true,
425                hover_pointer: true,
426                touch: true,
427                stylus: true,
428                hardware_keyboard: true,
429                safe_area_insets: true,
430                hardware_gpu: true,
431                software_blit: true,
432                clipboard: true,
433                ime: true,
434                dynamic_island: false,
435                live_activities: true,
436                system_tray: false,
437                biometrics: true,
438                haptics: true,
439                protocol_handler: true,
440                accessibility_bridge: true,
441                rotary_input: true,
442                always_on_display: true,
443                capsule_chrome: false,
444                terminal_cells: false,
445                distributed_continuation: true,
446                local_storage: true,
447            },
448            PlatformKind::Wearable => Self {
449                multi_window: false,
450                hover_pointer: false,
451                touch: true,
452                stylus: false,
453                hardware_keyboard: false,
454                safe_area_insets: true,
455                hardware_gpu: true,
456                software_blit: true,
457                clipboard: false,
458                ime: true,
459                dynamic_island: false,
460                live_activities: true,
461                system_tray: false,
462                biometrics: false,
463                haptics: true,
464                protocol_handler: true,
465                accessibility_bridge: true,
466                rotary_input: true,
467                always_on_display: true,
468                capsule_chrome: false,
469                terminal_cells: false,
470                distributed_continuation: false,
471                local_storage: true,
472            },
473            PlatformKind::MiniApp => Self {
474                multi_window: false,
475                hover_pointer: false,
476                touch: true,
477                stylus: false,
478                hardware_keyboard: false,
479                safe_area_insets: true,
480                hardware_gpu: true,
481                software_blit: true,
482                clipboard: true,
483                ime: true,
484                dynamic_island: false,
485                live_activities: false,
486                system_tray: false,
487                biometrics: false,
488                haptics: true,
489                protocol_handler: true,
490                accessibility_bridge: true,
491                rotary_input: false,
492                always_on_display: false,
493                capsule_chrome: true,
494                terminal_cells: false,
495                distributed_continuation: true,
496                local_storage: true,
497            },
498            PlatformKind::QuickApp => Self {
499                multi_window: false,
500                hover_pointer: false,
501                touch: true,
502                stylus: false,
503                hardware_keyboard: false,
504                safe_area_insets: true,
505                hardware_gpu: true,
506                software_blit: true,
507                clipboard: true,
508                ime: true,
509                dynamic_island: false,
510                live_activities: false,
511                system_tray: false,
512                biometrics: false,
513                haptics: true,
514                protocol_handler: true,
515                accessibility_bridge: true,
516                rotary_input: false,
517                always_on_display: false,
518                capsule_chrome: true,
519                terminal_cells: false,
520                distributed_continuation: false,
521                local_storage: true,
522            },
523            PlatformKind::Web => Self {
524                multi_window: false,
525                hover_pointer: true,
526                touch: true,
527                stylus: true,
528                hardware_keyboard: true,
529                safe_area_insets: true,
530                hardware_gpu: true,
531                software_blit: true,
532                clipboard: true,
533                ime: true,
534                dynamic_island: false,
535                live_activities: false,
536                system_tray: false,
537                biometrics: true,
538                haptics: true,
539                protocol_handler: true,
540                accessibility_bridge: true,
541                rotary_input: false,
542                always_on_display: false,
543                capsule_chrome: false,
544                terminal_cells: false,
545                distributed_continuation: false,
546                local_storage: true,
547            },
548            PlatformKind::Terminal => Self {
549                multi_window: false,
550                hover_pointer: true,
551                touch: false,
552                stylus: false,
553                hardware_keyboard: true,
554                safe_area_insets: false,
555                hardware_gpu: false,
556                software_blit: false,
557                clipboard: true,
558                ime: true,
559                dynamic_island: false,
560                live_activities: false,
561                system_tray: false,
562                biometrics: false,
563                haptics: false,
564                protocol_handler: false,
565                accessibility_bridge: true,
566                rotary_input: false,
567                always_on_display: false,
568                capsule_chrome: false,
569                terminal_cells: true,
570                distributed_continuation: false,
571                local_storage: false,
572            },
573            PlatformKind::TerminalCli => Self {
574                multi_window: false,
575                hover_pointer: false,
576                touch: false,
577                stylus: false,
578                hardware_keyboard: false,
579                safe_area_insets: false,
580                hardware_gpu: false,
581                software_blit: false,
582                clipboard: false,
583                ime: false,
584                dynamic_island: false,
585                live_activities: false,
586                system_tray: false,
587                biometrics: false,
588                haptics: false,
589                protocol_handler: false,
590                accessibility_bridge: true,
591                rotary_input: false,
592                always_on_display: false,
593                capsule_chrome: false,
594                terminal_cells: true,
595                distributed_continuation: false,
596                local_storage: false,
597            },
598            PlatformKind::Headless => Self {
599                multi_window: true,
600                hover_pointer: true,
601                touch: true,
602                stylus: false,
603                hardware_keyboard: true,
604                safe_area_insets: true,
605                hardware_gpu: false,
606                software_blit: true,
607                clipboard: true,
608                ime: true,
609                dynamic_island: false,
610                live_activities: false,
611                system_tray: true,
612                biometrics: false,
613                haptics: false,
614                protocol_handler: true,
615                accessibility_bridge: true,
616                rotary_input: false,
617                always_on_display: false,
618                capsule_chrome: false,
619                terminal_cells: false,
620                distributed_continuation: false,
621                local_storage: true,
622            },
623        }
624    }
625}
626
627/// Public accessors for `DisplayModeInfo`.
628impl DisplayModeInfo {
629    /// Returns the OS mode identifier.
630    ///
631    /// # Arguments
632    ///
633    /// - `&Self` - Display mode info.
634    ///
635    /// # Returns
636    ///
637    /// - `i32` - Mode identifier.
638    #[must_use]
639    pub fn mode_id(&self) -> i32 {
640        self.get_mode_id()
641    }
642
643    /// Returns the physical resolution `(width, height)` in pixels.
644    ///
645    /// # Arguments
646    ///
647    /// - `&Self` - Display mode info.
648    ///
649    /// # Returns
650    ///
651    /// - `(u32, u32)` - Physical width and height.
652    #[must_use]
653    pub fn physical_size(&self) -> (u32, u32) {
654        (self.get_physical_width(), self.get_physical_height())
655    }
656
657    /// Returns the hardware refresh rate in Hertz.
658    ///
659    /// # Arguments
660    ///
661    /// - `&Self` - Display mode info.
662    ///
663    /// # Returns
664    ///
665    /// - `f32` - Refresh rate in Hertz.
666    #[must_use]
667    pub fn refresh_rate_hz(&self) -> f32 {
668        self.get_refresh_rate_hz()
669    }
670}
671
672/// Public accessors for `FramePacingConfig`.
673impl FramePacingConfig {
674    /// Returns the minimum adaptive refresh rate in Hertz.
675    ///
676    /// # Arguments
677    ///
678    /// - `&Self` - Frame pacing config.
679    ///
680    /// # Returns
681    ///
682    /// - `f32` - Minimum refresh rate in Hertz.
683    #[must_use]
684    pub fn min_hz(&self) -> f32 {
685        self.get_min_hz()
686    }
687
688    /// Returns the maximum adaptive refresh rate in Hertz.
689    ///
690    /// # Arguments
691    ///
692    /// - `&Self` - Frame pacing config.
693    ///
694    /// # Returns
695    ///
696    /// - `f32` - Maximum refresh rate in Hertz.
697    #[must_use]
698    pub fn max_hz(&self) -> f32 {
699        self.get_max_hz()
700    }
701
702    /// Returns the preferred target refresh rate in Hertz.
703    ///
704    /// # Arguments
705    ///
706    /// - `&Self` - Frame pacing config.
707    ///
708    /// # Returns
709    ///
710    /// - `f32` - Preferred refresh rate in Hertz.
711    #[must_use]
712    pub fn preferred_hz(&self) -> f32 {
713        self.get_preferred_hz()
714    }
715
716    /// Returns the target frame interval in seconds.
717    ///
718    /// # Arguments
719    ///
720    /// - `&Self` - Frame pacing config.
721    ///
722    /// # Returns
723    ///
724    /// - `f32` - Frame duration in seconds.
725    #[must_use]
726    pub fn frame_interval_secs(&self) -> f32 {
727        self.get_frame_interval_secs()
728    }
729
730    /// Returns the target frame interval in nanoseconds.
731    ///
732    /// # Arguments
733    ///
734    /// - `&Self` - Frame pacing config.
735    ///
736    /// # Returns
737    ///
738    /// - `u64` - Frame duration in nanoseconds.
739    #[must_use]
740    pub fn frame_interval_nanos(&self) -> u64 {
741        self.get_frame_interval_nanos()
742    }
743}
744
745/// Multi-touch pointer lifecycle tracking and cancellation helpers for `TouchPointerTracker`.
746impl TouchPointerTracker {
747    /// Returns the currently active mapped pointer identifiers.
748    ///
749    /// # Arguments
750    ///
751    /// - `&Self` - Tracker reference.
752    ///
753    /// # Returns
754    ///
755    /// - `&[u64]` - Slice of active pointer IDs.
756    #[must_use]
757    pub fn active_ids(&self) -> &[u64] {
758        self.get_active_pointers().as_slice()
759    }
760
761    /// Returns the count of currently active touch pointers.
762    ///
763    /// # Arguments
764    ///
765    /// - `&Self` - Tracker reference.
766    ///
767    /// # Returns
768    ///
769    /// - `usize` - Active pointer count.
770    #[must_use]
771    pub fn active_count(&self) -> usize {
772        self.get_active_pointers().len()
773    }
774
775    /// Maps an Android `MotionEvent` raw pointer ID (`>= 0`) to a non-zero `euv` pointer identifier (`>= 1`).
776    ///
777    /// # Arguments
778    ///
779    /// - `i32` - Android pointer identifier.
780    ///
781    /// # Returns
782    ///
783    /// - `u64` - Non-zero mapped pointer identifier.
784    #[must_use]
785    pub fn map_android_pointer_id(raw_id: i32) -> u64 {
786        (raw_id.max(0) as u64).saturating_add(1)
787    }
788
789    /// Inserts `pointer_id` into the active contact set if not already present.
790    ///
791    /// # Arguments
792    ///
793    /// - `&Self` - Mutable tracker.
794    /// - `u64` - Mapped pointer identifier.
795    fn track_pointer(&mut self, pointer_id: u64) {
796        if pointer_id != 0 && !self.get_active_pointers().contains(&pointer_id) {
797            self.get_mut_active_pointers().push(pointer_id);
798        }
799    }
800
801    /// Removes `pointer_id` from the active contact set.
802    ///
803    /// # Arguments
804    ///
805    /// - `&Self` - Mutable tracker.
806    /// - `u64` - Mapped pointer identifier.
807    fn untrack_pointer(&mut self, pointer_id: u64) {
808        self.get_mut_active_pointers()
809            .retain(|id: &u64| *id != pointer_id);
810    }
811
812    /// Translates an Android `MotionEvent` (`action_masked`, `action_index`, `pointers`) into normalized `WindowEvent`s.
813    ///
814    /// # Arguments
815    ///
816    /// - `&Self` - Mutable tracker.
817    /// - `WindowId` - Target window handle.
818    /// - `i32` - Masked Android motion action (`ACTION_DOWN`, `ACTION_POINTER_DOWN`, `ACTION_MOVE`, `ACTION_POINTER_UP`, `ACTION_UP`, `ACTION_CANCEL`).
819    /// - `usize` - Pointer index reported by `MotionEvent.getActionIndex()`.
820    /// - `&[(i32, f32, f32)]` - Active pointer tuples `(raw_pointer_id, logical_x, logical_y)` in index order.
821    ///
822    /// # Returns
823    ///
824    /// - `Vec<WindowEvent>` - Ordered events to dispatch to `App`.
825    pub fn handle_android_motion(
826        &mut self,
827        wid: WindowId,
828        action_masked: i32,
829        action_index: usize,
830        pointers: &[(i32, f32, f32)],
831    ) -> Vec<WindowEvent> {
832        let mut events: Vec<WindowEvent> = Vec::new();
833        match action_masked {
834            ANDROID_ACTION_DOWN => {
835                if !self.get_active_pointers().is_empty() {
836                    let stale: Vec<u64> = take(self.get_mut_active_pointers());
837                    for id in stale.into_iter() {
838                        events.push(WindowEvent::PointerCancel(wid, id));
839                    }
840                    events.push(WindowEvent::PointerCancel(wid, 0));
841                }
842                if let Some(&(raw_id, x, y)) = pointers.get(action_index) {
843                    let pid: u64 = Self::map_android_pointer_id(raw_id);
844                    self.track_pointer(pid);
845                    events.push(WindowEvent::PointerDown(
846                        wid,
847                        PointerEvent::touch(pid, x, y),
848                    ));
849                }
850            }
851            ANDROID_ACTION_POINTER_DOWN => {
852                if let Some(&(raw_id, x, y)) = pointers.get(action_index) {
853                    let pid: u64 = Self::map_android_pointer_id(raw_id);
854                    self.track_pointer(pid);
855                    events.push(WindowEvent::PointerDown(
856                        wid,
857                        PointerEvent::touch(pid, x, y),
858                    ));
859                }
860            }
861            ANDROID_ACTION_MOVE => {
862                for &(raw_id, x, y) in pointers.iter() {
863                    let pid: u64 = Self::map_android_pointer_id(raw_id);
864                    self.track_pointer(pid);
865                    events.push(WindowEvent::PointerMove(
866                        wid,
867                        PointerEvent::touch(pid, x, y),
868                    ));
869                }
870            }
871            ANDROID_ACTION_POINTER_UP => {
872                if let Some(&(raw_id, x, y)) = pointers.get(action_index) {
873                    let pid: u64 = Self::map_android_pointer_id(raw_id);
874                    self.untrack_pointer(pid);
875                    events.push(WindowEvent::PointerUp(wid, PointerEvent::touch(pid, x, y)));
876                }
877            }
878            ANDROID_ACTION_UP => {
879                if let Some(&(raw_id, x, y)) = pointers.get(action_index) {
880                    let pid: u64 = Self::map_android_pointer_id(raw_id);
881                    self.untrack_pointer(pid);
882                    events.push(WindowEvent::PointerUp(wid, PointerEvent::touch(pid, x, y)));
883                }
884                self.get_mut_active_pointers().clear();
885            }
886            ANDROID_ACTION_CANCEL => {
887                let stale: Vec<u64> = take(self.get_mut_active_pointers());
888                for id in stale.into_iter() {
889                    events.push(WindowEvent::PointerCancel(wid, id));
890                }
891                events.push(WindowEvent::PointerCancel(wid, 0));
892            }
893            _ => {}
894        }
895        events
896    }
897
898    /// Records iOS `touchesBegan` contacts and produces corresponding `PointerDown` events.
899    ///
900    /// # Arguments
901    ///
902    /// - `&Self` - Mutable tracker.
903    /// - `WindowId` - Target window handle.
904    /// - `&[(u64, f32, f32)]` - Touch tuples `(pointer_id, logical_x, logical_y)`.
905    ///
906    /// # Returns
907    ///
908    /// - `Vec<WindowEvent>` - `PointerDown` events.
909    pub fn handle_ios_touches_began(
910        &mut self,
911        wid: WindowId,
912        touches: &[(u64, f32, f32)],
913    ) -> Vec<WindowEvent> {
914        let mut events: Vec<WindowEvent> = Vec::with_capacity(touches.len());
915        for &(raw_id, x, y) in touches.iter() {
916            let pid: u64 = raw_id.max(1);
917            self.track_pointer(pid);
918            events.push(WindowEvent::PointerDown(
919                wid,
920                PointerEvent::touch(pid, x, y),
921            ));
922        }
923        events
924    }
925
926    /// Handles iOS `touchesCancelled`, emitting `PointerCancel` for every cancelled and stale contact.
927    ///
928    /// # Arguments
929    ///
930    /// - `&Self` - Mutable tracker.
931    /// - `WindowId` - Target window handle.
932    /// - `&[u64]` - Cancelled touch pointer identifiers.
933    /// - `&[u64]` - Remaining active touch pointer identifiers from `UIEvent.allTouches`.
934    ///
935    /// # Returns
936    ///
937    /// - `Vec<WindowEvent>` - Ordered `PointerCancel` events.
938    pub fn handle_ios_touches_cancelled(
939        &mut self,
940        wid: WindowId,
941        cancelled_ids: &[u64],
942        remaining_live_ids: &[u64],
943    ) -> Vec<WindowEvent> {
944        let mut events: Vec<WindowEvent> = Vec::new();
945        for &raw_id in cancelled_ids.iter() {
946            let pid: u64 = raw_id.max(1);
947            self.untrack_pointer(pid);
948            events.push(WindowEvent::PointerCancel(wid, pid));
949        }
950        let stale: Vec<u64> = self
951            .get_active_pointers()
952            .iter()
953            .copied()
954            .filter(|id: &u64| !remaining_live_ids.contains(id))
955            .collect();
956        for id in stale.into_iter() {
957            self.untrack_pointer(id);
958            events.push(WindowEvent::PointerCancel(wid, id));
959        }
960        if self.get_active_pointers().is_empty() {
961            events.push(WindowEvent::PointerCancel(wid, 0));
962        }
963        events
964    }
965
966    /// Cancels all active touches on focus loss, pause, or window detachment so input never wedges.
967    ///
968    /// # Arguments
969    ///
970    /// - `&Self` - Mutable tracker.
971    /// - `WindowId` - Target window handle.
972    ///
973    /// # Returns
974    ///
975    /// - `Vec<WindowEvent>` - Per-pointer and global `PointerCancel` events (empty if no contacts were active).
976    pub fn cancel_all_on_focus_loss(&mut self, wid: WindowId) -> Vec<WindowEvent> {
977        let active: Vec<u64> = take(self.get_mut_active_pointers());
978        if active.is_empty() {
979            return Vec::new();
980        }
981        let mut events: Vec<WindowEvent> = Vec::with_capacity(active.len().saturating_add(1));
982        for id in active.into_iter() {
983            events.push(WindowEvent::PointerCancel(wid, id));
984        }
985        events.push(WindowEvent::PointerCancel(wid, 0));
986        events
987    }
988}
989
990/// Generation-stamped same-process session lifecycle helpers for `MobileSessionLifecycle`.
991impl MobileSessionLifecycle {
992    /// Registers a new host activity or scene session, resetting transient flags and returning its monotonic generation.
993    ///
994    /// # Arguments
995    ///
996    /// - `&Self` - Mutable lifecycle coordinator.
997    /// - `u64` - Unique identifier of the newly created host activity or scene.
998    ///
999    /// # Returns
1000    ///
1001    /// - `u64` - Monotonic session generation assigned to `owner_id`.
1002    pub fn begin_session(&mut self, owner_id: u64) -> u64 {
1003        let next_gen: u64 = self.get_session_generation().wrapping_add(1).max(1);
1004        self.set_session_generation(next_gen);
1005        self.set_active_owner_id(owner_id);
1006        self.set_surface_attached(false);
1007        self.set_loop_running(false);
1008        self.set_app_running(true);
1009        self.set_background_frozen(false);
1010        self.set_terminated(false);
1011        self.get_mut_touch_tracker()
1012            .get_mut_active_pointers()
1013            .clear();
1014        next_gen
1015    }
1016
1017    /// Re-claims bridge ownership when `owner_id` resumes and is either the latest session or the previous owner cleared.
1018    ///
1019    /// # Arguments
1020    ///
1021    /// - `&Self` - Mutable lifecycle coordinator.
1022    /// - `u64` - Resuming host activity or scene identifier.
1023    /// - `u64` - Generation originally assigned to `owner_id`.
1024    ///
1025    /// # Returns
1026    ///
1027    /// - `bool` - `true` when `owner_id` holds active bridge ownership after the call.
1028    pub fn activate_session(&mut self, owner_id: u64, session_gen: u64) -> bool {
1029        let cur_gen: u64 = self.get_session_generation();
1030        if session_gen >= cur_gen || self.get_active_owner_id() == 0 {
1031            if session_gen > cur_gen {
1032                self.set_session_generation(session_gen);
1033            }
1034            self.set_active_owner_id(owner_id);
1035            return true;
1036        }
1037        self.get_active_owner_id() == owner_id && cur_gen == session_gen
1038    }
1039
1040    /// Ends `owner_id`'s session only when `(owner_id, session_gen)` still owns the bridge, preventing delayed teardown races.
1041    ///
1042    /// # Arguments
1043    ///
1044    /// - `&Self` - Mutable lifecycle coordinator.
1045    /// - `u64` - Destroying host activity or scene identifier.
1046    /// - `u64` - Generation originally assigned to `owner_id`.
1047    ///
1048    /// # Returns
1049    ///
1050    /// - `bool` - `true` when ownership belonged to `owner_id` and was cleared; `false` when a newer session already replaced it.
1051    pub fn end_session(&mut self, owner_id: u64, session_gen: u64) -> bool {
1052        if self.get_active_owner_id() != owner_id || self.get_session_generation() != session_gen {
1053            return false;
1054        }
1055        self.set_active_owner_id(0);
1056        self.set_surface_attached(false);
1057        self.set_loop_running(false);
1058        self.set_app_running(false);
1059        self.set_terminated(true);
1060        self.get_mut_touch_tracker()
1061            .get_mut_active_pointers()
1062            .clear();
1063        true
1064    }
1065
1066    /// Returns `true` when `(owner_id, session_gen)` is currently the authoritative foreground bridge owner.
1067    ///
1068    /// # Arguments
1069    ///
1070    /// - `&Self` - Lifecycle coordinator reference.
1071    /// - `u64` - Host activity or scene identifier.
1072    /// - `u64` - Generation assigned to `owner_id`.
1073    ///
1074    /// # Returns
1075    ///
1076    /// - `bool` - `true` when `owner_id` matches the active generation and owner.
1077    #[must_use]
1078    pub fn is_active_owner(&self, owner_id: u64, session_gen: u64) -> bool {
1079        owner_id != 0
1080            && self.get_active_owner_id() == owner_id
1081            && self.get_session_generation() == session_gen
1082    }
1083
1084    /// Returns the current monotonic session generation.
1085    ///
1086    /// # Arguments
1087    ///
1088    /// - `&Self` - Lifecycle coordinator reference.
1089    ///
1090    /// # Returns
1091    ///
1092    /// - `u64` - Current session generation.
1093    #[must_use]
1094    pub fn active_session_generation(&self) -> u64 {
1095        self.get_session_generation()
1096    }
1097
1098    /// Returns the currently active bridge owner identifier (`0` when no activity or scene is active).
1099    ///
1100    /// # Arguments
1101    ///
1102    /// - `&Self` - Lifecycle coordinator reference.
1103    ///
1104    /// # Returns
1105    ///
1106    /// - `u64` - Active host owner identifier.
1107    #[must_use]
1108    pub fn active_owner_id(&self) -> u64 {
1109        self.get_active_owner_id()
1110    }
1111
1112    /// Returns the current VSync loop generation counter.
1113    ///
1114    /// # Arguments
1115    ///
1116    /// - `&Self` - Lifecycle coordinator reference.
1117    ///
1118    /// # Returns
1119    ///
1120    /// - `u64` - Active VSync callback generation.
1121    #[must_use]
1122    pub fn loop_generation(&self) -> u64 {
1123        self.get_loop_generation()
1124    }
1125
1126    /// Returns whether the VSync render loop is currently active.
1127    ///
1128    /// # Arguments
1129    ///
1130    /// - `&Self` - Lifecycle coordinator reference.
1131    ///
1132    /// # Returns
1133    ///
1134    /// - `bool` - `true` when the VSync frame pump is running.
1135    #[must_use]
1136    pub fn is_loop_running(&self) -> bool {
1137        self.get_loop_running()
1138    }
1139
1140    /// Returns whether a native rendering surface is currently attached.
1141    ///
1142    /// # Arguments
1143    ///
1144    /// - `&Self` - Lifecycle coordinator reference.
1145    ///
1146    /// # Returns
1147    ///
1148    /// - `bool` - `true` when the native surface is valid and bound.
1149    #[must_use]
1150    pub fn is_surface_attached(&self) -> bool {
1151        self.get_surface_attached()
1152    }
1153
1154    /// Returns `true` when an existing activity resumed after `Terminate` or exit request and must recreate its native `App` handle.
1155    ///
1156    /// # Arguments
1157    ///
1158    /// - `&Self` - Lifecycle coordinator reference.
1159    ///
1160    /// # Returns
1161    ///
1162    /// - `bool` - `true` when the native handle is no longer running or was terminated.
1163    #[must_use]
1164    pub fn should_recreate_handle(&self) -> bool {
1165        self.get_terminated() || !self.get_app_running()
1166    }
1167
1168    /// Marks the active session's surface attached and recreates the live running state if needed.
1169    ///
1170    /// # Arguments
1171    ///
1172    /// - `&Self` - Mutable lifecycle coordinator.
1173    pub fn on_surface_created(&mut self) {
1174        self.set_surface_attached(true);
1175        if self.should_recreate_handle() {
1176            self.set_app_running(true);
1177            self.set_terminated(false);
1178            self.set_background_frozen(false);
1179        }
1180    }
1181
1182    /// Marks the active surface detached and emits `PointerCancel` events for any active contacts.
1183    ///
1184    /// # Arguments
1185    ///
1186    /// - `&Self` - Mutable lifecycle coordinator.
1187    /// - `WindowId` - Window whose surface detached.
1188    ///
1189    /// # Returns
1190    ///
1191    /// - `Vec<WindowEvent>` - Cancellation events for any dangling touch contacts.
1192    pub fn on_surface_destroyed(&mut self, wid: WindowId) -> Vec<WindowEvent> {
1193        self.set_surface_attached(false);
1194        self.get_mut_touch_tracker().cancel_all_on_focus_loss(wid)
1195    }
1196
1197    /// Transitions the active session to resumed foreground state and returns the unique VSync loop generation.
1198    ///
1199    /// # Arguments
1200    ///
1201    /// - `&Self` - Mutable lifecycle coordinator.
1202    ///
1203    /// # Returns
1204    ///
1205    /// - `u64` - Unique VSync loop generation preventing duplicate frame callbacks.
1206    pub fn on_resume(&mut self) -> u64 {
1207        self.set_background_frozen(false);
1208        if self.should_recreate_handle() {
1209            self.set_app_running(true);
1210            self.set_terminated(false);
1211        }
1212        let next_loop: u64 = self.get_loop_generation().wrapping_add(1).max(1);
1213        self.set_loop_generation(next_loop);
1214        self.set_loop_running(true);
1215        next_loop
1216    }
1217
1218    /// Pauses the active VSync loop, advances the loop generation to invalidate in-flight callbacks, and cancels active touches.
1219    ///
1220    /// # Arguments
1221    ///
1222    /// - `&Self` - Mutable lifecycle coordinator.
1223    /// - `WindowId` - Target window handle.
1224    ///
1225    /// # Returns
1226    ///
1227    /// - `Vec<WindowEvent>` - Cancellation events for any active touch contacts.
1228    pub fn on_pause(&mut self, wid: WindowId) -> Vec<WindowEvent> {
1229        self.set_loop_running(false);
1230        let next_loop: u64 = self.get_loop_generation().wrapping_add(1).max(1);
1231        self.set_loop_generation(next_loop);
1232        self.get_mut_touch_tracker().cancel_all_on_focus_loss(wid)
1233    }
1234
1235    /// Marks the active session background-frozen with the VSync loop halted.
1236    ///
1237    /// # Arguments
1238    ///
1239    /// - `&Self` - Mutable lifecycle coordinator.
1240    pub fn on_background(&mut self) {
1241        self.set_background_frozen(true);
1242        self.set_loop_running(false);
1243    }
1244
1245    /// Records a double-back exit request or OS termination so subsequent re-entry recreates a fresh native handle.
1246    ///
1247    /// # Arguments
1248    ///
1249    /// - `&Self` - Mutable lifecycle coordinator.
1250    pub fn on_terminate(&mut self) {
1251        self.set_app_running(false);
1252        self.set_terminated(true);
1253        self.set_loop_running(false);
1254    }
1255
1256    /// Returns an immutable reference to the session's `TouchPointerTracker`.
1257    ///
1258    /// # Arguments
1259    ///
1260    /// - `&Self` - Lifecycle coordinator reference.
1261    ///
1262    /// # Returns
1263    ///
1264    /// - `&TouchPointerTracker` - Active touch tracker.
1265    #[must_use]
1266    pub fn touch_tracker(&self) -> &TouchPointerTracker {
1267        self.get_touch_tracker()
1268    }
1269
1270    /// Returns a mutable reference to the session's `TouchPointerTracker`.
1271    ///
1272    /// # Arguments
1273    ///
1274    /// - `&Self` - Mutable lifecycle coordinator.
1275    ///
1276    /// # Returns
1277    ///
1278    /// - `&mut TouchPointerTracker` - Mutable touch tracker.
1279    pub fn touch_tracker_mut(&mut self) -> &mut TouchPointerTracker {
1280        self.get_mut_touch_tracker()
1281    }
1282}