1
//! Sensor manager — cross-platform state for the motion-sensor surface
2
//! (`SUPER_PLAN_2` §1 feature 5 + research/03).
3
//!
4
//! Continuous + push-driven, like geolocation:
5
//!
6
//! - The **platform backend** (`dll/src/desktop/extra/sensors/<plat>.rs`) subscribes to
7
//!   `CoreMotion` (`CMMotionManager`) / Android `SensorManager` and calls [`push_sensor_reading`]
8
//!   on every sample (arbitrary thread).
9
//! - The dll **layout pass** drains the channel via [`drain_sensor_readings`] and folds each into
10
//!   the manager through [`SensorManager::set_reading`].
11
//! - **Callbacks** read `reading(kind)` synchronously (via `CallbackInfo::get_sensor_reading`) to
12
//!   drive tilt / shake / compass UI.
13
//!
14
//! One reading slot per [`SensorKind`]. No platform deps
15
//! (`SUPER_PLAN_2` §0.5); the channel mirrors `geolocation.rs` verbatim.
16

            
17
use alloc::vec::Vec;
18

            
19
pub use azul_core::sensors::{SensorKind, SensorReading};
20
use azul_core::{
21
    dom::DomNodeId,
22
    events::{EventData, EventProvider, EventSource as CoreEventSource, EventType, SyntheticEvent},
23
    task::Instant,
24
};
25

            
26
/// Cross-platform sensor state. One per `App` — the OS exposes a single
27
/// per-process sensor subscription, not per-window.
28
#[derive(Copy, Debug, Clone, PartialEq, Default)]
29
pub struct SensorManager {
30
    /// Latest reading per kind, indexed by `SensorKind::slot()`.
31
    ///
32
    /// An array rather than a field per kind: the set went from 3 to 11 when
33
    /// the derived sensors landed, and one field each would have meant a new
34
    /// field, two match arms and an accessor per addition.
35
    pub readings: [Option<SensorReading>; SensorKind::COUNT],
36
    /// The typed proximity answer (8e-i-a-i, 8e-i-a-ii): Near / Far from a
37
    /// binary sensor, a distance from a ranging one. Separate from the
38
    /// `Proximity` reading slot, which keeps the raw centimetres where a
39
    /// platform reports them, because an `(x, y, z)` triple cannot say
40
    /// "far" without inventing a number for it.
41
    pub proximity: Option<azul_core::sensors::Proximity>,
42
    /// `true` when a reading advanced since the last event-pass drain. Set by
43
    /// [`set_reading`](Self::set_reading), read by the `EventProvider` impl,
44
    /// cleared by [`clear_pending_event`](Self::clear_pending_event).
45
    pub pending_event: bool,
46
    /// `true` while any node in the current layout registers a
47
    /// `SensorChanged` callback (Hover or Window filter). Recomputed on every
48
    /// relayout by the DOM walk in `shell2::common::layout`; the capability
49
    /// pump polls the platform sensor backend only while this is set
50
    /// (MWA-A1 arming signal — no listeners, no polling, no timer).
51
    pub has_listeners: bool,
52
}
53

            
54
impl SensorManager {
55
    #[must_use]
56
7770
    pub fn new() -> Self {
57
7770
        Self::default()
58
7770
    }
59

            
60
    /// Latest reading for `kind`, or `None` if no backend has delivered one.
61
    #[must_use]
62
177
    pub const fn reading(&self, kind: SensorKind) -> Option<SensorReading> {
63
177
        self.readings[kind.slot()]
64
177
    }
65

            
66
    /// Apply a reading the backend delivered. Returns `true` if it advanced
67
    /// (bit-pattern different from the previous, so missing-as-`NaN` axes
68
    /// don't make every sample look "changed").
69
351
    pub fn set_reading(&mut self, reading: SensorReading) -> bool {
70
351
        let slot = &mut self.readings[reading.kind.slot()];
71
351
        let changed = slot
72
351
            .as_mut()
73
351
            .is_none_or(|prev| !reading_bitwise_eq(prev, &reading));
74
351
        *slot = Some(reading);
75
351
        if changed {
76
218
            self.pending_event = true;
77
218
        }
78
351
        changed
79
351
    }
80

            
81
    #[must_use]
82
    pub const fn proximity(&self) -> Option<azul_core::sensors::Proximity> {
83
        self.proximity
84
    }
85

            
86
    /// Record the typed proximity answer; a change raises `SensorChanged`
87
    /// like any reading. Returns whether it changed.
88
    pub fn set_proximity(&mut self, proximity: azul_core::sensors::Proximity) -> bool {
89
        let changed = self.proximity != Some(proximity);
90
        self.proximity = Some(proximity);
91
        if changed {
92
            self.pending_event = true;
93
        }
94
        changed
95
    }
96

            
97
    /// Clear the pending-event flag. The dll calls this after the event pass
98
    /// has collected the `SensorChanged` event (mirrors `clear_changeset`).
99
149
    pub const fn clear_pending_event(&mut self) {
100
149
        self.pending_event = false;
101
149
    }
102

            
103
    /// Relayout walk reports whether any node listens for `SensorChanged`.
104
9
    pub const fn set_has_listeners(&mut self, has: bool) {
105
9
        self.has_listeners = has;
106
9
    }
107

            
108
    /// `true` while the capability pump should poll the sensor backend.
109
    #[must_use]
110
14
    pub const fn has_listeners(&self) -> bool {
111
14
        self.has_listeners
112
14
    }
113
}
114

            
115
impl EventProvider for SensorManager {
116
    /// Yield a window-level `SensorChanged` event when a reading advanced
117
    /// since the last drain (target = root; read the value via
118
    /// `CallbackInfo::get_sensor_reading` inside the callback).
119
170
    fn get_pending_events(&self, timestamp: Instant) -> Vec<SyntheticEvent> {
120
170
        if self.pending_event {
121
14
            alloc::vec![SyntheticEvent::new(
122
14
                EventType::SensorChanged,
123
14
                CoreEventSource::User,
124
                DomNodeId::ROOT,
125
14
                timestamp,
126
14
                EventData::None,
127
            )]
128
        } else {
129
156
            Vec::new()
130
        }
131
170
    }
132
}
133

            
134
15794
fn reading_bitwise_eq(a: &SensorReading, b: &SensorReading) -> bool {
135
15794
    a.kind == b.kind
136
5424
        && a.x.to_bits() == b.x.to_bits()
137
652
        && a.y.to_bits() == b.y.to_bits()
138
648
        && a.z.to_bits() == b.z.to_bits()
139
644
        && a.timestamp_ms == b.timestamp_ms
140
15794
}
141

            
142
// ────────── Async reading channel (platform backend → manager) ─────────
143
//
144
// CoreMotion / Android `SensorManager` deliver on an arbitrary thread with
145
// no handle to the live `SensorManager` (inside the window's
146
// `LayoutWindow`). The backend parks each reading here; the layout pass
147
// drains it and applies the latest per kind. Pure Rust — no platform
148
// dependency (SUPER_PLAN_2 §0.5). Mirrors the geolocation fix channel.
149

            
150
/// The channel, as a VALUE: a readings queue and a latest-wins proximity slot.
151
///
152
/// Mirrors `hid::HidChannel` — a struct so the process-wide instance
153
/// (`CHANNEL`) is an instance, and a test can own its own instead of sharing
154
/// a global with every other test in the binary.
155
#[derive(Debug, Default)]
156
pub struct SensorChannel {
157
    pending_readings: std::sync::Mutex<Vec<SensorReading>>,
158
    /// The typed proximity answer, LATEST-WINS rather than queued: proximity
159
    /// is a state, and a widget wants the current one, not every flicker
160
    /// between two polls.
161
    pending_proximity: std::sync::Mutex<Option<azul_core::sensors::Proximity>>,
162
}
163

            
164
/// The process-wide channel the dll backends push into and the engine drains.
165
static CHANNEL: SensorChannel = SensorChannel::new();
166

            
167
impl SensorChannel {
168
    /// An empty channel. `const` so the process-wide one can be a `static`.
169
    #[must_use]
170
1
    pub const fn new() -> Self {
171
1
        Self {
172
1
            pending_readings: std::sync::Mutex::new(Vec::new()),
173
1
            pending_proximity: std::sync::Mutex::new(None),
174
1
        }
175
1
    }
176

            
177
    /// Park a reading. Thread-safe; poison-recovering.
178
13
    pub fn push_reading(&self, reading: SensorReading) {
179
13
        let mut q = self
180
13
            .pending_readings
181
13
            .lock()
182
13
            .unwrap_or_else(std::sync::PoisonError::into_inner);
183
13
        q.push(reading);
184
13
    }
185

            
186
    /// Drain every parked reading, in arrival order.
187
    #[must_use]
188
32
    pub fn drain_readings(&self) -> Vec<SensorReading> {
189
32
        let mut q = self
190
32
            .pending_readings
191
32
            .lock()
192
32
            .unwrap_or_else(std::sync::PoisonError::into_inner);
193
32
        core::mem::take(&mut *q)
194
32
    }
195

            
196
    /// Backend side: publish the current proximity answer.
197
    pub fn push_proximity(&self, proximity: azul_core::sensors::Proximity) {
198
        if let Ok(mut slot) = self.pending_proximity.lock() {
199
            *slot = Some(proximity);
200
        }
201
    }
202

            
203
    /// Engine side: take the latest published answer, if any.
204
    #[must_use]
205
    pub fn take_proximity(&self) -> Option<azul_core::sensors::Proximity> {
206
        self.pending_proximity
207
            .lock()
208
            .ok()
209
            .and_then(|mut slot| slot.take())
210
    }
211
}
212

            
213
/// Park a sensor reading delivered by a platform backend (in the dll).
214
/// Thread-safe; poison-recovering.
215
10
pub fn push_sensor_reading(reading: SensorReading) {
216
10
    CHANNEL.push_reading(reading);
217
10
}
218

            
219
/// Drain every reading parked by [`push_sensor_reading`], in arrival order.
220
/// Called once per layout pass; the caller applies them through
221
/// [`SensorManager::set_reading`] (the last per kind wins).
222
31
pub fn drain_sensor_readings() -> Vec<SensorReading> {
223
31
    CHANNEL.drain_readings()
224
31
}
225

            
226
/// Backend side: publish the current proximity answer.
227
pub fn push_proximity(proximity: azul_core::sensors::Proximity) {
228
    CHANNEL.push_proximity(proximity);
229
}
230

            
231
/// Engine side: take the latest published answer, if any.
232
pub fn take_proximity() -> Option<azul_core::sensors::Proximity> {
233
    CHANNEL.take_proximity()
234
}
235

            
236
#[cfg(test)]
237
mod tests {
238
    use super::*;
239

            
240
    #[test]
241
1
    fn listener_flag_gates_polling_decision() {
242
1
        let mut mgr = SensorManager::new();
243
1
        assert!(
244
1
            !mgr.has_listeners(),
245
            "no listeners until the relayout walk reports some"
246
        );
247
1
        mgr.set_has_listeners(true);
248
1
        assert!(mgr.has_listeners());
249
1
        mgr.set_has_listeners(false);
250
1
        assert!(!mgr.has_listeners());
251
1
    }
252

            
253
8
    fn r(kind: SensorKind, x: f32, y: f32, z: f32) -> SensorReading {
254
8
        SensorReading {
255
8
            kind,
256
8
            x,
257
8
            y,
258
8
            z,
259
8
            timestamp_ms: 0,
260
8
        }
261
8
    }
262

            
263
    #[test]
264
1
    fn manager_defaults_to_no_readings() {
265
1
        let mgr = SensorManager::new();
266
1
        assert_eq!(mgr.reading(SensorKind::Accelerometer), None);
267
1
        assert_eq!(mgr.reading(SensorKind::Gyroscope), None);
268
1
        assert_eq!(mgr.reading(SensorKind::Magnetometer), None);
269
1
    }
270

            
271
    #[test]
272
1
    fn set_reading_routes_by_kind_and_flags_change() {
273
1
        let mut mgr = SensorManager::new();
274
1
        assert!(mgr.set_reading(r(SensorKind::Accelerometer, 0.0, 0.0, 9.81)));
275
        // Only the accelerometer slot is filled.
276
1
        assert!(mgr.reading(SensorKind::Accelerometer).is_some());
277
1
        assert_eq!(mgr.reading(SensorKind::Gyroscope), None);
278
        // Same value again — no change.
279
1
        assert!(!mgr.set_reading(r(SensorKind::Accelerometer, 0.0, 0.0, 9.81)));
280
        // Different value — change.
281
1
        assert!(mgr.set_reading(r(SensorKind::Accelerometer, 1.0, 0.0, 9.81)));
282
        // A different kind fills its own slot.
283
1
        assert!(mgr.set_reading(r(SensorKind::Gyroscope, 0.1, 0.0, 0.0)));
284
1
        assert_eq!(mgr.reading(SensorKind::Gyroscope).map(|r| r.x), Some(0.1));
285
1
    }
286

            
287
    #[test]
288
1
    fn magnitude_of_resting_accelerometer() {
289
1
        let g = r(SensorKind::Accelerometer, 0.0, 0.0, 9.81);
290
1
        assert!((g.magnitude() - 9.81).abs() < 1e-4);
291
1
    }
292

            
293
    #[test]
294
1
    fn readings_round_trip_through_manager() {
295
        // Own the channel rather than sharing the process-wide one with every
296
        // other test in the binary (the HID mirror of this test raced).
297
1
        let ch = SensorChannel::new();
298
1
        ch.push_reading(r(SensorKind::Accelerometer, 1.0, 2.0, 3.0));
299
1
        ch.push_reading(r(SensorKind::Accelerometer, 4.0, 5.0, 6.0)); // last wins per kind
300
1
        ch.push_reading(r(SensorKind::Magnetometer, 20.0, 0.0, 40.0));
301
1
        let drained = ch.drain_readings();
302
1
        assert_eq!(drained.len(), 3, "all parked readings drain in order");
303

            
304
1
        let mut mgr = SensorManager::new();
305
4
        for reading in &drained {
306
3
            mgr.set_reading(*reading);
307
3
        }
308
1
        assert_eq!(
309
1
            mgr.reading(SensorKind::Accelerometer).map(|r| r.x),
310
            Some(4.0),
311
            "the last accelerometer reading wins"
312
        );
313
1
        assert_eq!(
314
1
            mgr.reading(SensorKind::Magnetometer).map(|r| r.z),
315
            Some(40.0)
316
        );
317

            
318
1
        assert!(drain_sensor_readings().is_empty());
319
1
    }
320
}
321

            
322
#[cfg(test)]
323
#[allow(clippy::float_cmp, clippy::eq_op)] // bit-exactness IS the invariant under test
324
mod autotest_generated {
325
    // Imported explicitly (not just via the `super::*` glob) so the trait
326
    // method `get_pending_events` and `Vec` resolve regardless of how the
327
    // parent's own imports are re-exported.
328
    use alloc::vec::Vec;
329

            
330
    use azul_core::{
331
        dom::DomNodeId,
332
        events::{EventProvider, EventType},
333
        task::{Instant, SystemTick},
334
    };
335

            
336
    use super::*;
337

            
338
    // ─────────────────────────── helpers ────────────────────────────
339
    //
340
    // NOTE — a test that needs a channel constructs its own `SensorChannel`
341
    // (see `tests::readings_round_trip_through_manager`). The process-wide
342
    // `CHANNEL` behind `push_sensor_reading` / `drain_sensor_readings` is
343
    // shared with every other test in this binary on the parallel runner,
344
    // so pushing into or draining it from a test is how one test's readings
345
    // end up in another's exact-count assertion. That used to be the reason
346
    // this section avoided the channel entirely; owning one is the fix.
347

            
348
    const KINDS: [SensorKind; 3] = [
349
        SensorKind::Accelerometer,
350
        SensorKind::Gyroscope,
351
        SensorKind::Magnetometer,
352
    ];
353

            
354
    const fn r(kind: SensorKind, x: f32, y: f32, z: f32, timestamp_ms: u64) -> SensorReading {
355
        SensorReading {
356
            kind,
357
            x,
358
            y,
359
            z,
360
            timestamp_ms,
361
        }
362
    }
363

            
364
    /// A representative "real sample" — every field distinct and non-zero, so
365
    /// knocking out a single field flips exactly one comparison.
366
    const fn base() -> SensorReading {
367
        r(SensorKind::Accelerometer, 1.5, -2.25, 9.81, 1_234)
368
    }
369

            
370
    /// The shape `set_reading` documents as its reason for comparing bit
371
    /// patterns: a backend that reports "axis missing" as `NaN`.
372
    const fn nan_sample(kind: SensorKind) -> SensorReading {
373
        r(kind, f32::NAN, f32::NAN, f32::NAN, 7)
374
    }
375

            
376
    fn tick() -> Instant {
377
        Instant::Tick(SystemTick::new(0))
378
    }
379

            
380
    /// The smallest possible perturbation of a finite float: flip the lowest
381
    /// mantissa bit. The result is a *different* bit pattern by construction,
382
    /// so "did this sample advance?" must answer yes for it.
383
    fn ulp_flip(v: f32) -> f32 {
384
        f32::from_bits(v.to_bits() ^ 1)
385
    }
386

            
387
    /// Every field of a `SensorReading`, compared bit-for-bit — the property
388
    /// the manager promises when it stores a sample.
389
    fn bits_identical(a: &SensorReading, b: &SensorReading) -> bool {
390
        a.kind == b.kind
391
            && a.x.to_bits() == b.x.to_bits()
392
            && a.y.to_bits() == b.y.to_bits()
393
            && a.z.to_bits() == b.z.to_bits()
394
            && a.timestamp_ms == b.timestamp_ms
395
    }
396

            
397
    /// Float values that break naive `==` comparisons: both zeroes, both
398
    /// infinities, two distinct NaN bit patterns, the subnormal floor and the
399
    /// finite extremes.
400
    fn hostile_floats() -> [f32; 12] {
401
        [
402
            0.0,
403
            -0.0,
404
            1.0,
405
            -1.0,
406
            f32::MIN_POSITIVE,
407
            f32::from_bits(1), // smallest subnormal
408
            f32::MAX,
409
            f32::MIN,
410
            f32::INFINITY,
411
            f32::NEG_INFINITY,
412
            f32::NAN,
413
            f32::from_bits(0xffc0_0000), // negative NaN
414
        ]
415
    }
416

            
417
    // ───────────────────── SensorManager::new (constructor) ─────────────────
418

            
419
    /// no_panic + invariants_hold: a fresh manager has no readings, no pending
420
    /// event and no listeners — the "cold start, don't poll the backend" state.
421
    #[test]
422
    fn new_starts_cold_and_matches_default() {
423
        let mgr = SensorManager::new();
424
        for kind in KINDS {
425
            assert_eq!(mgr.reading(kind), None, "{kind:?} slot must start empty");
426
        }
427
        assert!(
428
            !mgr.pending_event,
429
            "no event may be pending before any sample"
430
        );
431
        assert!(
432
            !mgr.has_listeners(),
433
            "polling must not be armed at construction"
434
        );
435
        assert_eq!(mgr, SensorManager::default(), "new() must equal Default");
436
        assert_eq!(mgr, SensorManager::new(), "new() must be deterministic");
437
    }
438

            
439
    // ───────────────────────── reading (accessor) ───────────────────────────
440

            
441
    /// invariant: the three slots are independent — writing one kind must not
442
    /// make any other kind report a reading.
443
    #[test]
444
    fn reading_slots_are_independent_per_kind() {
445
        for written in KINDS {
446
            let mut mgr = SensorManager::new();
447
            assert!(mgr.set_reading(r(written, 1.0, 2.0, 3.0, 0)));
448
            for probed in KINDS {
449
                if probed == written {
450
                    assert_eq!(
451
                        mgr.reading(probed).map(|s| s.kind),
452
                        Some(written),
453
                        "{written:?} must land in its own slot, tagged with its kind"
454
                    );
455
                } else {
456
                    assert_eq!(
457
                        mgr.reading(probed),
458
                        None,
459
                        "writing {written:?} must not leak into the {probed:?} slot"
460
                    );
461
                }
462
            }
463
        }
464
    }
465

            
466
    /// invariant: `reading` hands back a *copy* (`SensorReading: Copy`), so a
467
    /// caller mutating it cannot corrupt the manager's stored sample.
468
    #[test]
469
    fn reading_returns_a_copy_not_an_alias() {
470
        let mut mgr = SensorManager::new();
471
        mgr.set_reading(base());
472
        let mut got = mgr.reading(SensorKind::Accelerometer).unwrap();
473
        got.x = -999.0;
474
        got.timestamp_ms = u64::MAX;
475
        assert_eq!(
476
            mgr.reading(SensorKind::Accelerometer),
477
            Some(base()),
478
            "mutating the returned copy must not write through to the manager"
479
        );
480
    }
481

            
482
    // ──────────────────────────── set_reading ───────────────────────────────
483

            
484
    /// The headline case from the doc comment: an all-`NaN` sample repeated
485
    /// verbatim must NOT look like it advanced. Under `PartialEq` every NaN
486
    /// compares unequal, so a naive `prev != new` would report a change on
487
    /// *every* sample and wake the event pass forever.
488
    #[test]
489
    fn repeated_nan_sample_does_not_advance() {
490
        for kind in KINDS {
491
            let mut mgr = SensorManager::new();
492
            let sample = nan_sample(kind);
493

            
494
            assert!(
495
                mgr.set_reading(sample),
496
                "{kind:?}: the first sample always advances (slot was empty)"
497
            );
498
            assert!(
499
                !mgr.set_reading(sample),
500
                "{kind:?}: an identical NaN sample must not be reported as changed"
501
            );
502
            assert!(
503
                !mgr.set_reading(sample),
504
                "{kind:?}: still no change on the third identical NaN sample"
505
            );
506

            
507
            // And the derived `PartialEq` really would have disagreed:
508
            let stored = mgr.reading(kind).unwrap();
509
            assert!(
510
                stored != sample,
511
                "{kind:?}: sanity — NaN fields make PartialEq report inequality, which is exactly \
512
                 why set_reading must compare bit patterns"
513
            );
514
        }
515
    }
516

            
517
    /// no_panic + invariant: the first sample into an empty slot always counts
518
    /// as an advance, even when every axis is NaN or infinite.
519
    #[test]
520
    fn first_sample_always_advances() {
521
        for kind in KINDS {
522
            for v in hostile_floats() {
523
                let mut mgr = SensorManager::new();
524
                assert!(
525
                    mgr.set_reading(r(kind, v, v, v, 0)),
526
                    "{kind:?}: first sample ({v:?}) must advance"
527
                );
528
                assert!(mgr.pending_event, "{kind:?}: an advance must arm the event");
529
            }
530
        }
531
    }
532

            
533
    /// round-trip: whatever is stored comes back bit-for-bit — NaN payloads,
534
    /// signed zeroes, infinities, subnormals, `u64::MAX` timestamps included.
535
    /// A resend of that exact sample is then correctly reported as *no* change.
536
    #[test]
537
    fn extremes_round_trip_bit_exactly_and_resend_is_idempotent() {
538
        for kind in KINDS {
539
            for x in hostile_floats() {
540
                for ts in [0_u64, 1, u64::MAX] {
541
                    let sample = r(kind, x, -x, x, ts);
542
                    let mut mgr = SensorManager::new();
543

            
544
                    assert!(mgr.set_reading(sample));
545
                    let stored = mgr.reading(kind).expect("just written");
546
                    assert!(
547
                        bits_identical(&stored, &sample),
548
                        "{kind:?}: stored sample must be bit-identical to the input (x = {x:?}, \
549
                         ts = {ts})"
550
                    );
551
                    assert!(
552
                        !mgr.set_reading(sample),
553
                        "{kind:?}: resending the identical sample must not advance (x = {x:?}, ts \
554
                         = {ts})"
555
                    );
556
                }
557
            }
558
        }
