1
//! Permission manager — the cross-platform piece of the "permission-as-DOM"
2
//! architecture: a capability is requested by putting an invisible probe node
3
//! in the DOM, and revoked by removing it.
4
//!
5
//! Stores per-capability state + a refcount keyed on bearing DOM nodes. Three
6
//! callers drive it:
7
//!
8
//! - The **layout pass** scans the styled DOM for permission-bearing `NodeTypes`
9
//!   (`GeolocationProbe`, `CameraPreview`, `SensorProbe`, etc.) and calls `subscribe` / `release`
10
//!   to maintain the refcount. The diff between consecutive layouts yields the
11
//!   [`PermissionDiffEvent`]s the platform backend translates into native subscribe/release
12
//!   operations.
13
//!
14
//! - The **platform backend** (`dll/src/desktop/extra/permission/<plat>.rs`) observes the diff
15
//!   events and issues the matching native call (`AVCaptureDevice.requestAccess` on iOS,
16
//!   `ActivityCompat.requestPermissions` on Android, etc.). When the OS callback fires it calls
17
//!   `set_status`, which is mirrored back into callback land via the `CallbackInfo` accessor
18
//!   `get_permission_status`.
19
//!
20
//! - **Callbacks** read `get_status(...)` synchronously to decide whether to mount a
21
//!   permission-bearing node or show a fallback (the "user-gesture-first" pattern in the research
22
//!   brief §8.3).
23
//!
24
//! The manager has no platform dependencies and is `no_std`-friendly (uses
25
//! `alloc::collections::BTreeMap` + `alloc::vec::Vec`).
26

            
27
use alloc::{collections::btree_map::BTreeMap, vec::Vec};
28

            
29
use azul_core::{
30
    dom::DomNodeId,
31
    events::{EventData, EventProvider, EventSource as CoreEventSource, EventType, SyntheticEvent},
32
    task::Instant,
33
};
34

            
35
/// One closed enum covering every capability the framework can request.
36
///
37
/// The variant set deliberately omits fields like `facing` / `accuracy` /
38
/// `mode` from the research brief — those parameters belong on the bearing
39
/// `NodeType` (e.g. `NodeType::CameraPreview(CameraSource::Front)`) so they
40
/// can change between layout passes without forcing a re-prompt. The
41
/// `Reconfigure` diff event carries the new params when a node mutates.
42
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
43
#[repr(C)]
44
pub enum Capability {
45
    /// Camera access (front or back, declared per node).
46
    Camera,
47
    /// Microphone access. iOS gates this separately from camera.
48
    Microphone,
49
    /// Entire-screen or per-window capture.
50
    ScreenCapture,
51
    /// Geolocation (precise vs approximate is per-node, not per-capability).
52
    Geolocation,
53
    /// Background geolocation. A separate iOS / Android permission gate.
54
    GeolocationBackground,
55
    /// `FaceID` / `TouchID` / Hello / `BiometricPrompt`.
56
    Biometric,
57
    /// Motion sensor data (accelerometer + gyro + magnetometer).
58
    Motion,
59
    /// `PhotoKit` / `MediaStore` read.
60
    PhotoLibrary,
61
    /// `PhotoKit` add-only / `MediaStore` write.
62
    PhotoLibraryWrite,
63
    /// Contacts list.
64
    Contacts,
65
    /// Calendar entries.
66
    Calendars,
67
    /// Reminders (iOS only — Android collapses into Calendars).
68
    Reminders,
69
    /// Push / local notification scheduling.
70
    Notifications,
71
    /// Bluetooth foreground.
72
    Bluetooth,
73
    /// Bluetooth background. Separate iOS Info.plist key + Android permission.
74
    BluetoothBackground,
75
    /// Nearby Wi-Fi (Android 13+).
76
    NearbyWifi,
77
    /// Local network multicast (iOS 14+).
78
    LocalNetwork,
79
    /// iOS App Tracking Transparency (`IDFA` consent, iOS 14.5+).
80
    AppTrackingTransparency,
81
    /// Raw HID access - macOS "Input Monitoring". APPENDED at the end for ABI
82
    /// stability: this enum crosses the C API, so a variant inserted in the
83
    /// middle would renumber every discriminant after it.
84
    ///
85
    /// The odd one out in this list, and worth saying why it belongs: every
86
    /// other capability here gates a SENSOR or a DATA STORE, while this gates
87
    /// reading input devices the app does not own. macOS models it as exactly
88
    /// the same kind of thing - a TCC permission with a `Check`/`Request` pair
89
    /// - so an app that wants a flight stick or a wheel can ASK, instead of
90
    /// silently getting an empty device list forever (9f-i-a-i).
91
    ///
92
    /// macOS ONLY, and that is not an omission: Linux gates `/dev/hidraw*`
93
    /// with file permissions and udev rules, which no runtime API can request;
94
    /// Windows `RawInput` needs no permission at all; and neither mobile
95
    /// platform exposes raw HID. Those backends leave it `NotDetermined`,
96
    /// which is honest - there is nothing to ask.
97
    InputMonitoring,
98
}
99

            
100
/// Quality of a granted permission. Matches research/08 §2's quality split.
101
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
102
#[repr(C)]
103
pub enum PermissionQuality {
104
    /// Full: precise location, full photo library, etc.
105
    Full,
106
    /// Reduced: approximate location, "Selected Photos" partial access, etc.
107
    Reduced,
108
}
109

            
110
/// State machine the manager tracks per-capability.
111
///
112
/// The five canonical states (`NotDetermined` / `Requested` / `Granted` /
113
/// `Denied` / `Restricted`) cover what every supported platform reports.
114
/// `EphemeralGranted` is the iOS 14+ "Allow Once" / Android 11+ one-time grant
115
/// — semantically a Granted that the OS will reset to `NotDetermined` at the
116
/// next activity launch.
117
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
118
#[repr(C, u8)]
119
pub enum PermissionState {
120
    /// Initial — no prompt has been shown.
121
    NotDetermined,
122
    /// OS prompt is currently visible / in-flight.
123
    Requested,
124
    /// User granted access.
125
    Granted(PermissionQuality),
126
    /// User denied access (with or without "don't ask again").
127
    Denied,
128
    /// MDM / parental controls / kiosk policy blocks the prompt entirely.
129
    Restricted,
130
    /// iOS "Allow Once" / Android one-time. Reverts on next app launch.
131
    EphemeralGranted(bool),
132
}
133

            
134
impl PermissionState {
135
    /// `true` if the capability is currently usable, regardless of quality.
136
    #[must_use]
137
20
    pub const fn is_granted(self) -> bool {
138
20
        matches!(self, Self::Granted(..) | Self::EphemeralGranted(..))
139
20
    }
140

            
141
    /// `true` if a re-prompt could plausibly flip this to `Granted`.
142
    #[must_use]
143
15
    pub const fn could_re_prompt(self) -> bool {
144
15
        matches!(self, Self::NotDetermined)
145
15
    }
146
}
147

            
148
/// Diff event emitted at the end of each layout pass for the platform
149
/// backend to translate into native subscribe / release / reconfigure calls.
150
///
151
/// `Subscribe` fires the first time a capability's refcount transitions from
152
/// zero to one (i.e. the first permission-bearing node of its kind appears).
153
/// `Release` fires when the refcount drops back to zero. `Reconfigure` is
154
/// reserved for in-place parameter changes (e.g. camera-facing front → back)
155
/// once `CameraPreview` lands as a `NodeType` — kept in the enum so platform
156
/// backends can ignore it cleanly until then.
157
#[derive(Copy, Debug, Clone, PartialEq, Eq)]
158
#[repr(C, u8)]
159
pub enum PermissionDiffEvent {
160
    /// First appearance of `capability` in the layout. Refcount went 0 → 1.
161
    Subscribe {
162
        capability: Capability,
163
        node_id: DomNodeId,
164
    },
165
    /// Last bearing node left the layout. Refcount went 1 → 0.
166
    Release { capability: Capability },
167
    /// Reserved for future use — currently never emitted. The diff path will
168
    /// fire it once `CameraPreview` etc. land with parameter fields.
169
    Reconfigure { capability: Capability },
170
}
171

            
172
/// Per-capability state held across frames.
173
///
174
/// `refcount` is the number of distinct DOM nodes currently in the layout
175
/// that subscribed to this capability. `last_subscriber` is the node that
176
/// caused the most recent 0 → 1 transition; the platform backend uses it
177
/// to anchor permission-related events back to a node (so an
178
/// `On::CameraPermissionDenied` callback fires on the right `CameraPreview`).
179
#[derive(Copy, Debug, Clone, PartialEq, Eq)]
180
pub struct CapabilityEntry {
181
    pub state: PermissionState,
182
    pub refcount: u32,
183
    pub last_subscriber: Option<DomNodeId>,
184
}
185

            
186
impl CapabilityEntry {
187
330
    const fn new() -> Self {
188
330
        Self {
189
330
            state: PermissionState::NotDetermined,
190
330
            refcount: 0,
191
330
            last_subscriber: None,
192
330
        }
193
330
    }
194
}
195

            
196
/// Cross-platform permission manager.
197
///
198
/// One per `App` (capabilities live at process scope, not per-window — a
199
/// camera session backing two windows multiplexes via a single capture
200
/// stream; cf. research/08 §8.6). `LayoutWindow` holds a borrow / `Arc`
201
/// reference, not an owned copy.
202
#[derive(Debug, Clone, PartialEq, Eq, Default)]
203
pub struct PermissionManager {
204
    /// Latest known state + refcount per capability.
205
    pub statuses: BTreeMap<Capability, CapabilityEntry>,
206
    /// Diff events emitted since the last call to `take_pending_events`.
207
    ///
208
    /// Held as a queue so the platform backend can drain it once per frame
209
    /// instead of receiving callbacks during the layout pass itself (the
210
    /// layout pass is on a hot path that should not block on FFI).
211
    pending_events: Vec<PermissionDiffEvent>,
212
    /// State flips folded since the last event pass, with the capability's
213
    /// most recent subscriber node (MWA-A1b). Read by the `EventProvider`
214
    /// impl to synthesize targeted `PermissionChanged` events; cleared by
215
    /// [`clear_pending_changed`](Self::clear_pending_changed) after dispatch.
216
    pending_changed: Vec<(Capability, Option<DomNodeId>)>,
217
}
218

            
219
impl EventProvider for PermissionManager {
220
    /// Yield one `PermissionChanged` event per state flip folded since the
221
    /// last pass — targeted at the capability's most recent subscriber node
222
    /// when known (so a probe node's Hover callback fires), else the root
223
    /// (window-level filters match either way).
224
229
    fn get_pending_events(&self, timestamp: Instant) -> Vec<SyntheticEvent> {
225
229
        self.pending_changed
226
229
            .iter()
227
271
            .map(|(_capability, node)| {
228
128
                SyntheticEvent::new(
229
128
                    EventType::PermissionChanged,
230
128
                    CoreEventSource::User,
231
128
                    node.unwrap_or(DomNodeId::ROOT),
232
128
                    timestamp.clone(),
233
128
                    EventData::None,
234
                )
235
128
            })
236
229
            .collect()
237
229
    }
238
}
239

            
240
impl PermissionManager {
241
    #[must_use]
242
7849
    pub fn new() -> Self {
243
7849
        Self::default()
244
7849
    }
245

            
246
    /// Read the most recently observed state for `capability`.
247
    #[must_use]
248
2998
    pub fn get_status(&self, capability: Capability) -> PermissionState {
249
2998
        self.statuses
250
2998
            .get(&capability)
251
2998
            .map_or(PermissionState::NotDetermined, |e| e.state)
252
2998
    }
253

            
254
    /// Record that `node_id` now needs `capability`. The first subscriber
255
    /// (refcount 0 → 1) enqueues a `Subscribe` event for the platform layer
256
    /// to translate into a native prompt.
257
29
    pub fn subscribe(&mut self, capability: Capability, node_id: DomNodeId) {
258
29
        let entry = self
259
29
            .statuses
260
29
            .entry(capability)
261
29
            .or_insert_with(CapabilityEntry::new);
262
29
        entry.last_subscriber = Some(node_id);
263
29
        entry.refcount = entry.refcount.saturating_add(1);
264
29
        if entry.refcount == 1 {
265
23
            self.pending_events.push(PermissionDiffEvent::Subscribe {
266
23
                capability,
267
23
                node_id,
268
23
            });
269
23
        }
270
29
    }
271

            
272
    /// Drop one subscription. The last release (refcount 1 → 0) enqueues a
273
    /// `Release` event so the platform backend can tear the session down.
274
37
    pub fn release(&mut self, capability: Capability) {
275
37
        let Some(entry) = self.statuses.get_mut(&capability) else {
276
19
            return;
277
        };
278
18
        if entry.refcount == 0 {
279
10
            return;
280
8
        }
281
8
        entry.refcount -= 1;
282
8
        if entry.refcount == 0 {
283
6
            entry.last_subscriber = None;
284
6
            self.pending_events
285
6
                .push(PermissionDiffEvent::Release { capability });
286
6
        }
287
37
    }
288

            
289
    /// Force `capability`'s refcount down to zero. Used by `recheck_all` when
290
    /// the OS revokes a permission out from under us — we have to tear down
291
    /// the subscription regardless of how many DOM nodes still reference it.
292
23
    pub fn force_release(&mut self, capability: Capability) {
293
23
        let Some(entry) = self.statuses.get_mut(&capability) else {
294
20
            return;
295
        };
296
3
        if entry.refcount == 0 {
297
1
            return;
298
2
        }
299
2
        entry.refcount = 0;
300
2
        entry.last_subscriber = None;
301
2
        self.pending_events
302
2
            .push(PermissionDiffEvent::Release { capability });
303
23
    }
304

            
305
    /// Platform backend writes the OS-observed state back into the manager.
306
    ///
307
    /// Returns true if the state actually changed — the caller can use this
308
    /// signal to mark the window dirty for relayout (so a permission-aware
309
    /// callback gets a chance to render the new state).
310
359
    pub fn set_status(&mut self, capability: Capability, state: PermissionState) -> bool {
311
359
        let entry = self
312
359
            .statuses
313
359
            .entry(capability)
314
359
            .or_insert_with(CapabilityEntry::new);
315
359
        if entry.state == state {
316
40
            return false;
317
319
        }
318
319
        entry.state = state;
319
        // MWA-A1b: remember the flip so the EventProvider can synthesize a
320
        // PermissionChanged event, targeted at the subscriber node when known.
321
319
        self.pending_changed
322
319
            .push((capability, entry.last_subscriber));
323
319
        true
324
359
    }
325

            
326
    /// Clear the pending state-flip queue. The dll calls this after the
327
    /// event pass has collected the `PermissionChanged` events.
328
153
    pub fn clear_pending_changed(&mut self) {
329
153
        self.pending_changed.clear();
330
153
    }
331

            
332
    /// `true` while any capability sits in [`PermissionState::Requested`]
333
    /// (an OS prompt is in flight and its outcome will arrive through the
334
    /// async channel) — the capability pump keeps its timer armed so the
335
    /// outcome reaches callbacks even in an otherwise idle app (MWA-A1b
336
    /// arming signal).
337
    #[must_use]
338
78
    pub fn has_pending_async(&self) -> bool {
339
78
        self.statuses
340
78
            .values()
341
130
            .any(|e| e.state == PermissionState::Requested)
342
78
    }
343

            
344
    /// Drain queued diff events. Platform backend calls this once per frame.
345
55
    pub fn take_pending_events(&mut self) -> Vec<PermissionDiffEvent> {
346
55
        core::mem::take(&mut self.pending_events)
347
55
    }
348

            
349
    /// Refcount snapshot — primarily for diagnostics and tests.
350
    #[must_use]
351
84
    pub fn refcount(&self, capability: Capability) -> u32 {
352
84
        self.statuses.get(&capability).map_or(0, |e| e.refcount)
353
84
    }
354

            
355
    /// Pre-compute the next-frame refcount map from a closure that yields
356
    /// `(capability, node_id)` pairs for every permission-bearing node in
357
    /// the current styled DOM. Then diff against the existing refcounts and
358
    /// enqueue the matching Subscribe / Release events.
359
    ///
360
    /// This is the entry point the layout pass calls. It exists as a closure
361
    /// rather than a direct `StyledDom` walker because `StyledDom` lives in
362
    /// `azul_core::styled_dom` and would otherwise force a (tiny) cycle.
363
28
    pub fn diff_layout<F>(&mut self, mut for_each_bearing_node: F)
364
28
    where
365
28
        F: FnMut(&mut dyn FnMut(Capability, DomNodeId)),
366
    {
367
        // 1. Drain the new layout into (capability → (count, first_node)).
368
28
        let mut next: BTreeMap<Capability, (u32, Option<DomNodeId>)> = BTreeMap::new();
369
10048
        for_each_bearing_node(&mut |cap, node| {
370
10048
            let slot = next.entry(cap).or_insert((0, None));
371
10048
            slot.0 = slot.0.saturating_add(1);
372
10048
            if slot.1.is_none() {
373
47
                slot.1 = Some(node);
374
10001
            }
375
10048
        });
376

            
377
        // 2. Compute the new state map from the old one + the next layout.
378
        // Iterate every capability we know about plus any new ones.
379
28
        let mut all_caps: Vec<Capability> = self.statuses.keys().copied().collect();
380
47
        for cap in next.keys() {
381
47
            if !all_caps.contains(cap) {
382
34
                all_caps.push(*cap);
383
34
            }
384
        }
385

            
386
123
        for cap in all_caps {
387
95
            let (new_count, first_node) = next.get(&cap).copied().unwrap_or((0, None));
388
95
            let entry = self
389
95
                .statuses
390
95
                .entry(cap)
391
95
                .or_insert_with(CapabilityEntry::new);
392
95
            let old_count = entry.refcount;
393
95
            entry.refcount = new_count;
394
95
            if new_count == 0 && old_count > 0 {
395
29
                entry.last_subscriber = None;
396
29
                self.pending_events
397
29
                    .push(PermissionDiffEvent::Release { capability: cap });
398
66
            } else if new_count > 0 && old_count == 0 {
399
36
                let node = first_node.unwrap_or(DomNodeId::ROOT);
400
36
                entry.last_subscriber = first_node;
401
36
                self.pending_events.push(PermissionDiffEvent::Subscribe {
402
36
                    capability: cap,
403
36
                    node_id: node,
404
36
                });
405
36
            }
406
        }
407
28
    }
408
}
409

            
410
// ────────── Async result channel (platform backend → manager) ─────────
411
//
412
// When a `Subscribe` fires an OS prompt, the result arrives later on an
413
// arbitrary thread (an iOS completion handler / Android
414
// `onRequestPermissionsResult`) where there's no handle to the live
415
// `PermissionManager` (it lives inside the window's `LayoutWindow`). The
416
// platform backend parks the resolved state here; the layout pass drains
417
// it once per frame via [`drain_async_results`] and applies each through
418
// [`PermissionManager::set_status`]. Pure Rust — no platform dependency,
419
// so it satisfies SUPER_PLAN_2 §0.5's "no platform deps in azul-layout".
420

            
421
static ASYNC_RESULTS: std::sync::Mutex<Vec<(Capability, PermissionState)>> =
422
    std::sync::Mutex::new(Vec::new());
