1
//! Geolocation manager — cross-platform state for the GPS/location surface
2
//! (`SUPER_PLAN_2` §1.5 + research/04 §3 + research/08 §6).
3
//!
4
//! Three callers drive it:
5
//!
6
//! - The **layout pass** scans the styled DOM for `GeolocationProbe` `NodeTypes`. When the first
7
//!   probe appears the framework fires `PermissionDiffEvent::Subscribe(Capability::Geolocation)`
8
//!   and the platform backend starts a native `CLLocationManager` / `LocationManager` / `geoclue`
9
//!   subscription. The reverse on the last probe leaving.
10
//!
11
//! - The **platform backend** (`dll/src/desktop/extra/geolocation/<plat>.rs`) calls
12
//!   `set_latest_fix(...)` whenever the native subscription delivers an update. The manager
13
//!   debounces and records the most recent value; callbacks read it via
14
//!   `CallbackInfo::get_geolocation_fix`.
15
//!
16
//! - **Callbacks** read `latest_fix()` synchronously to render the map centre, decide whether to
17
//!   show "acquiring signal…", etc.
18
//!
19
//! No platform deps; `no_std`-friendly via `alloc::collections::BTreeMap`.
20

            
21
use alloc::{collections::btree_map::BTreeMap, vec::Vec};
22

            
23
// `LocationFix` + `GeolocationProbeConfig` live in `azul-core` so
24
// `NodeType::GeolocationProbe(GeolocationProbeConfig)` can reference
25
// the config struct without a cyclic dep on `azul-layout`. We re-export
26
// them here for the existing `azul_layout::managers::geolocation::*`
27
// import paths.
28
pub use azul_core::geolocation::{GeolocationProbeConfig, LocationFix};
29
use azul_core::{
30
    dom::DomNodeId,
31
    events::{EventData, EventProvider, EventSource as CoreEventSource, EventType, SyntheticEvent},
32
    task::Instant,
33
};
34

            
35
/// Diff event the layout pass emits when a probe appears or disappears.
36
/// Symmetric to `PermissionDiffEvent` — drives the platform backend's
37
/// native subscribe / release calls.
38
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
39
#[repr(C, u8)]
40
pub enum GeolocationDiffEvent {
41
    /// First probe of this config landed in the layout — start a
42
    /// native subscription with these options.
43
    Subscribe { config: GeolocationProbeConfig },
44
    /// Last probe left — stop the native subscription.
45
    Release,
46
    /// Probe config changed without subscriber churn — reconfigure
47
    /// the running subscription in place (e.g. `high_accuracy` false →
48
    /// true).
49
    Reconfigure { config: GeolocationProbeConfig },
50
}
51

            
52
/// Cross-platform geolocation state. One per `App` (the OS gives us
53
/// a single per-process subscription, not per-window).
54
#[derive(Debug, Clone, PartialEq, Default)]
55
pub struct GeolocationManager {
56
    /// Most recent fix from the platform backend, or `None` until the
57
    /// first native sample arrives (or `None` again after a Release).
58
    pub latest_fix: Option<LocationFix>,
59
    /// Active probe config — set on each Subscribe / Reconfigure,
60
    /// cleared on Release.
61
    pub active_config: Option<GeolocationProbeConfig>,
62
    /// Diff queue drained once per frame by the platform backend.
63
    pending_events: Vec<GeolocationDiffEvent>,
64
    /// Refcount of `GeolocationProbe` nodes currently in the layout.
65
    refcount: u32,
66
    /// `true` when a fix advanced since the last event-pass drain. Set by
67
    /// [`set_latest_fix`](Self::set_latest_fix), read by the `EventProvider`
68
    /// impl (yields `EventType::GeolocationFix`), cleared by
69
    /// [`clear_pending_event`](Self::clear_pending_event) after dispatch
70
    /// (MWA-A1 — this manager previously computed fixes nobody dispatched).
71
    pending_event: bool,
72
    /// Most recent backend error (subscription failed / timed out /
73
    /// revoked), or `None`. Cleared on the next successful fix (MWA-A1b).
74
    pub last_error: Option<LocationError>,
75
    /// `true` when an error arrived since the last event-pass drain — the
76
    /// `EventProvider` impl yields `EventType::GeolocationError` for it.
77
    pending_error_event: bool,
78
}
79

            
80
/// Error from the native geolocation backend (MWA-A1b).
81
///
82
/// Layout-internal
83
/// (not FFI-exposed) until the `CallbackInfo` getter lands with the Phase C
84
/// geolocation item — the `GeolocationError` EVENT carries no payload, so
85
/// callbacks poll this via the manager.
86
#[derive(Debug, Clone, PartialEq, Eq, Default)]
87
pub struct LocationError {
88
    /// Platform-specific error code (`CLError` code / `GError` code / HRESULT).
89
    pub code: u32,
90
    /// Human-readable message from the backend.
91
    pub message: String,
92
}
93

            
94
impl GeolocationManager {
95
    #[must_use]
96
7621
    pub fn new() -> Self {
97
7621
        Self::default()
98
7621
    }
99

            
100
    #[must_use]
101
37
    pub const fn latest_fix(&self) -> Option<LocationFix> {
102
37
        self.latest_fix
103
37
    }
104

            
105
    #[must_use]
106
36
    pub const fn refcount(&self) -> u32 {
107
36
        self.refcount
108
36
    }
109

            
110
    /// Platform backend writes the freshly-received fix. Returns true
111
    /// if the fix actually advanced (different from the previous one)
112
    /// so the caller can mark the window dirty for relayout.
113
    ///
114
    /// Compared via bit-pattern equality so missing fields (encoded as
115
    /// `f32::NAN`) compare equal — `PartialEq` returns `false` on
116
    /// NaN-vs-NaN, which would make every fix look "changed" even
117
    /// when nothing actually moved.
118
154
    pub fn set_latest_fix(&mut self, fix: LocationFix) -> bool {
119
154
        let changed = self
120
154
            .latest_fix
121
154
            .is_none_or(|prev| !Self::location_fix_bitwise_eq(&prev, &fix));
122
154
        self.latest_fix = Some(fix);
123
154
        if changed {
124
43
            self.pending_event = true;
125
43
            // A successful fix supersedes any earlier error.
126
43
            self.last_error = None;
127
111
        }
128
154
        changed
129
154
    }
130

            
131
    /// Platform backend reports a subscription error (MWA-A1b). Always
132
    /// raises the error-event flag — repeated errors each answer a live
133
    /// subscription and callbacks should hear every one.
134
12
    pub fn set_last_error(&mut self, error: LocationError) {
135
12
        self.last_error = Some(error);
136
12
        self.pending_error_event = true;
137
12
    }
138

            
139
    /// Clear the pending-event flags (fix + error). The dll calls this
140
    /// after the event pass has collected the geolocation events.
141
166
    pub const fn clear_pending_event(&mut self) {
142
166
        self.pending_event = false;
143
166
        self.pending_error_event = false;
144
166
    }
145

            
146
    /// `true` while at least one `GeolocationProbe` is mounted — the
147
    /// capability pump keeps its drain timer armed while this holds, so
148
    /// fixes parked by the native backend reach callbacks without waiting
149
    /// for unrelated input (MWA-A1 arming signal).
150
    #[must_use]
151
23
    pub const fn has_active_subscription(&self) -> bool {
152
23
        self.refcount > 0
153
23
    }
154

            
155
204
    const fn location_fix_bitwise_eq(a: &LocationFix, b: &LocationFix) -> bool {
156
204
        a.latitude_deg.to_bits() == b.latitude_deg.to_bits()
157
156
            && a.longitude_deg.to_bits() == b.longitude_deg.to_bits()
158
153
            && a.accuracy_m.to_bits() == b.accuracy_m.to_bits()
159
150
            && a.altitude_m.to_bits() == b.altitude_m.to_bits()
160
147
            && a.altitude_accuracy_m.to_bits() == b.altitude_accuracy_m.to_bits()
161
144
            && a.heading_deg.to_bits() == b.heading_deg.to_bits()
162
140
            && a.speed_mps.to_bits() == b.speed_mps.to_bits()
163
137
            && a.timestamp_ms == b.timestamp_ms
164
204
    }
165

            
166
    /// Drain queued diff events. Platform backend calls this once per
167
    /// frame.
168
36
    pub fn take_pending_events(&mut self) -> Vec<GeolocationDiffEvent> {
169
36
        core::mem::take(&mut self.pending_events)
170
36
    }
171

            
172
    /// Diff entry point. The layout pass walks the styled DOM for
173
    /// `GeolocationProbe` nodes and feeds each `(config, node_id)`
174
    /// pair to the closure. The manager bumps the refcount, watches
175
    /// for config drift, and enqueues the right Subscribe / Release /
176
    /// Reconfigure event.
177
38
    pub fn diff_layout<F>(&mut self, mut for_each_probe: F)
178
38
    where
179
38
        F: FnMut(&mut dyn FnMut(GeolocationProbeConfig)),
180
    {
181
38
        let mut new_count: u32 = 0;
182
38
        let mut next_config: Option<GeolocationProbeConfig> = None;
183
10032
        for_each_probe(&mut |cfg| {
184
10032
            new_count += 1;
185
            // First probe's config wins. Subsequent probes that
186
            // disagree are accepted silently — a real app shouldn't
187
            // mount two `GeolocationProbe`s with different configs
188
            // but the framework can't assert that here.
189
10032
            if next_config.is_none() {
190
28
                next_config = Some(cfg);
191
10004
            }
192
10032
        });
193

            
194
38
        let old_count = self.refcount;
195
38
        self.refcount = new_count;
196

            
197
38
        match (old_count, new_count) {
198
18
            (0, n) if n > 0 => {
199
14
                let config = next_config.unwrap_or_default();
200
14
                self.active_config = Some(config);
201
14
                self.pending_events
202
14
                    .push(GeolocationDiffEvent::Subscribe { config });
203
14
            }
204
10
            (m, 0) if m > 0 => {
205
6
                self.active_config = None;
206
6
                self.latest_fix = None;
207
6
                self.pending_events.push(GeolocationDiffEvent::Release);
208
6
            }
209
18
            (m, n) if m > 0 && n > 0 => {
210
                // Both frames have probes. Emit Reconfigure if the
211
                // config actually drifted.
212
14
                let new_config = next_config.unwrap_or_default();
213
14
                if Some(new_config) != self.active_config {
214
6
                    self.active_config = Some(new_config);
215
6
                    self.pending_events
216
6
                        .push(GeolocationDiffEvent::Reconfigure { config: new_config });
217
8
                }
218
            }
219
4
            _ => {
220
4
                // 0 → 0 — nothing to do.
221
4
            }
222
        }
223
38
    }
224
}
225

            
226
impl EventProvider for GeolocationManager {
227
    /// Yield a window-level `GeolocationFix` event when a fix advanced since
228
    /// the last drain (target = root; read the value via
229
    /// `CallbackInfo::get_geolocation_fix` inside the callback). Mirrors the
230
    /// sensor / gamepad providers; before MWA-A1 nothing ever produced
231
    /// `EventType::GeolocationFix`, so fix callbacks could never fire.
232
181
    fn get_pending_events(&self, timestamp: Instant) -> Vec<SyntheticEvent> {
233
181
        let mut events = Vec::new();
234
181
        if self.pending_event {
235
14
            events.push(SyntheticEvent::new(
236
14
                EventType::GeolocationFix,
237
14
                CoreEventSource::User,
238
14
                DomNodeId::ROOT,
239
14
                timestamp.clone(),
240
14
                EventData::None,
241
14
            ));
242
167
        }
243
181
        if self.pending_error_event {
244
12
            events.push(SyntheticEvent::new(
245
12
                EventType::GeolocationError,
246
12
                CoreEventSource::User,
247
12
                DomNodeId::ROOT,
248
12
                timestamp,
249
12
                EventData::None,
250
12
            ));
251
169
        }
252
181
        events
253
181
    }
254
}
255

            
256
// ────────── Async fix channel (platform backend → manager) ────────────
257
//
258
// A native location callback (Android `FusedLocationProvider`
259
// `onLocationResult`, iOS `CLLocationManagerDelegate`) fires on an
260
// arbitrary thread with no handle to the live `GeolocationManager` (it
261
// lives inside the window's `LayoutWindow`). The backend parks each fix
262
// here; the layout pass drains it once per frame via
263
// [`drain_location_fixes`] and applies the latest through
264
// [`GeolocationManager::set_latest_fix`]. Pure Rust — no platform
265
// dependency (SUPER_PLAN_2 §0.5). Mirrors the permission manager's
266
// async-result channel.
267

            
268
/// The channel, as a VALUE: a fixes queue and an errors queue.
269
///
270
/// Mirrors `hid::HidChannel` / `sensors::SensorChannel` — a struct so the
271
/// process-wide instance (`CHANNEL`) is an instance, and a test can own its
272
/// own instead of sharing a global with every other test in the binary.
273
#[derive(Debug, Default)]
274
pub struct GeolocationChannel {
275
    pending_fixes: std::sync::Mutex<Vec<LocationFix>>,
276
    /// Error channel (MWA-A1b) — same shape as the fix channel: the native
277
    /// backend's error callback fires on an OS thread and parks here; the
278
    /// capability pump drains into `set_last_error`.
279
    pending_errors: std::sync::Mutex<Vec<LocationError>>,
280
}
281

            
282
/// The process-wide channel the dll backends push into and the engine drains.
283
static CHANNEL: GeolocationChannel = GeolocationChannel::new();
284

            
285
impl GeolocationChannel {
286
    /// An empty channel. `const` so the process-wide one can be a `static`.
287
    #[must_use]
288
2
    pub const fn new() -> Self {
289
2
        Self {
290
2
            pending_fixes: std::sync::Mutex::new(Vec::new()),
291
2
            pending_errors: std::sync::Mutex::new(Vec::new()),
292
2
        }
293
2
    }
294

            
295
    /// Park a fix. Thread-safe; recovers from a poisoned lock so one
296
    /// panicking applier can't wedge delivery forever.
297
12
    pub fn push_fix(&self, fix: LocationFix) {
298
12
        let mut q = self
299
12
            .pending_fixes
300
12
            .lock()
301
12
            .unwrap_or_else(std::sync::PoisonError::into_inner);
302
12
        q.push(fix);
303
12
    }
304

            
305
    /// Drain every parked fix, in arrival order.
306
    #[must_use]
307
22
    pub fn drain_fixes(&self) -> Vec<LocationFix> {
308
22
        let mut q = self
309
22
            .pending_fixes
310
22
            .lock()
311
22
            .unwrap_or_else(std::sync::PoisonError::into_inner);
312
22
        core::mem::take(&mut *q)
313
22
    }
314

            
315
    /// Park an error. Thread-safe; poison-recovering.
316
1
    pub fn push_error(&self, error: LocationError) {
317
1
        let mut q = self
318
1
            .pending_errors
319
1
            .lock()
320
1
            .unwrap_or_else(std::sync::PoisonError::into_inner);
321
1
        q.push(error);
322
1
    }
323

            
324
    /// Drain every parked error, in arrival order.
325
    #[must_use]
326
2
    pub fn drain_errors(&self) -> Vec<LocationError> {
327
2
        let mut q = self
328
2
            .pending_errors
329
2
            .lock()
330
2
            .unwrap_or_else(std::sync::PoisonError::into_inner);
331
2
        core::mem::take(&mut *q)
332
2
    }
333
}
334

            
335
/// Park a location fix delivered by a platform backend (in the dll).
336
/// Thread-safe; recovers from a poisoned lock so one panicking applier
337
/// can't wedge delivery forever.
338
10
pub fn push_location_fix(fix: LocationFix) {
339
10
    CHANNEL.push_fix(fix);
340
10
}
341

            
342
/// Drain every fix parked by [`push_location_fix`], in arrival order.
343
/// Called once per layout pass; the caller applies them through
344
/// [`GeolocationManager::set_latest_fix`] (the last one wins).
345
21
pub fn drain_location_fixes() -> Vec<LocationFix> {
346
21
    CHANNEL.drain_fixes()
347
21
}
348

            
349
/// Park a geolocation error delivered by a platform backend (in the dll).
350
/// Thread-safe; poison-recovering.
351
pub fn push_location_error(error: LocationError) {
352
    CHANNEL.push_error(error);
353
}
354

            
355
/// Drain every error parked by [`push_location_error`], in arrival order.
356
pub fn drain_location_errors() -> Vec<LocationError> {
357
    CHANNEL.drain_errors()
358
}
359

            
360
#[cfg(test)]
361
mod tests {
362
    use super::*;
363

            
364
6
    fn cfg() -> GeolocationProbeConfig {
365
6
        GeolocationProbeConfig::default()
366
6
    }
367

            
368
1
    fn high_accuracy_cfg() -> GeolocationProbeConfig {
369
1
        GeolocationProbeConfig {
370
1
            high_accuracy: true,
371
1
            ..GeolocationProbeConfig::default()
372
1
        }
373
1
    }
374

            
375
10
    fn fix(lat: f64, lon: f64) -> LocationFix {
376
10
        LocationFix {
377
10
            latitude_deg: lat,
378
10
            longitude_deg: lon,
379
10
            accuracy_m: 10.0,
380
10
            altitude_m: f32::NAN,
381
10
            altitude_accuracy_m: f32::NAN,
382
10
            heading_deg: f32::NAN,
383
10
            speed_mps: f32::NAN,
384
10
            timestamp_ms: 0,
385
10
        }
386
10
    }
387

            
388
    #[test]
389
1
    fn first_probe_emits_subscribe_with_config() {
390
1
        let mut mgr = GeolocationManager::new();
391
1
        mgr.diff_layout(|emit| emit(cfg()));
392
1
        assert_eq!(mgr.refcount(), 1);
393
1
        let events = mgr.take_pending_events();
394
1
        assert_eq!(events.len(), 1);
395
1
        assert!(matches!(events[0], GeolocationDiffEvent::Subscribe { .. }));
396
1
    }
397

            
398
    #[test]
399
1
    fn last_probe_drop_emits_release_and_clears_fix() {
400
1
        let mut mgr = GeolocationManager::new();
401
1
        mgr.diff_layout(|emit| emit(cfg()));
402
1
        mgr.set_latest_fix(fix(37.0, -122.0));
403
1
        drop(mgr.take_pending_events());
404

            
405
1
        mgr.diff_layout(|_emit| {});
406
1
        assert_eq!(mgr.refcount(), 0);
407
1
        assert_eq!(mgr.latest_fix(), None);
408
1
        let events = mgr.take_pending_events();
409
1
        assert_eq!(events.len(), 1);
410
1
        assert!(matches!(events[0], GeolocationDiffEvent::Release));
411
1
    }
412

            
413
    #[test]
414
1
    fn config_drift_emits_reconfigure() {
415
1
        let mut mgr = GeolocationManager::new();
416
1
        mgr.diff_layout(|emit| emit(cfg()));
417
1
        drop(mgr.take_pending_events());
418

            
419
1
        mgr.diff_layout(|emit| emit(high_accuracy_cfg()));
420
1
        let events = mgr.take_pending_events();
421
1
        assert_eq!(events.len(), 1);
422
1
        let ev = &events[0];
423
1
        match ev {
424
1
            GeolocationDiffEvent::Reconfigure { config } => {
425
1
                assert!(config.high_accuracy);
426
            }
427
            _ => panic!("expected Reconfigure, got {ev:?}"),
428
        }
429
1
    }
430

            
431
    #[test]
432
1
    fn stable_config_does_not_re_emit() {
433
1
        let mut mgr = GeolocationManager::new();
434
1
        mgr.diff_layout(|emit| emit(cfg()));
435
1
        drop(mgr.take_pending_events());
436

            
437
        // Same config across frames — no events.
438
1
        mgr.diff_layout(|emit| emit(cfg()));
439
1
        assert!(mgr.take_pending_events().is_empty());
440
1
    }
441

            
442
    #[test]
443
1
    fn set_latest_fix_returns_change_flag() {
444
1
        let mut mgr = GeolocationManager::new();
445
1
        assert!(mgr.set_latest_fix(fix(37.0, -122.0)));
446
1
        assert!(!mgr.set_latest_fix(fix(37.0, -122.0)));
447
1
        assert!(mgr.set_latest_fix(fix(37.7749, -122.4194)));
448
1
    }
449

            
450
    #[test]
451
1
    fn missing_fields_decode_to_none() {
452
1
        let f = fix(0.0, 0.0);
453
1
        assert_eq!(f.altitude(), None);
454
1
        assert_eq!(f.heading(), None);
455
1
        assert_eq!(f.speed(), None);
456
1
    }
457

            
458
    #[test]
459
1
    fn provider_yields_fix_event_then_clears() {
460
        use azul_core::task::{Instant, SystemTick};
461

            
462
1
        let ts = Instant::Tick(SystemTick::new(0));
463
1
        let mut mgr = GeolocationManager::new();
464
1
        assert!(mgr.get_pending_events(ts.clone()).is_empty(), "no fix yet");
465

            
466
1
        mgr.set_latest_fix(fix(37.0, -122.0));
467
1
        let events = mgr.get_pending_events(ts.clone());
468
1
        assert_eq!(events.len(), 1);
469
1
        assert_eq!(events[0].event_type, EventType::GeolocationFix);
470

            
471
1
        mgr.clear_pending_event();
472
1
        assert!(
473
1
            mgr.get_pending_events(ts.clone()).is_empty(),
474
            "cleared after dispatch"
475
        );
476

            
477
        // An identical fix is not a change — no re-fire.
478
1
        mgr.set_latest_fix(fix(37.0, -122.0));
479
1
        assert!(mgr.get_pending_events(ts).is_empty());
480
1
    }
481

            
482
    #[test]
483
1
    fn error_channel_and_provider_event() {
484
        use azul_core::task::{Instant, SystemTick};
485

            
486
        // Own the channel; the process-wide one is shared with every other
487
        // test in this binary on the parallel runner.
488
1
        let ch = GeolocationChannel::new();
489
1
        ch.push_error(LocationError {
490
1
            code: 1,
491
1
            message: "denied".into(),
492
1
        });
493
1
        let errs = ch.drain_errors();
494
1
        assert_eq!(errs.len(), 1);
495
1
        assert!(ch.drain_errors().is_empty());
496

            
497
1
        let ts = Instant::Tick(SystemTick::new(0));
498
1
        let mut mgr = GeolocationManager::new();
499
1
        mgr.set_last_error(errs[0].clone());
500
1
        let events = mgr.get_pending_events(ts.clone());
501
1
        assert_eq!(events.len(), 1);
502
1
        assert_eq!(events[0].event_type, EventType::GeolocationError);
503
1
        mgr.clear_pending_event();
504
1
        assert!(mgr.get_pending_events(ts).is_empty());
505

            
506
        // a successful (changed) fix supersedes the stored error
507
1
        mgr.set_latest_fix(fix(1.0, 2.0));
508
1
        assert!(mgr.last_error.is_none());
509
1
    }
510

            
511
    #[test]
512
1
    fn subscription_flag_follows_probe_refcount() {
513
1
        let mut mgr = GeolocationManager::new();
514
1
        assert!(!mgr.has_active_subscription());
515
1
        mgr.diff_layout(|emit| emit(cfg()));
516
1
        assert!(mgr.has_active_subscription());
517
1
        mgr.diff_layout(|_emit| {});
518
1
        assert!(!mgr.has_active_subscription());
519
1
    }
520

            
521
    #[test]
522
    #[allow(clippy::float_cmp)] // test asserts exact float equality on deterministic values
523
1
    fn async_fixes_round_trip_through_manager() {
524
        // Own the channel rather than clearing "residue" off the process-wide
525
        // one — residue is another test's data, and clearing it is how tests
526
        // steal from each other.
527
1
        let ch = GeolocationChannel::new();
528
1
        ch.push_fix(fix(37.0, -122.0));
529
1
        ch.push_fix(fix(48.8566, 2.3522)); // Paris — last wins
530
1
        let drained = ch.drain_fixes();
531
1
        assert_eq!(drained.len(), 2, "both parked fixes drain in order");
532
1
        assert_eq!(drained[0].latitude_deg, 37.0);
533
1
        assert_eq!(drained[1].latitude_deg, 48.8566);
534

            
535
        // Applying them reflects in latest_fix() — what the layout pass does.
536
1
        let mut mgr = GeolocationManager::new();
537
3
        for f in &drained {
538
2
            mgr.set_latest_fix(*f);
539
2
        }
540
1
        let got = mgr.latest_fix().expect("a fix was applied");
541
1
        assert_eq!(got.latitude_deg, 48.8566, "the last applied fix wins");
542

            
543
        // A second drain is empty — the queue was taken, not copied.
544
1
        assert!(drain_location_fixes().is_empty());
545
1
    }
546
}
547

            
548
#[cfg(test)]
549
#[allow(clippy::float_cmp, clippy::eq_op, clippy::redundant_clone)]
550
mod autotest_generated {
551
    use azul_core::task::{Instant, SystemTick};
552

            
553
    use super::*;
554

            
555
    // ─────────────────────────── helpers ────────────────────────────
556

            
557
    /// A fix where every optional field is *present* — knocking out a single
558
    /// field then flips exactly one comparison.
559
    const fn full_fix() -> LocationFix {
560
        LocationFix {
561
            latitude_deg: 48.208_8,
562
            longitude_deg: 16.372_1,
563
            accuracy_m: 5.0,
564
            altitude_m: 171.0,
565
            altitude_accuracy_m: 3.0,
566
            heading_deg: 90.0,
567
            speed_mps: 1.5,
568
            timestamp_ms: 1_234,
569
        }
570
    }
571

            
572
    /// "Platform reported nothing but lat/lon" — the NaN-heavy shape
573
    /// `set_latest_fix` documents as the reason it compares bit patterns.
574
    const fn nan_fix() -> LocationFix {
575
        LocationFix {
576
            latitude_deg: 37.0,
577
            longitude_deg: -122.0,
578
            accuracy_m: 10.0,
579
            altitude_m: f32::NAN,
580
            altitude_accuracy_m: f32::NAN,
581
            heading_deg: f32::NAN,
582
            speed_mps: f32::NAN,
583
            timestamp_ms: 0,
584
        }
585
    }
586

            
587
    const fn probe_cfg(high_accuracy: bool, max_accuracy_m: f32) -> GeolocationProbeConfig {
588
        GeolocationProbeConfig {
589
            high_accuracy,
590
            background: false,
591
            max_accuracy_m,
592
            min_interval_ms: 0,
593
        }
594
    }
595

            
596
    fn tick() -> Instant {
597
        Instant::Tick(SystemTick::new(0))
598
    }
599

            
600
    /// The 8 single-field mutations of [`full_fix`], one per field the
601
    /// bit-pattern comparison has to look at.
602
    fn single_field_mutations() -> Vec<(&'static str, LocationFix)> {
603
        let base = full_fix();
604
        let mut out = Vec::new();
605

            
606
        let mut f = base;
607
        f.latitude_deg = -48.208_8;
608
        out.push(("latitude_deg", f));
609

            
610
        let mut f = base;
611
        f.longitude_deg = 16.372_2;
612
        out.push(("longitude_deg", f));
613

            
614
        let mut f = base;
615
        f.accuracy_m = 5.000_001;
616
        out.push(("accuracy_m", f));
617

            
618
        let mut f = base;
619
        f.altitude_m = f32::NAN;
620
        out.push(("altitude_m", f));
621

            
622
        let mut f = base;
623
        f.altitude_accuracy_m = f32::NAN;
624
        out.push(("altitude_accuracy_m", f));
625

            
626
        let mut f = base;
627
        f.heading_deg = 270.0;
628
        out.push(("heading_deg", f));
629

            
630
        let mut f = base;
631
        f.speed_mps = -1.5;
632
        out.push(("speed_mps", f));
633

            
634
        let mut f = base;
635
        f.timestamp_ms = u64::MAX;
636
        out.push(("timestamp_ms", f));
637

            
638
        out
639
    }
640

            
641
    // ───────────────────── constructor / getters ────────────────────
642

            
643
    #[test]
644
    fn new_equals_default_and_holds_construction_invariants() {
645
        let mgr = GeolocationManager::new();
646
        assert_eq!(mgr, GeolocationManager::default());
647
        assert_eq!(
648
            mgr,
649
            GeolocationManager::new(),
650
            "construction is deterministic"
651
        );
652

            
653
        assert_eq!(mgr.latest_fix(), None);
654
        assert_eq!(mgr.refcount(), 0);
655
        assert_eq!(mgr.active_config, None);
656
        assert_eq!(mgr.last_error, None);
657
        assert!(!mgr.has_active_subscription());
658
        assert!(mgr.get_pending_events(tick()).is_empty());
659
    }
660

            
661
    #[test]
662
    fn getters_on_a_fresh_manager_do_not_panic() {
663
        let mut mgr = GeolocationManager::new();
664
        // Repeated reads of an empty manager stay None / 0 and never panic.
665
        for _ in 0..3 {
666
            assert_eq!(mgr.latest_fix(), None);
667
            assert_eq!(mgr.refcount(), 0);
668
            assert!(!mgr.has_active_subscription());
669
            assert!(mgr.take_pending_events().is_empty());
670
            mgr.clear_pending_event();
671
        }
672
    }
673

            
674
    #[test]
675
    fn latest_fix_round_trips_extreme_bit_patterns() {
676
        let extreme = LocationFix {
677
            latitude_deg: f64::INFINITY,
678
            longitude_deg: f64::NEG_INFINITY,
679
            accuracy_m: f32::MAX,
680
            altitude_m: f32::MIN_POSITIVE,
681
            altitude_accuracy_m: f32::from_bits(1), // subnormal
682
            heading_deg: -0.0,
683
            speed_mps: f32::NEG_INFINITY,
684
            timestamp_ms: u64::MAX,
685
        };
686

            
687
        let mut mgr = GeolocationManager::new();
688
        assert!(mgr.set_latest_fix(extreme), "first fix is always a change");
689

            
690
        let got = mgr.latest_fix().expect("a fix was stored");
691
        // encode == decode, bit for bit (not float-eq: -0.0 and subnormals).
692
        assert_eq!(got.latitude_deg.to_bits(), extreme.latitude_deg.to_bits());
693
        assert_eq!(got.longitude_deg.to_bits(), extreme.longitude_deg.to_bits());
694
        assert_eq!(got.accuracy_m.to_bits(), extreme.accuracy_m.to_bits());
695
        assert_eq!(got.altitude_m.to_bits(), extreme.altitude_m.to_bits());
696
        assert_eq!(
697
            got.altitude_accuracy_m.to_bits(),
698
            extreme.altitude_accuracy_m.to_bits()
699
        );
700
        assert_eq!(got.heading_deg.to_bits(), extreme.heading_deg.to_bits());
701
        assert_eq!(got.speed_mps.to_bits(), extreme.speed_mps.to_bits());
702
        assert_eq!(got.timestamp_ms, u64::MAX);
703

            
704
        // Infinities are *not* NaN, so the getters report them as present.
705
        assert_eq!(got.speed(), Some(f32::NEG_INFINITY));
706
        assert!(mgr.latest_fix().is_some());
707
        // Re-applying the identical extreme fix is not a change.
708
        assert!(!mgr.set_latest_fix(extreme));
709
    }
710

            
711
    #[test]
712
    fn nan_fix_round_trips_and_getters_still_report_missing() {
713
        let mut mgr = GeolocationManager::new();
714
        assert!(mgr.set_latest_fix(nan_fix()));
715

            
716
        let got = mgr.latest_fix().expect("a fix was stored");
717
        assert_eq!(got.altitude(), None);
718
        assert_eq!(got.altitude_accuracy(), None);
719
        assert_eq!(got.heading(), None);
720
        assert_eq!(got.speed(), None);
721
        assert_eq!(got.latitude_deg.to_bits(), 37.0_f64.to_bits());
722
    }
723

            
724
    // ───────────────── location_fix_bitwise_eq (private) ─────────────
725

            
726
    #[test]
727
    fn bitwise_eq_is_reflexive_on_nan_unlike_partial_eq() {
728
        let f = nan_fix();
729
        // Derived PartialEq is *not* reflexive here — that is the whole
730
        // reason `set_latest_fix` compares bit patterns instead.
731
        assert!(f != f, "PartialEq on a NaN-carrying fix is not reflexive");
732
        assert!(GeolocationManager::location_fix_bitwise_eq(&f, &f));
733
        assert!(GeolocationManager::location_fix_bitwise_eq(
734
            &nan_fix(),
735
            &nan_fix()
736
        ));
737
    }
738

            
739
    #[test]
740
    fn bitwise_eq_is_reflexive_and_symmetric_over_extremes() {
741
        let extremes = [
742
            full_fix(),
743
            nan_fix(),
744
            LocationFix {
745
                latitude_deg: f64::INFINITY,
746
                longitude_deg: f64::NEG_INFINITY,
747
                accuracy_m: f32::INFINITY,
748
                altitude_m: f32::MAX,
749
                altitude_accuracy_m: f32::MIN,
750
                heading_deg: f32::from_bits(1),
751
                speed_mps: -0.0,
752
                timestamp_ms: u64::MAX,
753
            },
754
            LocationFix {
755
                latitude_deg: 0.0,
756
                longitude_deg: 0.0,
757
                accuracy_m: 0.0,
758
                altitude_m: 0.0,
759
                altitude_accuracy_m: 0.0,
760
                heading_deg: 0.0,
761
                speed_mps: 0.0,
762
                timestamp_ms: 0,
763
            },
764
        ];
765

            
766
        for (i, a) in extremes.iter().enumerate() {
767
            assert!(
768
                GeolocationManager::location_fix_bitwise_eq(a, a),
769
                "not reflexive for extreme #{i}"
770
            );
771
            for (j, b) in extremes.iter().enumerate() {
772
                assert_eq!(
773
                    GeolocationManager::location_fix_bitwise_eq(a, b),
774
                    GeolocationManager::location_fix_bitwise_eq(b, a),
775
                    "not symmetric for ({i}, {j})"
776
                );
777
                if i != j {
778
                    assert!(
779
                        !GeolocationManager::location_fix_bitwise_eq(a, b),
780
                        "distinct extremes #{i}/#{j} compared equal"
781
                    );
782
                }
783
            }
784
        }
785
    }
786

            
787
    #[test]
788
    fn bitwise_eq_looks_at_every_field() {
789
        let base = full_fix();
790
        for (field, mutated) in single_field_mutations() {
791
            assert!(
792
                !GeolocationManager::location_fix_bitwise_eq(&base, &mutated),
793
                "`{field}` is ignored by location_fix_bitwise_eq"
794
            );
795
            assert!(
796
                !GeolocationManager::location_fix_bitwise_eq(&mutated, &base),
797
                "`{field}` comparison is asymmetric"
798
            );
799
            assert!(GeolocationManager::location_fix_bitwise_eq(
800
                &mutated, &mutated
801
            ));
802
        }
803
    }
804

            
805
    #[test]
806
    fn bitwise_eq_separates_positive_and_negative_zero() {
807
        let mut a = full_fix();
808
        a.heading_deg = 0.0;
809
        let mut b = a;
810
        b.heading_deg = -0.0;
811

            
812
        // Float equality says these are the same heading; the bit patterns
813
        // do not. `set_latest_fix` therefore treats +0 → -0 as a change.
814
        assert!(a.heading_deg == b.heading_deg);
815
        assert!(!GeolocationManager::location_fix_bitwise_eq(&a, &b));
816
    }
817

            
818
    // ─────────────────────── set_latest_fix ─────────────────────────
819

            
820
    #[test]
821
    fn repeated_identical_nan_fix_reports_no_change() {
822
        let mut mgr = GeolocationManager::new();
823
        assert!(mgr.set_latest_fix(nan_fix()), "first fix advances");
824
        for _ in 0..100 {
825
            assert!(
826
                !mgr.set_latest_fix(nan_fix()),
827
                "an unchanged NaN-carrying fix must not look like movement"
828
            );
829
        }
830
        // The one real change is still pending until the event pass drains it.
831
        assert_eq!(mgr.get_pending_events(tick()).len(), 1);
832
    }
833

            
834
    #[test]
835
    fn set_latest_fix_detects_a_change_in_every_field() {
836
        for (field, mutated) in single_field_mutations() {
837
            let mut mgr = GeolocationManager::new();
838
            assert!(mgr.set_latest_fix(full_fix()));
839
            mgr.clear_pending_event();
840

            
841
            assert!(
842
                mgr.set_latest_fix(mutated),
843
                "a change in `{field}` was not reported"
844
            );
845
            assert_eq!(
846
                mgr.get_pending_events(tick()).len(),
847
                1,
848
                "a change in `{field}` raised no GeolocationFix event"
849
            );
850
        }
851
    }
852

            
853
    #[test]
854
    fn set_latest_fix_survives_extreme_and_pathological_values() {
855
        let mut mgr = GeolocationManager::new();
856

            
857
        // Out-of-range coordinates: the manager stores whatever the backend
858
        // hands it, it is not a validator — but it must not panic.
859
        let pathological = [
860
            (f64::MAX, f64::MIN),
861
            (f64::INFINITY, f64::NEG_INFINITY),
862
            (f64::NAN, f64::NAN),
863
            (1e308, -1e308),
864
            (f64::MIN_POSITIVE, -f64::MIN_POSITIVE),
865
            (91.0, 181.0),   // beyond the WGS-84 range
866
            (-91.0, -181.0), // …and the other way
867
        ];
868

            
869
        for (lat, lon) in pathological {
870
            let f = LocationFix {
871
                latitude_deg: lat,
872
                longitude_deg: lon,
873
                accuracy_m: f32::INFINITY,
874
                altitude_m: f32::NAN,
875
                altitude_accuracy_m: f32::NAN,
876
                heading_deg: f32::NAN,
877
                speed_mps: f32::NAN,
878
                timestamp_ms: u64::MAX,
879
            };
880
            mgr.set_latest_fix(f);
881
            let got = mgr.latest_fix().expect("stored");
882
            assert_eq!(got.latitude_deg.to_bits(), lat.to_bits());
883
            assert_eq!(got.longitude_deg.to_bits(), lon.to_bits());
884
            // Idempotent re-apply: even an all-NaN coordinate pair compares
885
            // equal to itself under bit-pattern equality.
886
            assert!(
887
                !mgr.set_latest_fix(f),
888
                "re-applying the same fix is not a change"
889
            );
890
        }
891
    }
892

            
893
    #[test]
894
    fn timestamp_only_movement_counts_as_a_change() {
895
        let mut mgr = GeolocationManager::new();
896
        let mut f = nan_fix();
897
        assert!(mgr.set_latest_fix(f));
898

            
899
        f.timestamp_ms = u64::MAX;
900
        assert!(
901
            mgr.set_latest_fix(f),
902
            "a fresh sample at the same coordinates is still a new fix"
903
        );
904
        assert_eq!(mgr.latest_fix().expect("stored").timestamp_ms, u64::MAX);
905
    }
906

            
907
    #[test]
908
    fn a_changed_fix_supersedes_the_stored_error_but_an_unchanged_one_does_not() {
909
        let mut mgr = GeolocationManager::new();
910
        assert!(mgr.set_latest_fix(full_fix()));
911

            
912
        mgr.set_last_error(LocationError {
913
            code: 2,
914
            message: String::from("timed out"),
915
        });
916
        assert!(mgr.last_error.is_some());
917

            
918
        // Re-delivering the *same* fix is not a change, so the error survives.
919
        assert!(!mgr.set_latest_fix(full_fix()));
920
        assert!(
921
            mgr.last_error.is_some(),
922
            "an unchanged fix does not clear the error (documented `changed`-gated behaviour)"
923
        );
924

            
925
        // A fix that actually advanced clears it.
926
        assert!(mgr.set_latest_fix(nan_fix()));
927
        assert_eq!(mgr.last_error, None);
928
    }
929

            
930
    // ─────────────────────── set_last_error ─────────────────────────
931

            
932
    #[test]
933
    fn set_last_error_round_trips_extreme_payloads() {
934
        let huge = "x".repeat(1 << 16);
935
        let unicode = String::from("\u{0}dénié 🛰️\u{0301}\u{fffd}中文\u{1f680}");
936
        let payloads = [
937
            LocationError {
938
                code: 0,
939
                message: String::new(),
940
            },
941
            LocationError {
942
                code: u32::MAX,
943
                message: huge.clone(),
944
            },
945
            LocationError {
946
                code: 1,
947
                message: unicode.clone(),
948
            },
949
        ];
950

            
951
        for err in payloads {
952
            let mut mgr = GeolocationManager::new();
953
            mgr.set_last_error(err.clone());
954
            let got = mgr.last_error.clone().expect("error was stored");
955
            assert_eq!(got, err, "error payload did not round-trip");
956
            assert_eq!(got.message.len(), err.message.len());
957

            
958
            let events = mgr.get_pending_events(tick());
959
            assert_eq!(events.len(), 1);
960
            assert_eq!(events[0].event_type, EventType::GeolocationError);
961
        }
962

            
963
        // The huge/unicode strings survived untouched.
964
        assert_eq!(huge.len(), 1 << 16);
965
        assert!(unicode.contains('\u{0}'));
966
    }
967

            
968
    #[test]
969
    fn every_repeated_error_raises_its_own_event() {
970
        let mut mgr = GeolocationManager::new();
971
        let err = LocationError {
972
            code: 7,
973
            message: String::from("revoked"),
974
        };
975

            
976
        for _ in 0..5 {
977
            mgr.set_last_error(err.clone());
978
            let events = mgr.get_pending_events(tick());
979
            assert_eq!(
980
                events.len(),
981
                1,
982
                "a repeated error must still answer the live subscription"
983
            );
984
            assert_eq!(events[0].event_type, EventType::GeolocationError);
985
            mgr.clear_pending_event();
986
            assert!(mgr.get_pending_events(tick()).is_empty());
987
        }
988
        assert_eq!(mgr.last_error, Some(err));
989
    }
990

            
991
    // ───────────── clear_pending_event / take_pending_events ─────────
992

            
993
    #[test]
994
    fn clear_pending_event_is_idempotent_and_spares_the_diff_queue() {
995
        let mut mgr = GeolocationManager::new();
996
        mgr.diff_layout(|emit| emit(probe_cfg(false, 0.0)));
997
        mgr.set_latest_fix(full_fix());
998
        mgr.set_last_error(LocationError {
999
            code: 1,
            message: String::from("e"),
        });
        for _ in 0..3 {
            mgr.clear_pending_event();
            assert!(
                mgr.get_pending_events(tick()).is_empty(),
                "clearing twice must stay cleared"
            );
        }
        // Clearing the *event* flags does not eat the queued *diff* events —
        // they are two independent queues with two independent drains.
        let diffs = mgr.take_pending_events();
        assert_eq!(diffs.len(), 1);
        assert!(matches!(diffs[0], GeolocationDiffEvent::Subscribe { .. }));
        // …nor the stored values themselves.
        assert!(mgr.latest_fix().is_some());
        assert!(mgr.last_error.is_some());
    }
    #[test]
    fn take_pending_events_drains_in_arrival_order_and_leaves_the_queue_empty() {
        let mut mgr = GeolocationManager::new();
        mgr.diff_layout(|emit| emit(probe_cfg(false, 0.0))); // Subscribe
        mgr.diff_layout(|emit| emit(probe_cfg(true, 0.0))); // Reconfigure
        mgr.diff_layout(|_emit| {}); // Release
        let events = mgr.take_pending_events();
        assert_eq!(events.len(), 3);
        assert!(matches!(events[0], GeolocationDiffEvent::Subscribe { .. }));
        assert!(matches!(
            events[1],
            GeolocationDiffEvent::Reconfigure { .. }
        ));
        assert_eq!(events[2], GeolocationDiffEvent::Release);
        assert!(mgr.take_pending_events().is_empty(), "taken, not copied");
        assert!(mgr.take_pending_events().is_empty(), "still empty");
    }
    #[test]
    fn get_pending_events_does_not_consume_the_flags() {
        let mut mgr = GeolocationManager::new();
        mgr.set_latest_fix(full_fix());
        mgr.set_last_error(LocationError {
            code: 3,
            message: String::from("boom"),
        });
        // Both flags are up: fix first, then error.
        for _ in 0..3 {
            let events = mgr.get_pending_events(tick());
            assert_eq!(events.len(), 2, "the getter is a read, not a drain");
            assert_eq!(events[0].event_type, EventType::GeolocationFix);
            assert_eq!(events[1].event_type, EventType::GeolocationError);
            assert_eq!(events[0].target, DomNodeId::ROOT);
            assert_eq!(events[1].target, DomNodeId::ROOT);
        }
        mgr.clear_pending_event();
        assert!(mgr.get_pending_events(tick()).is_empty());
    }
    // ──────────────────────── diff_layout ───────────────────────────
    #[test]
    fn no_probes_on_a_fresh_manager_emits_nothing() {
        let mut mgr = GeolocationManager::new();
        for _ in 0..4 {
            mgr.diff_layout(|_emit| {});
            assert_eq!(mgr.refcount(), 0);
            assert!(!mgr.has_active_subscription());
            assert_eq!(mgr.active_config, None);
            assert!(
                mgr.take_pending_events().is_empty(),
                "0 → 0 must not emit a spurious Release"
            );
        }
    }
    #[test]
    fn refcount_tracks_the_probe_count_and_gates_the_subscription_flag() {
        let mut mgr = GeolocationManager::new();
        mgr.diff_layout(|emit| {
            for _ in 0..10_000 {
                emit(probe_cfg(false, 0.0));
            }
        });
        assert_eq!(mgr.refcount(), 10_000);
        assert!(mgr.has_active_subscription());
        assert_eq!(mgr.take_pending_events().len(), 1, "one Subscribe, not 10k");
        // Probe count churn with an unchanged config emits nothing at all.
        mgr.diff_layout(|emit| {
            for _ in 0..3 {
                emit(probe_cfg(false, 0.0));
            }
        });
        assert_eq!(mgr.refcount(), 3);
        assert!(mgr.has_active_subscription());
        assert!(mgr.take_pending_events().is_empty());
        // The boundary: exactly one probe still counts as subscribed.
        mgr.diff_layout(|emit| emit(probe_cfg(false, 0.0)));
        assert_eq!(mgr.refcount(), 1);
        assert!(mgr.has_active_subscription());
        mgr.diff_layout(|_emit| {});
        assert_eq!(mgr.refcount(), 0);
        assert!(!mgr.has_active_subscription(), "0 probes ⇒ no subscription");
        assert_eq!(
            mgr.take_pending_events(),
            vec![GeolocationDiffEvent::Release]
        );
    }
    #[test]
    fn the_first_probes_config_wins_the_subscribe() {
        let mut mgr = GeolocationManager::new();
        mgr.diff_layout(|emit| {
            emit(probe_cfg(true, 25.0));
            emit(probe_cfg(false, 999.0)); // disagreeing second probe
            emit(probe_cfg(false, 0.0));
        });
        assert_eq!(mgr.refcount(), 3);
        let events = mgr.take_pending_events();
        assert_eq!(events.len(), 1);
        match events[0] {
            GeolocationDiffEvent::Subscribe { config } => {
                assert!(config.high_accuracy);
                assert_eq!(config.max_accuracy_m, 25.0);
            }
            ref other => panic!("expected Subscribe, got {other:?}"),
        }
        assert_eq!(mgr.active_config, Some(probe_cfg(true, 25.0)));
        // A frame whose *first* probe keeps the active config emits nothing,
        // even when a later probe disagrees.
        mgr.diff_layout(|emit| {
            emit(probe_cfg(true, 25.0));
            emit(probe_cfg(false, 0.0));
        });
        assert!(mgr.take_pending_events().is_empty());
    }
    #[test]
    fn release_clears_the_fix_and_a_resubscribe_starts_from_scratch() {
        let mut mgr = GeolocationManager::new();
        mgr.diff_layout(|emit| emit(probe_cfg(false, 0.0)));
        assert!(mgr.set_latest_fix(full_fix()));
        assert!(mgr.take_pending_events().len() == 1);
        mgr.diff_layout(|_emit| {}); // Release
        assert_eq!(mgr.latest_fix(), None, "Release drops the stale fix");
        assert_eq!(mgr.active_config, None);
        assert_eq!(
            mgr.take_pending_events(),
            vec![GeolocationDiffEvent::Release]
        );
        // Re-mounting emits a fresh Subscribe (not a Reconfigure) and the fix
        // stays None until the backend delivers a new sample.
        mgr.diff_layout(|emit| emit(probe_cfg(true, 5.0)));
        assert_eq!(mgr.refcount(), 1);
        assert_eq!(mgr.latest_fix(), None);
        let events = mgr.take_pending_events();
        assert_eq!(events.len(), 1);
        assert_eq!(
            events[0],
            GeolocationDiffEvent::Subscribe {
                config: probe_cfg(true, 5.0)
            }
        );
    }
    #[test]
    fn release_leaves_the_fix_event_flag_raised_with_no_fix_behind_it() {
        // Characterisation of the current behaviour: `diff_layout` clears
        // `latest_fix` on Release but not `pending_event`, so the event pass
        // still dispatches a GeolocationFix whose payload is already gone.
        // Callbacks must therefore tolerate `get_geolocation_fix() == None`
        // inside a GeolocationFix handler.
        let mut mgr = GeolocationManager::new();
        mgr.diff_layout(|emit| emit(probe_cfg(false, 0.0)));
        assert!(mgr.set_latest_fix(full_fix()));
        mgr.diff_layout(|_emit| {}); // Release
        assert_eq!(mgr.latest_fix(), None);
        let events = mgr.get_pending_events(tick());
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].event_type, EventType::GeolocationFix);
        mgr.clear_pending_event();
        assert!(mgr.get_pending_events(tick()).is_empty());
    }
    #[test]
    fn a_nan_probe_config_settles_like_any_other() {
        // FIXED (was "re_emits_reconfigure_on_every_frame"): the Reconfigure check uses
        // `PartialEq` on `GeolocationProbeConfig`, whose `max_accuracy_m` is an f32.
        // That PartialEq now compares by BIT PATTERN (see core/src/geolocation.rs), so a
        // NaN config equals itself and an *unchanged* config no longer looks drifted —
        // it settles after one Reconfigure instead of re-queuing every frame.
        let nan_cfg = probe_cfg(false, f32::NAN);
        let mut mgr = GeolocationManager::new();
        mgr.diff_layout(|emit| emit(nan_cfg));
        assert_eq!(mgr.take_pending_events().len(), 1, "the initial Subscribe");
        for _ in 0..3 {
            mgr.diff_layout(|emit| emit(nan_cfg));
            assert!(
                mgr.take_pending_events().is_empty(),
                "an unchanged NaN config must NOT re-queue a Reconfigure"
            );
        }
        // A sane config also settles immediately.
        mgr.diff_layout(|emit| emit(probe_cfg(false, 0.0)));
        assert_eq!(
            mgr.take_pending_events().len(),
            1,
            "one Reconfigure to sane"
        );
        mgr.diff_layout(|emit| emit(probe_cfg(false, 0.0)));
        assert!(mgr.take_pending_events().is_empty(), "then quiet");
    }
    #[test]
    fn extreme_probe_configs_survive_the_diff() {
        let extremes = [
            probe_cfg(true, f32::MAX),
            probe_cfg(false, f32::INFINITY),
            probe_cfg(true, -0.0),
            GeolocationProbeConfig {
                high_accuracy: true,
                background: true,
                max_accuracy_m: f32::MIN_POSITIVE,
                min_interval_ms: u32::MAX,
            },
        ];
        let mut mgr = GeolocationManager::new();
        for cfg in extremes {
            mgr.diff_layout(|emit| emit(cfg));
            assert_eq!(mgr.refcount(), 1);
            assert_eq!(mgr.active_config, Some(cfg));
            let events = mgr.take_pending_events();
            assert_eq!(
                events.len(),
                1,
                "each distinct config emits exactly one event"
            );
            match events[0] {
                GeolocationDiffEvent::Subscribe { config }
                | GeolocationDiffEvent::Reconfigure { config } => {
                    assert_eq!(
                        config.max_accuracy_m.to_bits(),
                        cfg.max_accuracy_m.to_bits()
                    );
                    assert_eq!(config.min_interval_ms, cfg.min_interval_ms);
                }
                GeolocationDiffEvent::Release => panic!("probes are mounted, not released"),
            }
        }
    }
    // ─────────────────────── equality invariants ────────────────────
    #[test]
    fn manager_equality_is_bit_blind_for_nan_fixes() {
        // The derived `PartialEq` on the manager inherits float semantics:
        // a manager holding a NaN-carrying fix is not even equal to its own
        // clone. Callers must not use `==` on the manager to detect movement
        // — that is what `set_latest_fix`'s return value is for.
        let mut with_nan = GeolocationManager::new();
        with_nan.set_latest_fix(nan_fix());
        assert_ne!(with_nan, with_nan.clone());
        let mut without_nan = GeolocationManager::new();
        without_nan.set_latest_fix(full_fix());
        assert_eq!(without_nan, without_nan.clone());
    }
}