559
    }
560

            
561
    /// Every mutable field must be watched, down to the last mantissa bit.
562
    /// Perturbing x, y, z (by one ULP) or the timestamp alone has to register
563
    /// as an advance — a comparison that skipped one field would silently
564
    /// swallow that sensor axis.
565
    #[test]
566
    fn a_change_in_any_single_field_advances() {
567
        let mut with_x = base();
568
        with_x.x = ulp_flip(base().x);
569
        let mut with_y = base();
570
        with_y.y = ulp_flip(base().y);
571
        let mut with_z = base();
572
        with_z.z = ulp_flip(base().z);
573
        let mut with_ts = base();
574
        with_ts.timestamp_ms = base().timestamp_ms + 1;
575

            
576
        for (field, mutated) in [
577
            ("x", with_x),
578
            ("y", with_y),
579
            ("z", with_z),
580
            ("timestamp_ms", with_ts),
581
        ] {
582
            let mut mgr = SensorManager::new();
583
            assert!(mgr.set_reading(base()));
584
            assert!(
585
                mgr.set_reading(mutated),
586
                "a change in `{field}` alone must be reported as an advance"
587
            );
588
            assert!(
589
                !mgr.set_reading(mutated),
590
                "`{field}`: the mutated sample is now the previous one"
591
            );
592
            assert!(
593
                mgr.set_reading(base()),
594
                "`{field}`: reverting back to the original is also an advance"
595
            );
596
        }
597
    }