423

            
424
/// Park an async permission result. Called by a platform backend (in the
425
/// dll) when an OS prompt resolves. Thread-safe; recovers from a poisoned
426
/// lock so one panicking applier can't wedge delivery forever.
427
411
pub fn push_async_result(capability: Capability, state: PermissionState) {
428
411
    let mut q = ASYNC_RESULTS
429
411
        .lock()
430
411
        .unwrap_or_else(std::sync::PoisonError::into_inner);
431
411
    q.push((capability, state));
432
411
}
433

            
434
/// Drain everything parked by [`push_async_result`], in arrival order.
435
/// Called once per layout pass; the caller applies each result through
436
/// [`PermissionManager::set_status`] and relayouts if any changed.
437
15
pub fn drain_async_results() -> Vec<(Capability, PermissionState)> {
438
15
    let mut q = ASYNC_RESULTS
439
15
        .lock()
440
15
        .unwrap_or_else(std::sync::PoisonError::into_inner);
441
15
    core::mem::take(&mut *q)
442
15
}
443

            
444
#[cfg(test)]
445
mod tests {
446
    use super::*;
447

            
448
    /// `Capability` crosses the C API, so its discriminants are an ABI.
449
    /// `InputMonitoring` must be LAST - inserting it anywhere else renumbers
450
    /// every variant after it, and a binding compiled against the old header
451
    /// would then ask for the wrong permission with nothing failing to
452
    /// compile.
453
    #[test]
454
1
    fn input_monitoring_is_appended_and_does_not_renumber_the_others() {
455
1
        assert_eq!(Capability::Camera as i32, 0);
456
1
        assert_eq!(Capability::Microphone as i32, 1);
457
1
        assert_eq!(Capability::ScreenCapture as i32, 2);
458
        // The variant that was last before this change stays where it was.
459
1
        assert_eq!(Capability::AppTrackingTransparency as i32, 17);
460
1
        assert_eq!(Capability::InputMonitoring as i32, 18);
461
1
    }
462

            
463
    use azul_core::dom::{DomId, NodeId};
464

            
465
10
    fn node(idx: usize) -> DomNodeId {
466
10
        DomNodeId {
467
10
            dom: DomId::ROOT_ID,
468
10
            node: NodeId::from_usize(idx).into(),
469
10
        }
470
10
    }
471

            
472
    #[test]
473
1
    fn subscribe_release_round_trip_emits_paired_events() {
474
1
        let mut mgr = PermissionManager::new();
475
1
        assert_eq!(
476
1
            mgr.get_status(Capability::Geolocation),
477
            PermissionState::NotDetermined
478
        );
479
1
        assert_eq!(mgr.refcount(Capability::Geolocation), 0);
480

            
481
1
        mgr.subscribe(Capability::Geolocation, node(1));
482
1
        assert_eq!(mgr.refcount(Capability::Geolocation), 1);
483
1
        let events = mgr.take_pending_events();
484
1
        assert_eq!(events.len(), 1);
485
1
        assert!(matches!(
486
1
            events[0],
487
            PermissionDiffEvent::Subscribe {
488
                capability: Capability::Geolocation,
489
                ..
490
            }
491
        ));
492

            
493
1
        mgr.release(Capability::Geolocation);
494
1
        assert_eq!(mgr.refcount(Capability::Geolocation), 0);
495
1
        let events = mgr.take_pending_events();
496
1
        assert_eq!(events.len(), 1);
497
1
        assert!(matches!(
498
1
            events[0],
499
            PermissionDiffEvent::Release {
500
                capability: Capability::Geolocation
501
            }
502
        ));
503
1
    }
504

            
505
    #[test]
506
1
    fn second_subscriber_does_not_re_emit_subscribe() {
507
1
        let mut mgr = PermissionManager::new();
508
1
        mgr.subscribe(Capability::Camera, node(1));
509
1
        mgr.subscribe(Capability::Camera, node(2));
510
1
        assert_eq!(mgr.refcount(Capability::Camera), 2);
511
1
        let events = mgr.take_pending_events();
512
        // Exactly one Subscribe should have been emitted across both subscribes.
513
1
        assert_eq!(events.len(), 1);
514
1
    }
515

            
516
    #[test]
517
1
    fn release_only_after_last_subscriber_drops() {
518
1
        let mut mgr = PermissionManager::new();
519
1
        mgr.subscribe(Capability::Microphone, node(1));
520
1
        mgr.subscribe(Capability::Microphone, node(2));
521
        // Drain the initial Subscribe so the assertion below isolates Release.
522
1
        drop(mgr.take_pending_events());
523

            
524
1
        mgr.release(Capability::Microphone);
525
1
        assert_eq!(mgr.refcount(Capability::Microphone), 1);
526
1
        assert!(mgr.take_pending_events().is_empty());
527

            
528
1
        mgr.release(Capability::Microphone);
529
1
        assert_eq!(mgr.refcount(Capability::Microphone), 0);
530
1
        let events = mgr.take_pending_events();
531
1
        assert_eq!(events.len(), 1);
532
1
        assert!(matches!(
533
1
            events[0],
534
            PermissionDiffEvent::Release {
535
                capability: Capability::Microphone
536
            }
537
        ));
538
1
    }
539

            
540
    #[test]
541
1
    fn force_release_drops_refcount_and_emits_event() {
542
1
        let mut mgr = PermissionManager::new();
543
1
        mgr.subscribe(Capability::Camera, node(1));
544
1
        mgr.subscribe(Capability::Camera, node(2));
545
1
        drop(mgr.take_pending_events());
546

            
547
1
        mgr.force_release(Capability::Camera);
548
1
        assert_eq!(mgr.refcount(Capability::Camera), 0);
549
1
        let events = mgr.take_pending_events();
550
1
        assert_eq!(events.len(), 1);
551
1
        assert!(matches!(
552
1
            events[0],
553
            PermissionDiffEvent::Release {
554
                capability: Capability::Camera
555
            }
556
        ));
557
1
    }
558

            
559
    #[test]
560
1
    fn set_status_returns_change_flag() {
561
1
        let mut mgr = PermissionManager::new();
562
1
        assert!(mgr.set_status(Capability::Camera, PermissionState::Requested));
563
1
        assert!(!mgr.set_status(Capability::Camera, PermissionState::Requested));
564
1
        assert!(mgr.set_status(
565
1
            Capability::Camera,
566
1
            PermissionState::Granted(PermissionQuality::Full)
567
        ));
568
1
        assert!(mgr.get_status(Capability::Camera).is_granted());
569
1
    }
570

            
571
    #[test]
572
1
    fn diff_layout_picks_up_appearing_node_and_releases_it_next_frame() {
573
1
        let mut mgr = PermissionManager::new();
574

            
575
        // Frame 1: GeolocationProbe present.
576
1
        mgr.diff_layout(|emit| {
577
1
            emit(Capability::Geolocation, node(7));
578
1
        });
579
1
        assert_eq!(mgr.refcount(Capability::Geolocation), 1);
580
1
        let events = mgr.take_pending_events();
581
1
        assert_eq!(events.len(), 1);
582
1
        assert!(matches!(
583
1
            events[0],
584
            PermissionDiffEvent::Subscribe {
585
                capability: Capability::Geolocation,
586
                ..
587
            }
588
        ));
589

            
590
        // Frame 2: probe removed.
591
1
        mgr.diff_layout(|_emit| { /* no bearing nodes this frame */ });
592
1
        assert_eq!(mgr.refcount(Capability::Geolocation), 0);
593
1
        let events = mgr.take_pending_events();
594
1
        assert_eq!(events.len(), 1);
595
1
        assert!(matches!(
596
1
            events[0],
597
            PermissionDiffEvent::Release {
598
                capability: Capability::Geolocation
599
            }
600
        ));
601
1
    }
602

            
603
    #[test]
604
1
    fn diff_layout_re_emits_subscribe_after_release_cycle() {
605
1
        let mut mgr = PermissionManager::new();
606

            
607
1
        mgr.diff_layout(|emit| emit(Capability::Camera, node(1)));
608
1
        drop(mgr.take_pending_events());
609

            
610
1
        mgr.diff_layout(|_emit| {});
611
1
        drop(mgr.take_pending_events());
612

            
613
        // Same capability reappears — must emit Subscribe again because the
614
        // platform tore the session down on the prior Release.
615
1
        mgr.diff_layout(|emit| emit(Capability::Camera, node(2)));
616
1
        let events = mgr.take_pending_events();
617
1
        assert_eq!(events.len(), 1);
618
1
        assert!(matches!(
619
1
            events[0],
620
            PermissionDiffEvent::Subscribe {
621
                capability: Capability::Camera,
622
                ..
623
            }
624
        ));
625
1
    }
626

            
627
    #[test]
628
1
    fn async_results_round_trip_through_manager() {
629
        // The channel is a process-global and libtest runs tests in parallel:
630
        // serialize against every other test that touches it.
631
1
        let _serialize = autotest_generated::lock_async_channel();
632
        // The channel is a process-global; clear anything a prior test or
633
        // ordering left behind so this test is self-contained.
634
1
        drop(drain_async_results());
635

            
636
1
        push_async_result(
637
1
            Capability::Camera,
638
1
            PermissionState::Granted(PermissionQuality::Full),
639
        );
640
1
        push_async_result(Capability::Geolocation, PermissionState::Denied);
641

            
642
1
        let drained = drain_async_results();
643
1
        assert_eq!(drained.len(), 2, "both parked results drain in order");
644
        // Arrival order preserved.
645
1
        assert_eq!(drained[0].0, Capability::Camera);
646
1
        assert_eq!(drained[1].0, Capability::Geolocation);
647

            
648
        // Applying them through the manager reflects in get_status — this is
649
        // exactly what the dll layout pass does each frame.
650
1
        let mut mgr = PermissionManager::new();
651
3
        for (cap, state) in drained {
652
2
            mgr.set_status(cap, state);
653
2
        }
654
1
        assert!(mgr.get_status(Capability::Camera).is_granted());
655
1
        assert_eq!(
656
1
            mgr.get_status(Capability::Geolocation),
657
            PermissionState::Denied
658
        );
659

            
660
        // A second drain is empty — the queue was taken, not copied.
661
1
        assert!(drain_async_results().is_empty());
662
1
    }
663
}
664

            
665
#[cfg(test)]
666
mod pump_provider_tests {
667
    use azul_core::task::{Instant, SystemTick};
668

            
669
    use super::*;
670

            
671
5
    fn ts() -> Instant {
672
5
        Instant::Tick(SystemTick::new(0))
673
5
    }
674

            
675
    #[test]
676
1
    fn status_flip_yields_targeted_permission_changed_event() {
677
1
        let node = DomNodeId::ROOT;
678
1
        let mut mgr = PermissionManager::new();
679
1
        mgr.subscribe(Capability::Geolocation, node);
680
1
        drop(mgr.take_pending_events());
681
1
        assert!(mgr.get_pending_events(ts()).is_empty(), "no flip yet");
682

            
683
1
        assert!(mgr.set_status(Capability::Geolocation, PermissionState::Requested));
684
1
        assert!(mgr.has_pending_async(), "Requested = OS prompt in flight");
685
1
        let events = mgr.get_pending_events(ts());
686
1
        assert_eq!(events.len(), 1);
687
1
        assert_eq!(events[0].event_type, EventType::PermissionChanged);
688
1
        assert_eq!(events[0].target, node, "targeted at the subscriber node");
689

            
690
1
        mgr.clear_pending_changed();
691
1
        assert!(
692
1
            mgr.get_pending_events(ts()).is_empty(),
693
            "cleared after dispatch"
694
        );
695

            
696
1
        assert!(mgr.set_status(
697
1
            Capability::Geolocation,
698
1
            PermissionState::Granted(PermissionQuality::Full),
699
        ));
700
1
        assert!(!mgr.has_pending_async(), "prompt resolved");
701
1
        assert_eq!(mgr.get_pending_events(ts()).len(), 1);
702
1
    }
703

            
704
    #[test]
705
1
    fn unchanged_status_emits_no_event() {
706
1
        let mut mgr = PermissionManager::new();
707
1
        assert!(mgr.set_status(Capability::Geolocation, PermissionState::Denied));
708
1
        mgr.clear_pending_changed();
709
1
        assert!(!mgr.set_status(Capability::Geolocation, PermissionState::Denied));
710
1
        assert!(mgr.get_pending_events(ts()).is_empty());
711
1
    }
712
}
713

            
714
#[cfg(test)]
715
mod autotest_generated {
716
    use alloc::collections::BTreeSet;
717

            
718
    use azul_core::{
719
        dom::{DomId, NodeId},
720
        task::{Instant, SystemTick},
721
    };
722

            
723
    use super::*;
724
    use crate::managers::{NodeIdMap, NodeIdRemap};
725

            
726
    // ── fixtures ────────────────────────────────────────────────────────
727

            
728
    /// Every `Capability` variant, in declaration order. Kept honest by
729
    /// `all_capabilities_are_distinct_and_totally_ordered` below, whose
730
    /// exhaustive `match` fails to compile if a variant is ever added.
731
    const ALL_CAPS: [Capability; 19] = [
732
        Capability::Camera,
733
        Capability::Microphone,
734
        Capability::ScreenCapture,
735
        Capability::Geolocation,
736
        Capability::GeolocationBackground,
737
        Capability::Biometric,
738
        Capability::Motion,
739
        Capability::PhotoLibrary,
740
        Capability::PhotoLibraryWrite,
741
        Capability::Contacts,
742
        Capability::Calendars,
743
        Capability::Reminders,
744
        Capability::Notifications,
745
        Capability::Bluetooth,
746
        Capability::BluetoothBackground,
747
        Capability::NearbyWifi,
748
        Capability::LocalNetwork,
749
        Capability::AppTrackingTransparency,
750
        Capability::InputMonitoring,
751
    ];
752

            
753
    /// Every distinct `PermissionState` value, including both payloads of the
754
    /// two data-carrying variants.
755
    const ALL_STATES: [PermissionState; 8] = [
756
        PermissionState::NotDetermined,
757
        PermissionState::Requested,
758
        PermissionState::Granted(PermissionQuality::Full),
759
        PermissionState::Granted(PermissionQuality::Reduced),
760
        PermissionState::Denied,
761
        PermissionState::Restricted,
762
        PermissionState::EphemeralGranted(true),
763
        PermissionState::EphemeralGranted(false),
764
    ];
765

            
766
    /// `NodeId::from_usize` is 1-based: `node(0)` is the `None` sentinel (==
767
    /// `DomNodeId::ROOT`), `node(1)` is `NodeId(0)`.
768
    fn node(idx: usize) -> DomNodeId {
769
        DomNodeId {
770
            dom: DomId::ROOT_ID,
771
            node: NodeId::from_usize(idx).into(),
772
        }
773
    }
774

            
775
    fn node_in_dom(dom: usize, idx: usize) -> DomNodeId {
776
        DomNodeId {
777
            dom: DomId { inner: dom },
778
            node: NodeId::from_usize(idx).into(),
779
        }
780
    }
781

            
782
    fn ts(tick: u64) -> Instant {
783
        Instant::Tick(SystemTick::new(tick))
784
    }
785

            
786
    /// Serializes every test that touches the process-global `ASYNC_RESULTS`
787
    /// queue. libtest runs tests in parallel threads inside one process, so
788
    /// without this a concurrent `push_async_result` would corrupt another
789
    /// test's drain. Recovers from poisoning so one failing test cannot wedge
790
    /// the rest of the suite.
791
    pub(super) fn lock_async_channel() -> std::sync::MutexGuard<'static, ()> {
792
        static ASYNC_CHANNEL_TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
793
        ASYNC_CHANNEL_TEST_LOCK
794
            .lock()
795
            .unwrap_or_else(std::sync::PoisonError::into_inner)
796
    }
