1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
use super::*;
/// Orientation classification helpers for `ScreenOrientation`.
impl ScreenOrientation {
/// Derives canonical `Portrait` or `Landscape` orientation from logical viewport dimensions.
///
/// # Arguments
///
/// - `f32` - Logical viewport width.
/// - `f32` - Logical viewport height.
///
/// # Returns
///
/// - `Self` - `Landscape` when `width > height`, otherwise `Portrait`.
#[must_use]
pub fn from_size(width: f32, height: f32) -> Self {
if width > height {
Self::Landscape
} else {
Self::Portrait
}
}
/// Returns `true` for any landscape orientation variant.
///
/// # Arguments
///
/// - `&Self` - Orientation reference.
///
/// # Returns
///
/// - `bool` - Whether orientation is horizontal.
#[must_use]
pub fn is_landscape(&self) -> bool {
matches!(
self,
Self::Landscape | Self::LandscapeLeft | Self::LandscapeRight
)
}
/// Returns `true` for any portrait orientation variant.
///
/// # Arguments
///
/// - `&Self` - Orientation reference.
///
/// # Returns
///
/// - `bool` - Whether orientation is vertical.
#[must_use]
pub fn is_portrait(&self) -> bool {
matches!(self, Self::Portrait | Self::PortraitUpsideDown)
}
}
/// Reachability helper methods for `NetworkStatus`.
impl NetworkStatus {
/// Returns `true` when network connectivity is available (`Online`, `Wifi`, or `Cellular`).
///
/// # Arguments
///
/// - `&Self` - Network status reference.
///
/// # Returns
///
/// - `bool` - Whether the host has an active online route.
#[must_use]
pub fn is_online(&self) -> bool {
matches!(self, Self::Online | Self::Wifi | Self::Cellular)
}
}
/// Marker trait enabling `SystemEvent` forwarding over `EventBus` when desired.
impl CustomEvent for SystemEvent {}
/// Manual early unregistration for `SystemEventSubscription`.
impl SystemEventSubscription {
/// Unregisters the associated system event listener immediately.
///
/// # Arguments
///
/// - `Self` - Subscription handle to cancel.
pub fn unsubscribe(self) {
let id: u64 = self.get_id();
let _: Result<(), _> = SYSTEM_EVENT_HUB.try_with(|cell: &RefCell<SystemEventHub>| {
if let Ok(mut hub) = cell.try_borrow_mut() {
hub.unregister(id);
}
});
}
}
/// Default upright portrait gravity sample for `DeviceMotionSample`.
impl Default for DeviceMotionSample {
/// Creates an upright stationary `DeviceMotionSample` with `(0.0, 9.80665, 0.0)` screen gravity.
///
/// # Returns
///
/// - `Self` - Default upright device motion sample with `sensor_active == false`.
fn default() -> Self {
Self {
gravity_x: 0.0,
gravity_y: STANDARD_GRAVITY_MPS2,
gravity_z: 0.0,
linear_accel_x: 0.0,
linear_accel_y: 0.0,
linear_accel_z: 0.0,
gyro_x: 0.0,
gyro_y: 0.0,
gyro_z: 0.0,
pitch_rad: 0.0,
roll_rad: 0.0,
yaw_rad: 0.0,
timestamp_ns: 0,
sensor_active: false,
}
}
}
/// Physical coordinate, orientation, and sanitization helpers for `DeviceMotionSample`.
impl DeviceMotionSample {
/// Returns an upright stationary `DeviceMotionSample` with standard Earth gravity along `+y`.
///
/// # Returns
///
/// - `Self` - Upright gravity sample (`0.0, 9.80665, 0.0`).
#[must_use]
pub fn upright() -> Self {
Self::default()
}
/// Constructs a sanitized screen-aligned `DeviceMotionSample` from grouped 3-axis gravity, linear acceleration, gyroscope, and attitude vectors.
///
/// # Arguments
///
/// - `[f32; 3]` - Screen-aligned gravity `[gx, gy, gz]` in `m/s²`.
/// - `[f32; 3]` - Screen-aligned linear shake acceleration `[lx, ly, lz]` in `m/s²`.
/// - `[f32; 3]` - Screen-aligned angular velocity `[wx, wy, wz]` in `rad/s`.
/// - `[f32; 3]` - Device attitude `[pitch_rad, roll_rad, yaw_rad]` in radians.
/// - `u64` - Monotonic sensor timestamp in nanoseconds.
/// - `bool` - Whether the sample comes from a live hardware sensor.
///
/// # Returns
///
/// - `Self` - Sanitized 6-DOF device motion sample.
#[must_use]
pub fn from_vectors(
gravity: [f32; 3],
linear_accel: [f32; 3],
gyro: [f32; 3],
attitude: [f32; 3],
timestamp_ns: u64,
sensor_active: bool,
) -> Self {
Self {
gravity_x: gravity[0],
gravity_y: gravity[1],
gravity_z: gravity[2],
linear_accel_x: linear_accel[0],
linear_accel_y: linear_accel[1],
linear_accel_z: linear_accel[2],
gyro_x: gyro[0],
gyro_y: gyro[1],
gyro_z: gyro[2],
pitch_rad: attitude[0],
roll_rad: attitude[1],
yaw_rad: attitude[2],
timestamp_ns,
sensor_active,
}
.sanitized()
}
/// Constructs a `DeviceMotionSample` from a screen-aligned gravity vector and derives `roll_rad` and `pitch_rad`.
///
/// # Arguments
///
/// - `f32` - Screen-right gravity component in `m/s²`.
/// - `f32` - Screen-down gravity component in `m/s²`.
/// - `f32` - Out-of-screen gravity component in `m/s²`.
///
/// # Returns
///
/// - `Self` - Sanitized sample with derived orientation angles.
#[must_use]
pub fn from_gravity(gx: f32, gy: f32, gz: f32) -> Self {
let sgx: f32 = sanitize_motion_scalar(gx, MAX_SENSOR_ACCEL_MPS2, 0.0);
let sgy: f32 = sanitize_motion_scalar(gy, MAX_SENSOR_ACCEL_MPS2, STANDARD_GRAVITY_MPS2);
let sgz: f32 = sanitize_motion_scalar(gz, MAX_SENSOR_ACCEL_MPS2, 0.0);
let roll_rad: f32 = sgx.atan2(sgy);
let planar: f32 = sgx.hypot(sgy);
let pitch_rad: f32 = (-sgz).atan2(planar);
Self {
gravity_x: sgx,
gravity_y: sgy,
gravity_z: sgz,
linear_accel_x: 0.0,
linear_accel_y: 0.0,
linear_accel_z: 0.0,
gyro_x: 0.0,
gyro_y: 0.0,
gyro_z: 0.0,
pitch_rad,
roll_rad,
yaw_rad: 0.0,
timestamp_ns: 0,
sensor_active: false,
}
}
/// Transforms natural-portrait device vectors (`+X` right, `+Y` up, `+Z` out-of-screen) by clockwise/CCW display rotation degrees (`0`, `90`, `180`, `270`) into screen-aligned `DeviceMotionSample` coordinates (`+x` right, `+y` down, `+z` out-of-screen).
///
/// `gravity_dev` must point downward in device coordinates (e.g. `(0, -9.80665, 0)` when upright portrait).
///
/// # Arguments
///
/// - `[f32; 3]` - Gravity vector in natural device `(+X_right, +Y_up, +Z_out)` `m/s²`.
/// - `[f32; 3]` - Linear acceleration in natural device `(+X_right, +Y_up, +Z_out)` `m/s²`.
/// - `[f32; 3]` - Angular velocity in natural device `(+X_right, +Y_up, +Z_out)` `rad/s`.
/// - `i32` - Display rotation angle in degrees (`0`, `90`, `180`, `270`, or `-90`).
/// - `u64` - Monotonic timestamp in nanoseconds.
///
/// # Returns
///
/// - `Self` - Sanitized screen-aligned `DeviceMotionSample` marked `sensor_active = true`.
#[must_use]
pub fn from_device_axes(
gravity_dev: [f32; 3],
linear_dev: [f32; 3],
gyro_dev: [f32; 3],
screen_angle_deg: i32,
timestamp_ns: u64,
) -> Self {
let [sgx, sgy_up, sgz]: [f32; 3] =
rotate_device_vec_to_screen_up(gravity_dev, screen_angle_deg);
let [slx, sly_up, slz]: [f32; 3] =
rotate_device_vec_to_screen_up(linear_dev, screen_angle_deg);
let [swx, swy_up, swz]: [f32; 3] =
rotate_device_vec_to_screen_up(gyro_dev, screen_angle_deg);
let gx: f32 = sgx;
let gy: f32 = -sgy_up;
let gz: f32 = sgz;
let lx: f32 = slx;
let ly: f32 = -sly_up;
let lz: f32 = slz;
let roll_rad: f32 = gx.atan2(gy);
let pitch_rad: f32 = (-gz).atan2(gx.hypot(gy));
Self {
gravity_x: gx,
gravity_y: gy,
gravity_z: gz,
linear_accel_x: lx,
linear_accel_y: ly,
linear_accel_z: lz,
gyro_x: swx,
gyro_y: swy_up,
gyro_z: swz,
pitch_rad,
roll_rad,
yaw_rad: 0.0,
timestamp_ns,
sensor_active: true,
}
.sanitized()
}
/// Returns a sanitized copy with non-finite values replaced and extreme sensor spikes clamped safely.
///
/// # Arguments
///
/// - `&Self` - Raw device motion sample.
///
/// # Returns
///
/// - `Self` - Sanitized finite sample.
#[must_use]
pub fn sanitized(&self) -> Self {
let gx: f32 = sanitize_motion_scalar(self.get_gravity_x(), MAX_SENSOR_ACCEL_MPS2, 0.0);
let gy: f32 = sanitize_motion_scalar(
self.get_gravity_y(),
MAX_SENSOR_ACCEL_MPS2,
STANDARD_GRAVITY_MPS2,
);
let gz: f32 = sanitize_motion_scalar(self.get_gravity_z(), MAX_SENSOR_ACCEL_MPS2, 0.0);
let lx: f32 = sanitize_motion_scalar(self.get_linear_accel_x(), MAX_SENSOR_ACCEL_MPS2, 0.0);
let ly: f32 = sanitize_motion_scalar(self.get_linear_accel_y(), MAX_SENSOR_ACCEL_MPS2, 0.0);
let lz: f32 = sanitize_motion_scalar(self.get_linear_accel_z(), MAX_SENSOR_ACCEL_MPS2, 0.0);
let wx: f32 = sanitize_motion_scalar(self.get_gyro_x(), MAX_SENSOR_GYRO_RAD_S, 0.0);
let wy: f32 = sanitize_motion_scalar(self.get_gyro_y(), MAX_SENSOR_GYRO_RAD_S, 0.0);
let wz: f32 = sanitize_motion_scalar(self.get_gyro_z(), MAX_SENSOR_GYRO_RAD_S, 0.0);
let pitch: f32 = sanitize_motion_scalar(self.get_pitch_rad(), TAU, 0.0);
let roll: f32 = sanitize_motion_scalar(self.get_roll_rad(), TAU, 0.0);
let yaw: f32 = sanitize_motion_scalar(self.get_yaw_rad(), TAU, 0.0);
Self {
gravity_x: gx,
gravity_y: gy,
gravity_z: gz,
linear_accel_x: lx,
linear_accel_y: ly,
linear_accel_z: lz,
gyro_x: wx,
gyro_y: wy,
gyro_z: wz,
pitch_rad: pitch,
roll_rad: roll,
yaw_rad: yaw,
timestamp_ns: self.get_timestamp_ns(),
sensor_active: self.get_sensor_active(),
}
}
/// Returns the in-screen gravity magnitude in `m/s²`.
///
/// # Arguments
///
/// - `&Self` - Device motion sample reference.
///
/// # Returns
///
/// - `f32` - Magnitude `sqrt(gx² + gy² + gz²)`.
#[must_use]
pub fn gravity_magnitude(&self) -> f32 {
let gx: f32 = self.get_gravity_x();
let gy: f32 = self.get_gravity_y();
let gz: f32 = self.get_gravity_z();
(gx * gx + gy * gy + gz * gz).sqrt()
}
}
/// Default active-foreground initial state for `SystemEventNormalizer`.
impl Default for SystemEventNormalizer {
/// Creates a `SystemEventNormalizer` initialized in `AppState::Active` and visible.
///
/// # Returns
///
/// - `Self` - Default normalizer state machine.
fn default() -> Self {
Self {
state: AppState::Active,
visible: true,
last_focused: None,
last_resize: None,
last_safe_area: None,
last_orientation: None,
last_theme: None,
last_locale: None,
last_keyboard: None,
last_low_power: None,
last_network: None,
last_device_motion: None,
}
}
}
/// Canonical cross-platform lifecycle normalization and deduplication state machine.
impl SystemEventNormalizer {
/// Creates a new `SystemEventNormalizer` starting in `AppState::Active`.
///
/// # Returns
///
/// - `Self` - Initialized state machine.
#[must_use]
pub fn new() -> Self {
Self::default()
}
/// Returns the current canonical `AppState`.
///
/// # Arguments
///
/// - `&Self` - Normalizer reference.
///
/// # Returns
///
/// - `AppState` - Active normalized application state.
#[must_use]
pub fn state(&self) -> AppState {
self.get_state()
}
/// Returns `true` when the active surface is currently visible.
///
/// # Arguments
///
/// - `&Self` - Normalizer reference.
///
/// # Returns
///
/// - `bool` - Whether `Appear` is active without a subsequent `Disappear`.
#[must_use]
pub fn is_visible(&self) -> bool {
self.get_visible()
}
/// Normalizes a raw platform `SystemEvent`, deduplicating redundant notifications and synthesizing missing transition edges.
///
/// # Arguments
///
/// - `&Self` - Mutable normalizer state machine.
/// - `SystemEvent` - Raw platform or synthetic system event.
///
/// # Returns
///
/// - `Vec<SystemEvent>` - Zero or more canonical events in strict cross-platform order.
pub fn normalize(&mut self, event: SystemEvent) -> Vec<SystemEvent> {
if self.get_state() == AppState::Terminated {
return Vec::new();
}
let mut out: Vec<SystemEvent> = Vec::with_capacity(3);
match event {
SystemEvent::Inactive => {
if self.get_state() == AppState::Active {
self.set_state(AppState::Inactive);
out.push(SystemEvent::Inactive);
}
}
SystemEvent::Disappear => {
if self.get_visible() {
if self.get_state() == AppState::Active {
self.set_state(AppState::Inactive);
out.push(SystemEvent::Inactive);
}
self.set_visible(false);
out.push(SystemEvent::Disappear);
}
}
SystemEvent::Background => {
if self.get_state() != AppState::Background {
if self.get_state() == AppState::Active {
self.set_state(AppState::Inactive);
out.push(SystemEvent::Inactive);
}
if self.get_visible() {
self.set_visible(false);
out.push(SystemEvent::Disappear);
}
self.set_state(AppState::Background);
out.push(SystemEvent::Background);
}
}
SystemEvent::Appear => {
if !self.get_visible() {
self.set_visible(true);
if self.get_state() == AppState::Background {
self.set_state(AppState::Inactive);
}
out.push(SystemEvent::Appear);
}
}
SystemEvent::Foreground => {
if self.get_state() != AppState::Active || !self.get_visible() {
if !self.get_visible() {
self.set_visible(true);
out.push(SystemEvent::Appear);
}
self.set_state(AppState::Active);
out.push(SystemEvent::Foreground);
}
}
SystemEvent::Terminate => {
if self.get_state() == AppState::Active {
out.push(SystemEvent::Inactive);
}
if self.get_visible() {
self.set_visible(false);
out.push(SystemEvent::Disappear);
}
self.set_state(AppState::Terminated);
out.push(SystemEvent::Terminate);
}
SystemEvent::FocusChanged(focused) => {
let prev: Option<bool> = {
let Self { last_focused, .. } = self;
*last_focused
};
if prev != Some(focused) {
self.set_last_focused(Some(focused));
out.push(SystemEvent::FocusChanged(focused));
}
}
SystemEvent::Resize {
width,
height,
scale_factor,
} => {
let w: f32 = width.max(1.0);
let h: f32 = height.max(1.0);
let s: f32 = if scale_factor.is_finite() {
scale_factor.clamp(0.5, 4.5)
} else {
1.0
};
let prev: Option<(f32, f32, f32)> = {
let Self { last_resize, .. } = self;
*last_resize
};
let changed: bool = match prev {
Some((pw, ph, ps)) => {
(pw - w).abs() > RESIZE_DEDUP_EPSILON
|| (ph - h).abs() > RESIZE_DEDUP_EPSILON
|| (ps - s).abs() > RESIZE_DEDUP_EPSILON
}
None => true,
};
if changed {
self.set_last_resize(Some((w, h, s)));
out.push(SystemEvent::Resize {
width: w,
height: h,
scale_factor: s,
});
let derived_orient: ScreenOrientation = ScreenOrientation::from_size(w, h);
let prev_orient: Option<ScreenOrientation> = {
let Self {
last_orientation, ..
} = self;
*last_orientation
};
let orient_changed: bool = match prev_orient {
Some(po) => po.is_landscape() != derived_orient.is_landscape(),
None => false,
};
if prev_orient.is_none() {
self.set_last_orientation(Some(derived_orient));
} else if orient_changed {
self.set_last_orientation(Some(derived_orient));
out.push(SystemEvent::OrientationChanged(derived_orient));
}
}
}
SystemEvent::SafeAreaChanged(insets) => {
let prev: Option<SafeAreaInsets> = {
let Self { last_safe_area, .. } = self;
*last_safe_area
};
if prev != Some(insets) {
self.set_last_safe_area(Some(insets));
out.push(SystemEvent::SafeAreaChanged(insets));
}
}
SystemEvent::OrientationChanged(orient) => {
let prev: Option<ScreenOrientation> = {
let Self {
last_orientation, ..
} = self;
*last_orientation
};
if prev != Some(orient) {
self.set_last_orientation(Some(orient));
out.push(SystemEvent::OrientationChanged(orient));
}
}
SystemEvent::ThemeChanged(theme) => {
let prev: Option<ThemeMode> = {
let Self { last_theme, .. } = self;
*last_theme
};
if prev != Some(theme) {
self.set_last_theme(Some(theme));
out.push(SystemEvent::ThemeChanged(theme));
}
}
SystemEvent::LocaleChanged(locale) => {
let trimmed: String = locale.trim().to_string();
if !trimmed.is_empty() {
let same: bool = {
let Self { last_locale, .. } = self;
last_locale.as_deref() == Some(trimmed.as_str())
};
if !same {
self.set_last_locale(Some(trimmed.clone()));
out.push(SystemEvent::LocaleChanged(trimmed));
}
}
}
SystemEvent::KeyboardVisibilityChanged { visible, height } => {
let norm_h: f32 = if visible && height.is_finite() {
height.max(0.0)
} else {
0.0
};
let prev: Option<(bool, f32)> = {
let Self { last_keyboard, .. } = self;
*last_keyboard
};
let changed: bool = match prev {
Some((pv, ph)) => {
pv != visible || (ph - norm_h).abs() > KEYBOARD_HEIGHT_EPSILON
}
None => true,
};
if changed {
self.set_last_keyboard(Some((visible, norm_h)));
out.push(SystemEvent::KeyboardVisibilityChanged {
visible,
height: norm_h,
});
}
}
SystemEvent::LowPowerModeChanged(enabled) => {
let prev: Option<bool> = {
let Self { last_low_power, .. } = self;
*last_low_power
};
if prev != Some(enabled) {
self.set_last_low_power(Some(enabled));
out.push(SystemEvent::LowPowerModeChanged(enabled));
}
}
SystemEvent::NetworkStatusChanged(status) => {
let prev: Option<NetworkStatus> = {
let Self { last_network, .. } = self;
*last_network
};
if prev != Some(status) {
self.set_last_network(Some(status));
out.push(SystemEvent::NetworkStatusChanged(status));
}
}
SystemEvent::MemoryWarning(pressure) => {
out.push(SystemEvent::MemoryWarning(pressure));
}
SystemEvent::BackPressed => {
out.push(SystemEvent::BackPressed);
}
SystemEvent::DeepLink(uri) => {
if !uri.is_empty() {
out.push(SystemEvent::DeepLink(uri));
}
}
SystemEvent::ClipboardChanged => {
out.push(SystemEvent::ClipboardChanged);
}
SystemEvent::DeviceMotion(sample) => {
let clean: DeviceMotionSample = sample.sanitized();
self.set_last_device_motion(Some(clean));
out.push(SystemEvent::DeviceMotion(clean));
}
}
out
}
}
/// Scoped listener registration, unregistration, and snapshot dispatch for `SystemEventHub`.
impl SystemEventHub {
/// Registers a listener callback owned by `owner_scope` and returns its unique identifier.
///
/// # Arguments
///
/// - `&Self` - Mutable system event hub.
/// - `Option<ScopeId>` - Enclosing reactive scope identifier, if any.
/// - `SystemEventCallback` - Type-erased callback handle.
///
/// # Returns
///
/// - `u64` - Unique listener identifier.
pub(crate) fn register(
&mut self,
owner_scope: Option<ScopeId>,
callback: SystemEventCallback,
) -> u64 {
let Self { next_id, listeners } = self;
*next_id = next_id.wrapping_add(1).max(1);
let assigned: u64 = *next_id;
listeners.push(SystemEventListener {
id: assigned,
owner_scope,
callback,
});
assigned
}
/// Removes the listener matching `id`, if still present.
///
/// # Arguments
///
/// - `&Self` - Mutable system event hub.
/// - `u64` - Listener identifier to remove.
pub(crate) fn unregister(&mut self, id: u64) {
let Self { listeners, .. } = self;
listeners.retain(|entry: &SystemEventListener| entry.id != id);
}
/// Removes all registered listeners and resets the identifier counter.
///
/// # Arguments
///
/// - `&Self` - Mutable system event hub.
pub(crate) fn clear(&mut self) {
let Self { next_id, listeners } = self;
listeners.clear();
*next_id = 0;
}
/// Clones callbacks for all non-frozen listeners so invocation happens outside any hub borrow.
///
/// # Arguments
///
/// - `&Self` - System event hub reference.
///
/// # Returns
///
/// - `Vec<SystemEventCallback>` - Ordered active callbacks ready to execute.
#[must_use]
pub(crate) fn snapshot_active(&self) -> Vec<SystemEventCallback> {
let Self { listeners, .. } = self;
if listeners.is_empty() {
return Vec::new();
}
with_runtime(
|rt: &mut ReactiveRuntime| {
let mut out: Vec<SystemEventCallback> = Vec::with_capacity(listeners.len());
for entry in listeners.iter() {
let is_frozen: bool = entry
.owner_scope
.map(|sid: ScopeId| rt.is_scope_effectively_frozen(sid))
.unwrap_or(false);
if !is_frozen {
out.push(Rc::clone(&entry.callback));
}
}
out
},
Vec::new(),
)
}
/// Clones callbacks for listeners owned by any scope in `scopes` (or descendant scopes thereof).
///
/// # Arguments
///
/// - `&Self` - System event hub reference.
/// - `&[ScopeId]` - Target subtree root scope identifiers.
///
/// # Returns
///
/// - `Vec<SystemEventCallback>` - Matching callbacks in registration order.
#[must_use]
pub(crate) fn snapshot_for_scopes(&self, scopes: &[ScopeId]) -> Vec<SystemEventCallback> {
let Self { listeners, .. } = self;
if listeners.is_empty() || scopes.is_empty() {
return Vec::new();
}
with_runtime(
|rt: &mut ReactiveRuntime| {
let mut out: Vec<SystemEventCallback> = Vec::new();
for entry in listeners.iter() {
if let Some(owner) = entry.owner_scope
&& scopes
.iter()
.any(|root_scope: &ScopeId| rt.is_scope_in_subtree(owner, *root_scope))
{
out.push(Rc::clone(&entry.callback));
}
}
out
},
Vec::new(),
)
}
}