598

            
599
    /// Bit-pattern comparison, not numeric: `-0.0 == 0.0` is *true* for floats,
600
    /// but the two are different samples and must be reported as an advance.
601
    #[test]
602
    fn signed_zero_flip_advances_even_though_it_compares_equal() {
603
        assert_eq!(0.0_f32, -0.0_f32, "sanity: the two zeroes compare equal");
604

            
605
        let mut mgr = SensorManager::new();
606
        let pos = r(SensorKind::Gyroscope, 0.0, 0.0, 0.0, 0);
607
        let neg = r(SensorKind::Gyroscope, -0.0, 0.0, 0.0, 0);
608

            
609
        assert!(mgr.set_reading(pos));
610
        assert!(
611
            mgr.set_reading(neg),
612
            "+0.0 → -0.0 differs in bits and must count as an advance"
613
        );
614
        assert!(!mgr.set_reading(neg), "…but the same -0.0 twice must not");
615
        assert!(
616
            mgr.reading(SensorKind::Gyroscope)
617
                .is_some_and(|s| s.x.is_sign_negative()),
618
            "the -0.0 must actually be the stored value"
619
        );
620
    }
621

            
622
    /// Distinct NaN payloads are distinct samples; the same payload is not.
623
    #[test]
624
    fn distinct_nan_payloads_advance_but_identical_ones_do_not() {
625
        let quiet = f32::NAN;
626
        let other = f32::from_bits(quiet.to_bits() | 1); // different payload
627
        let negative = f32::from_bits(0xffc0_0000); // sign bit set
628
        assert!(quiet.is_nan() && other.is_nan() && negative.is_nan());
629

            
630
        let mut mgr = SensorManager::new();
631
        assert!(mgr.set_reading(r(SensorKind::Magnetometer, quiet, 0.0, 0.0, 0)));
632
        assert!(
633
            mgr.set_reading(r(SensorKind::Magnetometer, other, 0.0, 0.0, 0)),
634
            "a different NaN payload is a different bit pattern → advance"
635
        );
636
        assert!(
637
            mgr.set_reading(r(SensorKind::Magnetometer, negative, 0.0, 0.0, 0)),
638
            "a sign-flipped NaN is a different bit pattern → advance"
639
        );
640
        assert!(
641
            !mgr.set_reading(r(SensorKind::Magnetometer, negative, 0.0, 0.0, 0)),
642
            "the very same NaN bit pattern → no advance"
643
        );
644
    }