797

            
798
    // ── Capability: enum hygiene ────────────────────────────────────────
799

            
800
    #[test]
801
    fn all_capabilities_are_distinct_and_totally_ordered() {
802
        // Exhaustiveness guard: adding a variant to `Capability` makes this
803
        // match non-exhaustive, which is the compile error that says "add it
804
        // to ALL_CAPS too". Combined with the distinctness check below, that
805
        // means ALL_CAPS provably covers every variant.
806
        for cap in ALL_CAPS {
807
            match cap {
808
                Capability::Camera
809
                | Capability::Microphone
810
                | Capability::ScreenCapture
811
                | Capability::Geolocation
812
                | Capability::GeolocationBackground
813
                | Capability::Biometric
814
                | Capability::Motion
815
                | Capability::PhotoLibrary
816
                | Capability::PhotoLibraryWrite
817
                | Capability::Contacts
818
                | Capability::Calendars
819
                | Capability::Reminders
820
                | Capability::Notifications
821
                | Capability::Bluetooth
822
                | Capability::BluetoothBackground
823
                | Capability::NearbyWifi
824
                | Capability::LocalNetwork
825
                | Capability::AppTrackingTransparency
826
                | Capability::InputMonitoring => {}
827
            }
828
        }
829

            
830
        let set: BTreeSet<Capability> = ALL_CAPS.iter().copied().collect();
831
        assert_eq!(set.len(), ALL_CAPS.len(), "ALL_CAPS contains a duplicate");
832

            
833
        // The derived Ord follows declaration order — the BTreeMap key order
834
        // (and therefore the diff-event order) depends on it.
835
        let mut sorted = ALL_CAPS.to_vec();
836
        sorted.sort_unstable();
837
        assert_eq!(sorted, ALL_CAPS.to_vec());
838
    }
