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