645

            
646
    /// invariant: the sample's own `kind` picks the slot, whatever was written
647
    /// before — a gyroscope sample can never overwrite the accelerometer.
648
    #[test]
649
    fn set_reading_routes_strictly_by_kind() {
650
        let mut mgr = SensorManager::new();
651
        mgr.set_reading(r(SensorKind::Accelerometer, 1.0, 1.0, 1.0, 1));
652
        mgr.set_reading(r(SensorKind::Gyroscope, 2.0, 2.0, 2.0, 2));
653
        mgr.set_reading(r(SensorKind::Magnetometer, 3.0, 3.0, 3.0, 3));
654

            
655
        assert_eq!(
656
            mgr.reading(SensorKind::Accelerometer).map(|s| s.x),
657
            Some(1.0)
658
        );
659
        assert_eq!(mgr.reading(SensorKind::Gyroscope).map(|s| s.x), Some(2.0));
660
        assert_eq!(
661
            mgr.reading(SensorKind::Magnetometer).map(|s| s.x),
662
            Some(3.0)
663
        );
664
        for kind in KINDS {
665
            assert_eq!(
666
                mgr.reading(kind).map(|s| s.kind),
667
                Some(kind),
668
                "the {kind:?} slot must hold a {kind:?}-tagged sample"
669
            );
670
        }
671
    }