839

            
840
    #[test]
841
    fn all_states_are_distinct() {
842
        // Same guard for the state machine: a new variant fails to compile.
843
        for state in ALL_STATES {
844
            match state {
845
                PermissionState::NotDetermined
846
                | PermissionState::Requested
847
                | PermissionState::Granted(_)
848
                | PermissionState::Denied
849
                | PermissionState::Restricted
850
                | PermissionState::EphemeralGranted(_) => {}
851
            }
852
        }
853
        let set: BTreeSet<PermissionState> = ALL_STATES.iter().copied().collect();
854
        assert_eq!(
855
            set.len(),
856
            ALL_STATES.len(),
857
            "ALL_STATES contains a duplicate"
858
        );
859
    }
860

            
861
    // ── PermissionState predicates ──────────────────────────────────────
862

            
863
    #[test]
864
    fn is_granted_matches_the_documented_state_matrix() {
865
        assert!(!PermissionState::NotDetermined.is_granted());
866
        assert!(!PermissionState::Requested.is_granted());
867
        assert!(PermissionState::Granted(PermissionQuality::Full).is_granted());
868
        assert!(
869
            PermissionState::Granted(PermissionQuality::Reduced).is_granted(),
870
            "reduced quality is still usable — `is_granted` ignores quality"
871
        );
872
        assert!(!PermissionState::Denied.is_granted());
873
        assert!(!PermissionState::Restricted.is_granted());
874
        // NOTE: the bool payload of EphemeralGranted is ignored by `is_granted`
875
        // (the `matches!` uses `..`), so BOTH payloads report granted.
876
        assert!(PermissionState::EphemeralGranted(true).is_granted());
877
        assert!(PermissionState::EphemeralGranted(false).is_granted());
878
    }