672

            
673
    /// The `pending_event` flag is *sticky*: it stays armed until the event
674
    /// pass clears it. A redundant sample arriving in between returns `false`
675
    /// but must not silently disarm the pending event (an implementation that
676
    /// wrote `self.pending_event = changed` would drop the notification).
677
    #[test]
678
    fn redundant_sample_does_not_disarm_a_pending_event() {
679
        let mut mgr = SensorManager::new();
680
        let sample = base();
681

            
682
        assert!(mgr.set_reading(sample));
683
        assert!(mgr.pending_event, "the advance armed the event");
684

            
685
        assert!(!mgr.set_reading(sample), "identical sample: no advance");
686
        assert!(
687
            mgr.pending_event,
688
            "a redundant sample must NOT clear an event the pass has not seen yet"
689
        );
690
        assert_eq!(
691
            mgr.get_pending_events(tick()).len(),
692
            1,
693
            "the event must still be deliverable"
694
        );
695
    }
696

            
697
    /// …and the converse: once cleared, a redundant sample must not re-arm it.
698
    #[test]
699
    fn redundant_sample_after_clear_does_not_re_arm() {
700
        let mut mgr = SensorManager::new();
701
        mgr.set_reading(base());
702
        mgr.clear_pending_event();
703

            
704
        assert!(!mgr.set_reading(base()), "identical sample: no advance");
705
        assert!(
706
            !mgr.pending_event,
707
            "a no-op sample must not raise a fresh event"
708
        );
709
        assert!(mgr.get_pending_events(tick()).is_empty());
710

            
711
        let mut moved = base();
712
        moved.x += 1.0;
713
        assert!(mgr.set_reading(moved), "a real change re-arms");
714
        assert!(mgr.pending_event);
715
    }
716

            
717
    // ───────────────────── clear_pending_event / listeners ──────────────────
718

            
719
    /// no_panic + invariant: clearing is idempotent, safe on a fresh manager,
720
    /// and touches neither the stored readings nor the listener flag.
721
    #[test]
722
    fn clear_pending_event_is_idempotent_and_narrow() {
723
        let mut mgr = SensorManager::new();
724
        mgr.clear_pending_event(); // on a cold manager: no-op, no panic
725
        assert!(!mgr.pending_event);
726

            
727
        mgr.set_has_listeners(true);
728
        mgr.set_reading(base());
729
        assert!(mgr.pending_event);
730

            
731
        mgr.clear_pending_event();
732
        mgr.clear_pending_event(); // twice — still just cleared
733
        assert!(!mgr.pending_event);
734
        assert_eq!(
735
            mgr.reading(SensorKind::Accelerometer),
736
            Some(base()),
737
            "clearing the flag must not discard the stored reading"
738
        );
739
        assert!(
740
            mgr.has_listeners(),
741
            "clearing the flag must not disarm polling"
742
        );
743
    }
744

            
745
    /// basic_true_false + edge_inputs: the listener flag round-trips, is
746
    /// idempotent, and is independent of the reading/event state.
747
    #[test]
748
    fn has_listeners_round_trips_and_stays_independent() {
749
        let mut mgr = SensorManager::new();
750
        assert!(!mgr.has_listeners(), "default is 'do not poll'");
751

            
752
        for arm in [true, true, false, false, true] {
753
            mgr.set_has_listeners(arm);
754
            assert_eq!(
755
                mgr.has_listeners(),
756
                arm,
757
                "set_has_listeners({arm}) must stick"
758
            );
759
        }
760

            
761
        // Arming/disarming polling must not fabricate or destroy readings.
762
        assert_eq!(mgr.reading(SensorKind::Accelerometer), None);
763
        assert!(!mgr.pending_event);
764

            
765
        mgr.set_reading(base());
766
        mgr.set_has_listeners(false);
767
        assert!(
768
            mgr.pending_event,
769
            "dropping the listeners must not swallow an already-pending event"
770
        );
771
        assert_eq!(mgr.reading(SensorKind::Accelerometer), Some(base()));
772
    }