879

            
880
    #[test]
881
    fn could_re_prompt_is_true_only_for_not_determined() {
882
        for state in ALL_STATES {
883
            let expected = state == PermissionState::NotDetermined;
884
            assert_eq!(
885
                state.could_re_prompt(),
886
                expected,
887
                "could_re_prompt({state:?}) should be {expected}"
888
            );
889
        }
890
        // Denied is explicitly NOT re-promptable — the OS suppresses the
891
        // second prompt, so callers must deep-link to settings instead.
892
        assert!(!PermissionState::Denied.could_re_prompt());
893
        assert!(!PermissionState::Restricted.could_re_prompt());
894
    }
895

            
896
    #[test]
897
    fn granted_and_re_promptable_are_mutually_exclusive() {
898
        for state in ALL_STATES {
899
            assert!(
900
                !(state.is_granted() && state.could_re_prompt()),
901
                "{state:?} claims to be both granted and re-promptable"
902
            );
903
        }
904
    }
905

            
906
    #[test]
907
    fn predicates_are_usable_in_const_context() {
908
        // Both are `const fn`; a regression to a non-const body would fail to
909
        // compile here rather than silently break `no_std` callers.
910
        const GRANTED: bool = PermissionState::Granted(PermissionQuality::Reduced).is_granted();
911
        const RE_PROMPT: bool = PermissionState::NotDetermined.could_re_prompt();
912
        const DENIED_GRANTED: bool = PermissionState::Denied.is_granted();
913
        const _: () = assert!(GRANTED && RE_PROMPT && !DENIED_GRANTED);
914
    }
915

            
916
    // ── constructors ────────────────────────────────────────────────────
917

            
918
    #[test]
919
    fn capability_entry_new_is_the_zero_state() {
920
        let e = CapabilityEntry::new();
921
        assert_eq!(e.state, PermissionState::NotDetermined);
922
        assert_eq!(e.refcount, 0);
923
        assert_eq!(e.last_subscriber, None);
924
        // Deterministic: two constructions are indistinguishable.
925
        assert_eq!(e, CapabilityEntry::new());
926
        // A fresh entry is re-promptable and not usable — the invariant every
927
        // caller assumes before the first prompt.
928
        assert!(!e.state.is_granted());
929
        assert!(e.state.could_re_prompt());
930
    }
931

            
932
    #[test]
933
    fn new_manager_is_empty_for_every_capability() {
934
        let mgr = PermissionManager::new();
935
        assert_eq!(mgr, PermissionManager::default());
936
        assert!(mgr.statuses.is_empty());
937
        assert!(!mgr.has_pending_async());
938
        assert!(mgr.get_pending_events(ts(0)).is_empty());
939

            
940
        for cap in ALL_CAPS {
941
            assert_eq!(mgr.get_status(cap), PermissionState::NotDetermined);
942
            assert_eq!(mgr.refcount(cap), 0);
943
        }
944
        // Reading must not lazily create entries — an entry with refcount 0
945
        // would make `diff_layout` iterate capabilities nobody ever used.
946
        assert!(
947
            mgr.statuses.is_empty(),
948
            "get_status/refcount created entries"
949
        );
950
    }
951

            
952
    #[test]
953
    fn take_pending_events_on_a_fresh_manager_is_empty_and_idempotent() {
954
        let mut mgr = PermissionManager::new();
955
        assert!(mgr.take_pending_events().is_empty());
956
        assert!(mgr.take_pending_events().is_empty());
957
        mgr.clear_pending_changed();
958
        mgr.clear_pending_changed();
959
        assert_eq!(mgr, PermissionManager::new());
960
    }
961

            
962
    // ── refcount arithmetic: underflow / overflow / saturation ──────────
963

            
964
    #[test]
965
    fn release_on_unknown_capability_is_a_noop() {
966
        let mut mgr = PermissionManager::new();
967
        for cap in ALL_CAPS {
968
            mgr.release(cap);
969
            mgr.force_release(cap);
970
        }
971
        assert!(mgr.statuses.is_empty(), "release must not create entries");
972
        assert!(mgr.take_pending_events().is_empty());
973
        assert!(mgr.get_pending_events(ts(0)).is_empty());
974
    }
975

            
976
    #[test]
977
    fn release_at_zero_refcount_does_not_underflow() {
978
        let mut mgr = PermissionManager::new();
979
        // set_status creates the entry with refcount 0 — the exact shape that
980
        // would panic on `refcount -= 1` in debug builds if unguarded.
981
        mgr.set_status(Capability::Camera, PermissionState::Denied);
982
        assert_eq!(mgr.refcount(Capability::Camera), 0);
983

            
984
        for _ in 0..8 {
985
            mgr.release(Capability::Camera);
986
        }
987
        assert_eq!(
988
            mgr.refcount(Capability::Camera),
989
            0,
990
            "refcount wrapped around"
991
        );
992
        assert!(
993
            mgr.take_pending_events().is_empty(),
994
            "a release that never had a subscriber must not emit Release"
995
        );
996
    }
997

            
998
    #[test]