773

            
774
    /// Applying a reading must not arm polling by itself — only the relayout
775
    /// walk gets to decide that (the MWA-A1 arming signal).
776
    #[test]
777
    fn set_reading_never_arms_the_listener_flag() {
778
        let mut mgr = SensorManager::new();
779
        for kind in KINDS {
780
            mgr.set_reading(nan_sample(kind));
781
            assert!(
782
                !mgr.has_listeners(),
783
                "{kind:?}: only set_has_listeners may arm polling"
784
            );
785
        }
786
    }
787

            
788
    // ────────────────────── reading_bitwise_eq (private) ────────────────────
789

            
790
    /// The crux of the helper: it is *reflexive even for NaN*, where the
791
    /// derived `PartialEq` is not.
792
    #[test]
793
    fn bitwise_eq_is_reflexive_even_for_nan() {
794
        for kind in KINDS {
795
            let a = nan_sample(kind);
796
            let b = a; // Copy — same bit pattern
797
            assert!(
798
                reading_bitwise_eq(&a, &b),
799
                "{kind:?}: identical bit patterns must compare equal"
800
            );
801
            assert!(
802
                a != b,
803
                "{kind:?}: sanity — derived PartialEq disagrees, because NaN != NaN"
804
            );
805
        }
806
    }
807

            
808
    /// …and it is *not* reflexive over numeric equality: `-0.0` and `0.0`
809
    /// compare equal as floats but are different bit patterns.
810
    #[test]
811
    fn bitwise_eq_separates_signed_zeroes_that_partialeq_merges() {
812
        let pos = r(SensorKind::Accelerometer, 0.0, 0.0, 0.0, 0);
813
        let neg = r(SensorKind::Accelerometer, -0.0, -0.0, -0.0, 0);
814

            
815
        assert_eq!(pos, neg, "sanity: derived PartialEq calls the zeroes equal");
816
        assert!(
817
            !reading_bitwise_eq(&pos, &neg),
818
            "the bitwise comparison must tell +0.0 and -0.0 apart"
819
        );
820
    }
821

            
822
    /// Completeness: flipping *any single field* — including `kind`, the branch
823
    /// `set_reading` can never reach because the kind picks the slot — must make
824
    /// the helper report "not equal".
825
    #[test]
826
    fn bitwise_eq_watches_every_field() {
827
        let b = base();
828

            
829
        let mut other_kind = b;
830
        other_kind.kind = SensorKind::Gyroscope;
831
        let mut other_x = b;
832
        other_x.x = ulp_flip(b.x);
833
        let mut other_y = b;
834
        other_y.y = ulp_flip(b.y);
835
        let mut other_z = b;
836
        other_z.z = ulp_flip(b.z);
837
        let mut other_ts = b;
838
        other_ts.timestamp_ms = b.timestamp_ms + 1;
839

            
840
        for (field, mutated) in [
841
            ("kind", other_kind),
842
            ("x", other_x),
843
            ("y", other_y),
844
            ("z", other_z),
845
            ("timestamp_ms", other_ts),
846
        ] {
847
            assert!(
848
                !reading_bitwise_eq(&b, &mutated),
849
                "a difference in `{field}` must be detected"
850
            );
851
            assert!(
852
                !reading_bitwise_eq(&mutated, &b),
853
                "`{field}`: and symmetrically so"
854
            );
855
        }
856
    }
857

            
858
    /// no_panic + invariant: reflexive and symmetric across a hostile matrix of
859
    /// float values, kinds and boundary timestamps.
860
    #[test]
861
    fn bitwise_eq_is_reflexive_and_symmetric_over_hostile_inputs() {
862
        let mut samples = Vec::new();
863
        for kind in KINDS {
864
            for v in hostile_floats() {
865
                for ts in [0_u64, u64::MAX] {
866
                    samples.push(r(kind, v, -v, v, ts));
867
                }
868
            }
869
        }
870

            
871
        for a in &samples {
872
            assert!(reading_bitwise_eq(a, a), "must be reflexive for {a:?}");
873
            for b in &samples {
874
                assert_eq!(
875
                    reading_bitwise_eq(a, b),
876
                    reading_bitwise_eq(b, a),
877
                    "must be symmetric for {a:?} vs {b:?}"
878
                );
879
                assert_eq!(
880
                    reading_bitwise_eq(a, b),
881
                    bits_identical(a, b),
882
                    "must agree with a field-by-field bit comparison for {a:?} vs {b:?}"
883
                );
884
            }
885
        }
886
    }
887

            
888
    // ───────────────────────── EventProvider surface ────────────────────────
889

            
890
    /// The event is emitted only while armed, exactly once, at the root — and
891
    /// `clear_pending_event` is what stops it repeating every pass.
892
    #[test]
893
    fn sensor_changed_event_is_emitted_only_while_pending() {
894
        let mut mgr = SensorManager::new();
895
        assert!(
896
            mgr.get_pending_events(tick()).is_empty(),
897
            "a cold manager emits nothing"
898
        );
899

            
900
        assert!(mgr.set_reading(base()));
901
        let events = mgr.get_pending_events(tick());
902
        assert_eq!(events.len(), 1, "one advance → exactly one event");
903
        assert_eq!(events[0].event_type, EventType::SensorChanged);
904
        assert_eq!(
905
            events[0].target,
906
            DomNodeId::ROOT,
907
            "window-level: target is root"
908
        );
909

            
910
        assert_eq!(
911
            mgr.get_pending_events(tick()).len(),
912
            1,
913
            "collecting is non-destructive; only clear_pending_event disarms"
914
        );
915

            
916
        mgr.clear_pending_event();
917
        assert!(
918
            mgr.get_pending_events(tick()).is_empty(),
919
            "after the event pass drained it, nothing more is pending"
920
        );
921
    }
922

            
923
    /// Several kinds advancing in one pass still collapse into a single
924
    /// window-level event (the callback reads the values it wants by kind).
925
    #[test]
926
    fn many_advances_collapse_into_one_event() {
927
        let mut mgr = SensorManager::new();
928
        for kind in KINDS {
929
            for (ts, x) in [(0_u64, 1.0_f32), (1, 2.0), (2, 3.0), (3, 4.0)] {
930
                mgr.set_reading(r(kind, x, 0.0, 0.0, ts));
931
            }
932
        }
933
        assert_eq!(
934
            mgr.get_pending_events(tick()).len(),
935
            1,
936
            "12 samples across 3 kinds still yield one SensorChanged"
937
        );
938
    }
939
}