999
    fn double_release_emits_exactly_one_release_event() {
        let mut mgr = PermissionManager::new();
        mgr.subscribe(Capability::Motion, node(1));
        drop(mgr.take_pending_events());
        mgr.release(Capability::Motion);
        mgr.release(Capability::Motion);
        mgr.release(Capability::Motion);
        assert_eq!(mgr.refcount(Capability::Motion), 0);
        let events = mgr.take_pending_events();
        assert_eq!(
            events.len(),
            1,
            "over-releasing must not double-tear-down the native session: {events:?}"
        );
    }
    #[test]
    fn subscribe_saturates_at_u32_max_instead_of_overflowing() {
        let mut mgr = PermissionManager::new();
        mgr.subscribe(Capability::Bluetooth, node(1));
        drop(mgr.take_pending_events());
        // Reach the boundary directly — 4 billion subscribe() calls is not a
        // test. `statuses` is a pub field, so this is a supported shortcut.
        mgr.statuses
            .get_mut(&Capability::Bluetooth)
            .unwrap()
            .refcount = u32::MAX;
        mgr.subscribe(Capability::Bluetooth, node(2));
        assert_eq!(
            mgr.refcount(Capability::Bluetooth),
            u32::MAX,
            "refcount wrapped to 0"
        );
        assert!(
            mgr.take_pending_events().is_empty(),
            "a saturating subscribe must not look like a 0 -> 1 transition"
        );
        // The subscriber is still tracked even when the count saturates.
        assert_eq!(
            mgr.statuses[&Capability::Bluetooth].last_subscriber,
            Some(node(2))
        );
    }
    #[test]
    fn release_from_u32_max_does_not_wrap_or_emit() {
        let mut mgr = PermissionManager::new();
        mgr.subscribe(Capability::Contacts, node(1));
        drop(mgr.take_pending_events());
        mgr.statuses
            .get_mut(&Capability::Contacts)
            .unwrap()
            .refcount = u32::MAX;
        mgr.release(Capability::Contacts);
        assert_eq!(mgr.refcount(Capability::Contacts), u32::MAX - 1);
        assert!(mgr.take_pending_events().is_empty());
    }
    #[test]
    fn force_release_from_saturated_refcount_emits_one_release() {
        let mut mgr = PermissionManager::new();
        mgr.subscribe(Capability::ScreenCapture, node(1));
        drop(mgr.take_pending_events());
        mgr.statuses
            .get_mut(&Capability::ScreenCapture)
            .unwrap()
            .refcount = u32::MAX;
        mgr.force_release(Capability::ScreenCapture);
        assert_eq!(mgr.refcount(Capability::ScreenCapture), 0);
        assert_eq!(
            mgr.statuses[&Capability::ScreenCapture].last_subscriber,
            None
        );
        assert_eq!(mgr.take_pending_events().len(), 1);
        // Second force_release: refcount is already 0, nothing to tear down.
        mgr.force_release(Capability::ScreenCapture);
        assert!(
            mgr.take_pending_events().is_empty(),
            "force_release on a zero refcount must be a no-op"
        );
    }
    #[test]
    fn subscribe_after_a_full_release_re_emits_subscribe() {
        let mut mgr = PermissionManager::new();
        mgr.subscribe(Capability::Camera, node(1));
        mgr.release(Capability::Camera);
        drop(mgr.take_pending_events());
        // The platform tore the session down on Release, so the reappearing
        // node must produce a fresh Subscribe (0 -> 1 again).
        mgr.subscribe(Capability::Camera, node(2));
        let events = mgr.take_pending_events();
        assert_eq!(
            events,
            [PermissionDiffEvent::Subscribe {
                capability: Capability::Camera,
                node_id: node(2),
            }]
            .to_vec()
        );
    }
    #[test]
    fn release_cycle_preserves_the_os_observed_state() {
        let mut mgr = PermissionManager::new();
        mgr.subscribe(Capability::Geolocation, node(1));
        mgr.set_status(
            Capability::Geolocation,
            PermissionState::Granted(PermissionQuality::Reduced),
        );
        mgr.release(Capability::Geolocation);
        // Refcount is gone but the grant is NOT forgotten — otherwise every
        // layout pass that drops the node would re-prompt the user.
        assert_eq!(mgr.refcount(Capability::Geolocation), 0);
        assert_eq!(
            mgr.get_status(Capability::Geolocation),
            PermissionState::Granted(PermissionQuality::Reduced)
        );
        assert_eq!(mgr.statuses[&Capability::Geolocation].last_subscriber, None);
    }
    #[test]
    fn subscribe_accepts_boundary_node_ids() {
        let mut mgr = PermissionManager::new();
        // The `None` sentinel (== DomNodeId::ROOT) and the largest encodable
        // NodeId must both round-trip through the event queue untouched.
        mgr.subscribe(Capability::Notifications, DomNodeId::ROOT);
        mgr.subscribe(Capability::Biometric, node(usize::MAX));
        let events = mgr.take_pending_events();
        assert_eq!(events.len(), 2);
        assert!(events.contains(&PermissionDiffEvent::Subscribe {
            capability: Capability::Notifications,
            node_id: DomNodeId::ROOT,
        }));
        assert!(events.contains(&PermissionDiffEvent::Subscribe {
            capability: Capability::Biometric,
            node_id: node(usize::MAX),
        }));
    }
    // ── set_status / pending_changed ────────────────────────────────────
    #[test]
    fn set_status_get_status_round_trips_over_the_whole_matrix() {
        for cap in ALL_CAPS {
            for state in ALL_STATES {
                let mut mgr = PermissionManager::new();
                mgr.set_status(cap, state);
                assert_eq!(
                    mgr.get_status(cap),
                    state,
                    "{cap:?} / {state:?} did not round-trip"
                );
                // Writing one capability must not leak into any other.
                for other in ALL_CAPS.iter().copied().filter(|c| *c != cap) {
                    assert_eq!(mgr.get_status(other), PermissionState::NotDetermined);
                }
            }
        }
    }
    #[test]
    fn set_status_change_flag_is_exact_over_every_transition() {
        for a in ALL_STATES {
            for b in ALL_STATES {
                let mut mgr = PermissionManager::new();
                let cap = Capability::Calendars;
                // The entry starts at NotDetermined, so writing NotDetermined
                // first is a no-change write.
                let changed_a = mgr.set_status(cap, a);
                assert_eq!(changed_a, a != PermissionState::NotDetermined, "{a:?}");
                let changed_b = mgr.set_status(cap, b);
                assert_eq!(changed_b, b != a, "{a:?} -> {b:?} reported the wrong flag");
                assert_eq!(mgr.get_status(cap), b);
                assert_eq!(mgr.has_pending_async(), b == PermissionState::Requested);
                // One PermissionChanged event per *actual* flip, no more.
                let expected = usize::from(changed_a) + usize::from(changed_b);
                assert_eq!(
                    mgr.get_pending_events(ts(0)).len(),
                    expected,
                    "{a:?} -> {b:?}"
                );
            }
        }
    }
    #[test]
    fn set_status_creates_an_entry_with_a_zero_refcount() {
        let mut mgr = PermissionManager::new();
        assert!(mgr.set_status(Capability::Reminders, PermissionState::Restricted));
        let entry = mgr.statuses[&Capability::Reminders];
        assert_eq!(entry.refcount, 0, "a status write is not a subscription");
        assert_eq!(entry.last_subscriber, None);
        assert!(
            mgr.take_pending_events().is_empty(),
            "set_status is not a diff event"
        );
    }
    #[test]
    fn quality_and_payload_changes_count_as_state_changes() {
        let mut mgr = PermissionManager::new();
        let cap = Capability::PhotoLibrary;
        assert!(mgr.set_status(cap, PermissionState::Granted(PermissionQuality::Full)));
        // Full -> Reduced ("Selected Photos") is a real change the UI must see.
        assert!(mgr.set_status(cap, PermissionState::Granted(PermissionQuality::Reduced)));
        assert!(!mgr.set_status(cap, PermissionState::Granted(PermissionQuality::Reduced)));
        // Both EphemeralGranted payloads are distinct states.
        assert!(mgr.set_status(cap, PermissionState::EphemeralGranted(true)));
        assert!(mgr.set_status(cap, PermissionState::EphemeralGranted(false)));
        assert!(!mgr.set_status(cap, PermissionState::EphemeralGranted(false)));
        assert!(mgr.get_status(cap).is_granted());
    }
    #[test]
    fn has_pending_async_tracks_only_the_requested_state() {
        for state in ALL_STATES {
            let mut mgr = PermissionManager::new();
            mgr.set_status(Capability::Camera, state);
            assert_eq!(
                mgr.has_pending_async(),
                state == PermissionState::Requested,
                "has_pending_async({state:?})"
            );
        }
        // One in-flight prompt among many resolved capabilities still arms the
        // pump — otherwise the outcome never reaches callbacks in an idle app.
        let mut mgr = PermissionManager::new();
        for cap in ALL_CAPS {
            mgr.set_status(cap, PermissionState::Granted(PermissionQuality::Full));
        }
        assert!(!mgr.has_pending_async());
        mgr.set_status(
            Capability::AppTrackingTransparency,
            PermissionState::Requested,
        );
        assert!(mgr.has_pending_async());
        mgr.set_status(Capability::AppTrackingTransparency, PermissionState::Denied);
        assert!(!mgr.has_pending_async());
    }
    #[test]
    fn pending_changed_targets_the_root_when_there_is_no_subscriber() {
        let mut mgr = PermissionManager::new();
        // A status flip with no bearing node (OS revoked it while nothing was
        // mounted) must still dispatch — targeted at the window root.
        mgr.set_status(Capability::Microphone, PermissionState::Denied);
        let events = mgr.get_pending_events(ts(42));
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].event_type, EventType::PermissionChanged);
        assert_eq!(events[0].source, CoreEventSource::User);
        assert_eq!(events[0].target, DomNodeId::ROOT);
        assert_eq!(
            events[0].timestamp,
            ts(42),
            "the caller's timestamp is preserved"
        );
    }
    #[test]
    fn pending_changed_falls_back_to_root_after_the_subscriber_leaves() {
        let mut mgr = PermissionManager::new();
        mgr.subscribe(Capability::Microphone, node(4));
        mgr.set_status(Capability::Microphone, PermissionState::Requested);
        assert_eq!(mgr.get_pending_events(ts(0))[0].target, node(4));
        mgr.clear_pending_changed();
        // The node unmounts, then the OS answer lands: last_subscriber is
        // cleared, so the event must NOT point at a stale node index.
        mgr.release(Capability::Microphone);
        mgr.set_status(Capability::Microphone, PermissionState::Denied);
        let events = mgr.get_pending_events(ts(0));
        assert_eq!(events.len(), 1);
        assert_eq!(events[0].target, DomNodeId::ROOT);
    }
    #[test]
    fn repeated_flips_accumulate_one_event_each_until_cleared() {
        let mut mgr = PermissionManager::new();
        let cap = Capability::LocalNetwork;
        mgr.set_status(cap, PermissionState::Requested);
        mgr.set_status(cap, PermissionState::Granted(PermissionQuality::Full));
        mgr.set_status(cap, PermissionState::Denied);
        assert_eq!(mgr.get_pending_events(ts(0)).len(), 3);
        // get_pending_events is a read, not a drain.
        assert_eq!(mgr.get_pending_events(ts(0)).len(), 3);
        mgr.clear_pending_changed();
        assert!(mgr.get_pending_events(ts(0)).is_empty());
        mgr.clear_pending_changed();
        assert!(
            mgr.get_pending_events(ts(0)).is_empty(),
            "clear is idempotent"
        );
    }
    #[test]
    fn the_two_queues_drain_independently() {
        let mut mgr = PermissionManager::new();
        mgr.subscribe(Capability::NearbyWifi, node(1)); // -> pending_events
        mgr.set_status(Capability::NearbyWifi, PermissionState::Requested); // -> pending_changed
        // Clearing the state-flip queue must not swallow the diff events the
        // platform backend has not drained yet.
        mgr.clear_pending_changed();
        assert!(mgr.get_pending_events(ts(0)).is_empty());
        assert_eq!(mgr.take_pending_events().len(), 1);
        // ... and vice versa.
        mgr.set_status(Capability::NearbyWifi, PermissionState::Denied);
        mgr.subscribe(Capability::Contacts, node(2));
        assert_eq!(mgr.take_pending_events().len(), 1);
        assert!(mgr.take_pending_events().is_empty(), "take drains");
        assert_eq!(
            mgr.get_pending_events(ts(0)).len(),
            1,
            "take_pending_events must not clear pending_changed"
        );
    }
    // ── diff_layout ─────────────────────────────────────────────────────
    #[test]
    fn diff_layout_on_an_empty_manager_with_no_nodes_is_a_noop() {
        let mut mgr = PermissionManager::new();
        mgr.diff_layout(|_emit| {});
        assert!(mgr.statuses.is_empty());
        assert!(mgr.take_pending_events().is_empty());
        assert!(mgr.get_pending_events(ts(0)).is_empty());
    }
    #[test]
    fn diff_layout_counts_duplicates_and_anchors_the_first_node() {
        let mut mgr = PermissionManager::new();
        mgr.diff_layout(|emit| {
            emit(Capability::Camera, node(3));
            emit(Capability::Camera, node(4));
            emit(Capability::Camera, node(5));
        });
        assert_eq!(mgr.refcount(Capability::Camera), 3);
        assert_eq!(
            mgr.statuses[&Capability::Camera].last_subscriber,
            Some(node(3)),
            "the FIRST emitted node anchors the capability"
        );
        assert_eq!(
            mgr.take_pending_events(),
            [PermissionDiffEvent::Subscribe {
                capability: Capability::Camera,
                node_id: node(3),
            }]
            .to_vec(),
            "three bearing nodes still mean exactly one native subscribe"
        );
    }
    #[test]
    fn diff_layout_is_idempotent_for_a_stable_layout() {
        let mut mgr = PermissionManager::new();
        for _ in 0..5 {
            mgr.diff_layout(|emit| {
                emit(Capability::Camera, node(1));
                emit(Capability::Microphone, node(2));
            });
        }
        assert_eq!(mgr.refcount(Capability::Camera), 1);
        assert_eq!(mgr.refcount(Capability::Microphone), 1);
        assert_eq!(
            mgr.take_pending_events().len(),
            2,
            "an unchanged layout must not re-emit subscribes every frame"
        );
    }
    #[test]
    fn diff_layout_emits_release_and_subscribe_in_the_same_frame() {
        let mut mgr = PermissionManager::new();
        mgr.diff_layout(|emit| emit(Capability::Camera, node(1)));
        drop(mgr.take_pending_events());
        // The camera node is swapped for a geolocation node in one pass.
        mgr.diff_layout(|emit| emit(Capability::Geolocation, node(2)));
        let events = mgr.take_pending_events();
        assert_eq!(events.len(), 2, "{events:?}");
        assert!(events.contains(&PermissionDiffEvent::Release {
            capability: Capability::Camera
        }));
        assert!(events.contains(&PermissionDiffEvent::Subscribe {
            capability: Capability::Geolocation,
            node_id: node(2),
        }));
        assert_eq!(mgr.refcount(Capability::Camera), 0);
        assert_eq!(mgr.refcount(Capability::Geolocation), 1);
    }
    #[test]
    fn diff_layout_reconciles_a_manually_subscribed_capability() {
        let mut mgr = PermissionManager::new();
        mgr.subscribe(Capability::Camera, node(1));
        mgr.subscribe(Capability::Camera, node(2));
        drop(mgr.take_pending_events());
        // The layout pass is authoritative: no bearing nodes this frame means
        // the refcount goes to 0 outright, not 2 -> 1.
        mgr.diff_layout(|_emit| {});
        assert_eq!(mgr.refcount(Capability::Camera), 0);
        assert_eq!(mgr.statuses[&Capability::Camera].last_subscriber, None);
        assert_eq!(
            mgr.take_pending_events(),
            [PermissionDiffEvent::Release {
                capability: Capability::Camera
            }]
            .to_vec()
        );
    }
    #[test]
    fn diff_layout_ignores_capabilities_that_only_have_a_status() {
        let mut mgr = PermissionManager::new();
        // set_status leaves a refcount-0 entry behind; diff_layout iterates
        // every known capability, so it must not emit a spurious Release.
        for cap in ALL_CAPS {
            mgr.set_status(cap, PermissionState::Denied);
        }
        mgr.diff_layout(|_emit| {});
        assert!(
            mgr.take_pending_events().is_empty(),
            "0 -> 0 is not a transition"
        );
        for cap in ALL_CAPS {
            assert_eq!(mgr.refcount(cap), 0);
            assert_eq!(mgr.get_status(cap), PermissionState::Denied);
        }
    }
    #[test]
    fn diff_layout_from_a_saturated_refcount_does_not_emit() {
        let mut mgr = PermissionManager::new();
        mgr.subscribe(Capability::Motion, node(1));
        drop(mgr.take_pending_events());
        mgr.statuses.get_mut(&Capability::Motion).unwrap().refcount = u32::MAX;
        // MAX -> 1 is neither a 0 -> 1 nor an n -> 0 transition: the session
        // stays up and nothing is emitted.
        mgr.diff_layout(|emit| emit(Capability::Motion, node(1)));
        assert_eq!(mgr.refcount(Capability::Motion), 1);
        assert!(mgr.take_pending_events().is_empty());
    }
    #[test]
    fn diff_layout_handles_every_capability_at_once() {
        let mut mgr = PermissionManager::new();
        mgr.diff_layout(|emit| {
            for (i, cap) in ALL_CAPS.iter().enumerate() {
                emit(*cap, node(i + 1));
            }
        });
        let events = mgr.take_pending_events();
        assert_eq!(events.len(), ALL_CAPS.len(), "one Subscribe per capability");
        for (i, cap) in ALL_CAPS.iter().enumerate() {
            assert_eq!(mgr.refcount(*cap), 1);
            assert!(
                events.contains(&PermissionDiffEvent::Subscribe {
                    capability: *cap,
                    node_id: node(i + 1),
                }),
                "missing Subscribe for {cap:?}"
            );
        }
        // ... and tears them all down again.
        mgr.diff_layout(|_emit| {});
        assert_eq!(mgr.take_pending_events().len(), ALL_CAPS.len());
    }
    #[test]
    fn diff_layout_event_order_is_deterministic() {
        let run = || {
            let mut mgr = PermissionManager::new();
            mgr.diff_layout(|emit| {
                emit(Capability::Notifications, node(1));
                emit(Capability::Camera, node(2));
                emit(Capability::Geolocation, node(3));
            });
            let first = mgr.take_pending_events();
            mgr.diff_layout(|emit| emit(Capability::Camera, node(2)));
            let second = mgr.take_pending_events();
            (first, second)
        };
        assert_eq!(
            run(),
            run(),
            "the diff-event order must not depend on run order"
        );
    }
    #[test]
    fn diff_layout_accepts_the_root_sentinel_as_a_bearing_node() {
        let mut mgr = PermissionManager::new();
        // A bearing node whose NodeHierarchyItemId is NONE encodes to exactly
        // the same value as the `unwrap_or(ROOT)` fallback — assert we still
        // subscribe rather than panicking or skipping it.
        mgr.diff_layout(|emit| emit(Capability::Biometric, DomNodeId::ROOT));
        assert_eq!(mgr.refcount(Capability::Biometric), 1);
        assert_eq!(
            mgr.take_pending_events(),
            [PermissionDiffEvent::Subscribe {
                capability: Capability::Biometric,
                node_id: DomNodeId::ROOT,
            }]
            .to_vec()
        );
    }
    #[test]
    fn diff_layout_handles_a_large_bearing_node_set() {
        let mut mgr = PermissionManager::new();
        const N: usize = 10_000;
        mgr.diff_layout(|emit| {
            for i in 1..=N {
                emit(Capability::PhotoLibraryWrite, node(i));
            }
        });
        assert_eq!(mgr.refcount(Capability::PhotoLibraryWrite), N as u32);
        assert_eq!(mgr.take_pending_events().len(), 1);
        mgr.diff_layout(|_emit| {});
        assert_eq!(mgr.refcount(Capability::PhotoLibraryWrite), 0);
        assert_eq!(mgr.take_pending_events().len(), 1);
    }
    #[test]
    fn diff_layout_does_not_disturb_the_state_machine() {
        let mut mgr = PermissionManager::new();
        mgr.set_status(
            Capability::Geolocation,
            PermissionState::EphemeralGranted(true),
        );
        mgr.clear_pending_changed();
        mgr.diff_layout(|emit| emit(Capability::Geolocation, node(1)));
        mgr.diff_layout(|_emit| {});
        // Subscribe/Release churn must never mutate the OS-observed state or
        // synthesize a PermissionChanged event out of thin air.
        assert_eq!(
            mgr.get_status(Capability::Geolocation),
            PermissionState::EphemeralGranted(true)
        );
        assert!(mgr.get_pending_events(ts(0)).is_empty());
    }
    // ── clone / equality ────────────────────────────────────────────────
    #[test]
    fn cloning_a_manager_deep_copies_its_queues() {
        let mut mgr = PermissionManager::new();
        mgr.subscribe(Capability::Camera, node(1));
        mgr.set_status(Capability::Camera, PermissionState::Requested);
        let mut clone = mgr.clone();
        assert_eq!(clone, mgr);
        clone.subscribe(Capability::Camera, node(2));
        clone.force_release(Capability::Microphone);
        drop(clone.take_pending_events());
        clone.clear_pending_changed();
        assert_ne!(clone, mgr, "the clone shares state with the original");
        assert_eq!(mgr.refcount(Capability::Camera), 1);
        assert_eq!(
            mgr.take_pending_events().len(),
            1,
            "original's queue was drained"
        );
        assert_eq!(mgr.get_pending_events(ts(0)).len(), 1);
    }
    // ── NodeIdRemap ─────────────────────────────────────────────────────
    #[test]
    fn remap_rewrites_the_subscriber_and_the_queued_target() {
        let mut mgr = PermissionManager::new();
        mgr.subscribe(Capability::Camera, node(3)); // node(3) == NodeId(2)
        mgr.set_status(Capability::Camera, PermissionState::Requested);
        // The DOM was rebuilt and the bearing node moved 2 -> 9.
        let map = NodeIdMap::from_pairs([(NodeId::new(2), NodeId::new(9))]);
        mgr.remap_node_ids(DomId::ROOT_ID, &map);
        assert_eq!(
            mgr.statuses[&Capability::Camera].last_subscriber,
            Some(node(10)), // node(10) == NodeId(9)
        );
        assert_eq!(mgr.get_pending_events(ts(0))[0].target, node(10));
    }
    #[test]
    fn remap_drops_an_unmounted_subscriber_instead_of_recycling_the_index() {
        let mut mgr = PermissionManager::new();
        mgr.subscribe(Capability::Camera, node(3));
        mgr.set_status(Capability::Camera, PermissionState::Requested);
        // Empty map == everything was unmounted.
        mgr.remap_node_ids(DomId::ROOT_ID, &NodeIdMap::default());
        assert_eq!(
            mgr.statuses[&Capability::Camera].last_subscriber,
            None,
            "an unmounted subscriber must fall back to None, never to a live-but-wrong node"
        );
        assert_eq!(
            mgr.get_pending_events(ts(0))[0].target,
            DomNodeId::ROOT,
            "the queued event retargets to the window root"
        );
        // The permission state itself survives the DOM rebuild.
        assert_eq!(
            mgr.get_status(Capability::Camera),
            PermissionState::Requested
        );
    }
    #[test]
    fn remap_leaves_nodes_from_other_doms_untouched() {
        let mut mgr = PermissionManager::new();
        let foreign = node_in_dom(7, 3);
        mgr.subscribe(Capability::Camera, foreign);
        mgr.set_status(Capability::Camera, PermissionState::Requested);
        // A reconciliation of DOM 0 says nothing about DOM 7 — dropping the
        // subscriber here would silently retarget an iframe's prompt at the
        // root window.
        mgr.remap_node_ids(DomId::ROOT_ID, &NodeIdMap::default());
        assert_eq!(
            mgr.statuses[&Capability::Camera].last_subscriber,
            Some(foreign)
        );
        assert_eq!(mgr.get_pending_events(ts(0))[0].target, foreign);
    }
    // ── async channel (process-global) ──────────────────────────────────
    #[test]
    fn async_channel_preserves_arrival_order_across_all_states() {
        let _serialize = lock_async_channel();
        drop(drain_async_results());
        for state in ALL_STATES {
            push_async_result(Capability::Camera, state);
        }
        let drained = drain_async_results();
        assert_eq!(drained.len(), ALL_STATES.len());
        for (i, state) in ALL_STATES.iter().enumerate() {
            assert_eq!(drained[i], (Capability::Camera, *state));
        }
        assert!(
            drain_async_results().is_empty(),
            "the queue is taken, not copied"
        );
    }
    #[test]
    fn async_channel_recovers_from_a_poisoned_lock() {
        let _serialize = lock_async_channel();
        drop(drain_async_results());
        // Poison the global mutex the way a panicking applier would: unwind
        // out of a live guard. (The panic message below is expected output if
        // this test ever fails; libtest swallows it while it passes.)
        let unwound = std::panic::catch_unwind(|| {
            let _guard = ASYNC_RESULTS.lock().unwrap();
            panic!("intentional: poisoning ASYNC_RESULTS");
        });
        assert!(
            unwound.is_err(),
            "the panic must have unwound through the guard"
        );
        assert!(
            ASYNC_RESULTS.is_poisoned(),
            "the lock should now be poisoned"
        );
        // Documented contract: delivery keeps working after a poisoning.
        push_async_result(Capability::Geolocation, PermissionState::Denied);
        let drained = drain_async_results();
        assert_eq!(
            drained,
            [(Capability::Geolocation, PermissionState::Denied)].to_vec(),
            "a poisoned lock must not wedge permission delivery forever"
        );
        assert!(drain_async_results().is_empty());
    }
    #[test]
    fn async_channel_survives_concurrent_pushers() {
        let _serialize = lock_async_channel();
        drop(drain_async_results());
        const THREADS: usize = 8;
        const PER_THREAD: usize = 50;
        let handles: Vec<_> = (0..THREADS)
            .map(|t| {
                let cap = ALL_CAPS[t];
                std::thread::spawn(move || {
                    for _ in 0..PER_THREAD {
                        push_async_result(cap, PermissionState::Granted(PermissionQuality::Full));
                    }
                })
            })
            .collect();
        for h in handles {
            h.join().expect("a pusher thread panicked");
        }
        let drained = drain_async_results();
        assert_eq!(drained.len(), THREADS * PER_THREAD, "results were lost");
        for cap in ALL_CAPS.iter().take(THREADS) {
            let count = drained.iter().filter(|(c, _)| c == cap).count();
            assert_eq!(count, PER_THREAD, "{cap:?} lost results");
        }
        assert!(drain_async_results().is_empty());
    }
    #[test]
    fn draining_an_empty_async_channel_is_safe_and_repeatable() {
        let _serialize = lock_async_channel();
        for _ in 0..3 {
            assert!(drain_async_results().is_empty());
        }
    }
}
impl crate::managers::NodeIdRemap for PermissionManager {
    /// Remap the `last_subscriber` node of each capability (the node a
    /// `PermissionChanged` event is targeted at) and the queued
    /// `pending_changed` targets. An unmounted subscriber falls back to `None`
    /// (→ the event targets the window root), never to a recycled index.
449
    fn remap_node_ids(&mut self, dom: azul_core::dom::DomId, map: &crate::managers::NodeIdMap) {
449
        for entry in self.statuses.values_mut() {
3
            if let Some(node) = entry.last_subscriber {
3
                entry.last_subscriber = map.resolve_dom_node_id(dom, node);
3
            }
        }
452
        for (_capability, node) in &mut self.pending_changed {
3
            if let Some(n) = *node {
3
                *node = map.resolve_dom_node_id(dom, n);
3
            }
        }
449
    }
}