day_part_permissions/lib.rs
1// Copyright © The Daybrite Project
2// SPDX-License-Identifier: MPL-2.0
3
4//! day-part-permissions: a headless portable API for the OS permission system. No UI; any Rust
5//! code can depend on this crate to ask what the OS will do, and to ask the OS itself.
6//!
7//! ```no_run
8//! use day_part_permissions::{Permission, Status, request, status};
9//! if status(Permission::Camera) != Status::Granted {
10//! request(Permission::Camera, |s| println!("camera: {s}"));
11//! }
12//! ```
13//!
14//! Platform selection is purely `#[cfg(target_os)]`/`#[cfg(target_env)]` (consent is an OS concern,
15//! not a widget-toolkit one): Apple platforms use the per-framework authorization APIs
16//! (`CLLocationManager`, `AVCaptureDevice`, `PHPhotoLibrary`, `UNUserNotificationCenter`,
17//! `CMMotionActivityManager`), Android `Context.checkSelfPermission` plus `requestPermissions` from
18//! a headless `Fragment`, HarmonyOS `OH_AT_CheckSelfPermission`, and the web
19//! `navigator.permissions` with the per-API request calls. Desktop Linux and Windows have no
20//! consent database, so every gated capability there answers [`Gate::Ungated`] / [`Status::Granted`].
21//!
22//! # Two questions, two vocabularies
23//!
24//! [`gate`] answers *"does this target gate the capability at all?"* and [`status`] answers *"what
25//! will the OS do if I use it now?"*. Keeping them apart is what lets desktop Linux answer
26//! [`Status::Granted`] for the camera (nothing stands in your way, so proceed, and let the real
27//! failure surface at `open("/dev/video0")`) without losing the structural fact that Linux has no
28//! permission system ([`Gate::Ungated`]).
29//!
30//! # Declare before you ask
31//!
32//! Every mobile OS also requires a BUILD-TIME declaration, and Day generates those from the
33//! `[permissions]` table in `Day.toml` (docs/permissions.md). This matters more than it sounds:
34//! an undeclared permission reports [`Status::Restricted`] on Android, and on iOS/macOS touching a
35//! gated API without its `NS…UsageDescription` key **terminates the process**.
36//!
37//! # Reasons are not a runtime parameter
38//!
39//! No platform accepts one. iOS and macOS read `NS…UsageDescription` from `Info.plist`;
40//! `requestPermissions(String[], int)` and `requestPermissionsFromUser(context, string[])` take no
41//! text, and neither does `getUserMedia` or `Notification.requestPermission`. So the reason lives in
42//! the declaration, where it reaches the OS, and this crate hands you [`should_show_rationale`] and
43//! [`can_prompt`] so your app can draw its own explanation first, in its own localized copy.
44//!
45//! # Threading and cancellation
46//!
47//! [`request`]'s completion runs on an unspecified thread, possibly the UI thread (Android's
48//! `onRequestPermissionsResult`, the browser's only thread), so deliver results with a
49//! `day_reactive::Setter`, the way `day-part-http` does. There is no blocking `request`: the OS
50//! prompt is drawn by the very thread a blocking call would park, so it would deadlock by
51//! construction. And dropping a [`StatusFuture`] does not take the prompt off the screen; no
52//! platform can do that. See [`StatusFuture`].
53
54use std::collections::HashMap;
55use std::future::Future;
56use std::sync::{Arc, Mutex, MutexGuard};
57
58/// A permission to query or request.
59///
60/// The seven portable variants exist on iOS, Android and HarmonyOS; the per-platform tables in
61/// docs/permissions.md say what each means everywhere else. For anything outside this set, use the
62/// `Permission`-typed constants in the [`android`], [`ohos`], [`apple`] and [`web`] modules; each
63/// is `#[cfg]`-gated to its platform, so a non-portable name is a compile error off it.
64#[non_exhaustive]
65#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
66pub enum Permission {
67 /// The device's location while the app is in the foreground. Apple
68 /// `requestWhenInUseAuthorization` (`NSLocationWhenInUseUsageDescription`); Android
69 /// `ACCESS_FINE_LOCATION` + `ACCESS_COARSE_LOCATION` requested together, which is what produces
70 /// the precise/approximate dialog; HarmonyOS `APPROXIMATELY_LOCATION` + `LOCATION` (the platform
71 /// rejects `LOCATION` alone); the web's `navigator.geolocation`.
72 Location,
73 /// Location while the app is backgrounded. Never request it first: every platform requires
74 /// foreground location to be granted already, and on Android 11+ it cannot be granted from an
75 /// in-app dialog at all, so [`can_prompt`] is `false` there and [`open_settings`] is the only
76 /// path. Apple `requestAlwaysAuthorization`; Android `ACCESS_BACKGROUND_LOCATION`; HarmonyOS
77 /// `LOCATION_IN_BACKGROUND`. The web has no such concept ([`Gate::Absent`]).
78 LocationAlways,
79 /// The camera. Apple `AVCaptureDevice` with `AVMediaTypeVideo`; Android `CAMERA`; HarmonyOS
80 /// `ohos.permission.CAMERA`; the web's `getUserMedia({video:true})`.
81 Camera,
82 /// The microphone. Apple `AVCaptureDevice` with `AVMediaTypeAudio`; Android `RECORD_AUDIO`;
83 /// HarmonyOS `ohos.permission.MICROPHONE`; the web's `getUserMedia({audio:true})`.
84 Microphone,
85 /// Posting user-visible notifications. Apple `UNUserNotificationCenter` (which needs no
86 /// `Info.plist` key); Android `POST_NOTIFICATIONS` on API 33+, and `areNotificationsEnabled()`
87 /// below it; the web's `Notification.requestPermission()`.
88 Notifications,
89 /// The photo library. Apple `PHPhotoLibrary` (its `Limited` tier reports [`Status::Granted`]:
90 /// the user chose *some* photos, which is access); Android `READ_MEDIA_IMAGES` +
91 /// `READ_MEDIA_VIDEO` on API 33+, else `READ_EXTERNAL_STORAGE`. HarmonyOS reaches photos
92 /// through a picker that needs no permission ([`Gate::Ungated`]), and the web has no library
93 /// concept at all ([`Gate::Absent`]); use a file picker.
94 Photos,
95 /// Motion and fitness activity. This is not raw accelerometer/gyroscope access, which needs no
96 /// permission on iOS or Android (docs/sensors.md); it gates step counts and activity
97 /// classification. iOS `CMMotionActivityManager` (`NSMotionUsageDescription`); Android
98 /// `ACTIVITY_RECOGNITION` on API 29+; HarmonyOS `ACTIVITY_MOTION`. On the web this is the one
99 /// that gates raw motion: iOS Safari's `DeviceMotionEvent.requestPermission()`. macOS has no
100 /// CoreMotion ([`Gate::Absent`]).
101 Motion,
102 /// A permission named the way its platform names it: the escape hatch for anything the
103 /// portable set doesn't cover. The string is the native id on Android
104 /// (`"android.permission.BLUETOOTH_CONNECT"`) and HarmonyOS, a Permissions-API name on the web
105 /// (`"clipboard-read"`), and a crate-defined `"apple.*"` id on Apple platforms, which have no
106 /// permission strings of their own. Prefer the typed constants in [`android`], [`ohos`],
107 /// [`apple`] and [`web`] over writing these literals.
108 Raw(&'static str),
109}
110
111impl Permission {
112 /// A stable ASCII id: `"location"`, `"camera"`, … or the raw string. Locale-independent, so it
113 /// is safe to assert on in dayscript and to write to logs.
114 #[must_use]
115 pub fn as_str(self) -> &'static str {
116 match self {
117 Permission::Location => "location",
118 Permission::LocationAlways => "location-always",
119 Permission::Camera => "camera",
120 Permission::Microphone => "microphone",
121 Permission::Notifications => "notifications",
122 Permission::Photos => "photos",
123 Permission::Motion => "motion",
124 Permission::Raw(s) => s,
125 }
126 }
127}
128
129impl std::fmt::Display for Permission {
130 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
131 f.write_str(self.as_str())
132 }
133}
134
135/// Whether the compiled target gates a capability at all: the structural question, asked
136/// separately from [`status`] so that "no gate here" never has to masquerade as a denial.
137#[derive(Clone, Copy, Debug, PartialEq, Eq)]
138pub enum Gate {
139 /// The OS keeps a consent record and can put a prompt on screen. [`status`] may report any of
140 /// [`Status::Granted`], [`Status::Denied`], [`Status::Prompt`] or [`Status::Restricted`].
141 Prompts,
142 /// The capability exists and nothing gates it; desktop Linux and Windows have no consent
143 /// database. [`status`] always reports [`Status::Granted`] and [`request`] resolves without a
144 /// prompt.
145 Ungated,
146 /// The capability does not exist on this target at all. [`status`] always reports
147 /// [`Status::Unsupported`].
148 Absent,
149}
150
151impl Gate {
152 /// A short display label (`"prompts"` / `"ungated"` / `"absent"`).
153 #[must_use]
154 pub fn label(self) -> &'static str {
155 match self {
156 Gate::Prompts => "prompts",
157 Gate::Ungated => "ungated",
158 Gate::Absent => "absent",
159 }
160 }
161}
162
163impl std::fmt::Display for Gate {
164 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
165 f.write_str(self.label())
166 }
167}
168
169/// What the OS will do if the capability is used now.
170#[non_exhaustive]
171#[derive(Clone, Copy, Debug, PartialEq, Eq)]
172pub enum Status {
173 /// Go ahead. Not a promise that the hardware exists: a laptop with no camera still answers
174 /// `Granted`, because no permission stands in the way. Ask the capability's own part (e.g.
175 /// `day_part_sensors::is_available`) about hardware.
176 Granted,
177 /// The user said no. Whether asking again can help is [`can_prompt`]'s answer: on Apple it never
178 /// can (send them to [`open_settings`]); on Android it depends on whether they checked
179 /// "don't ask again".
180 Denied,
181 /// Nobody has decided yet; [`request`] will put a prompt on screen. The platforms spell this
182 /// `notDetermined` (Apple), `'prompt'` (web), or "not granted and never asked".
183 Prompt,
184 /// Policy forbids it and the user cannot change that: iOS `restricted` (Screen Time, MDM,
185 /// supervised devices), or a permission missing from the app's merged manifest on Android.
186 /// A request there returns denied in the same frame and Settings has nothing to offer.
187 Restricted,
188 /// This target has no such capability ([`Gate::Absent`]).
189 Unsupported,
190 /// Not known yet. Only two situations produce it, and only from the synchronous [`status`]:
191 /// the web, where `navigator.permissions.query()` is asynchronous, and Apple `Notifications`,
192 /// whose settings have no synchronous accessor. Both prime a cache on first use, so this is
193 /// a first-call state rather than a lasting one, and [`status_future`] never returns it.
194 Unknown,
195}
196
197impl Status {
198 /// Whether the capability may be used now.
199 #[must_use]
200 pub fn is_granted(self) -> bool {
201 self == Status::Granted
202 }
203
204 /// A short display label (`"granted"`, `"denied"`, `"prompt"`, `"restricted"`,
205 /// `"unsupported"`, `"unknown"`). Locale-independent, so safe to assert on in dayscript.
206 #[must_use]
207 pub fn label(self) -> &'static str {
208 match self {
209 Status::Granted => "granted",
210 Status::Denied => "denied",
211 Status::Prompt => "prompt",
212 Status::Restricted => "restricted",
213 Status::Unsupported => "unsupported",
214 Status::Unknown => "unknown",
215 }
216 }
217}
218
219impl std::fmt::Display for Status {
220 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
221 f.write_str(self.label())
222 }
223}
224
225// ---------------------------------------------------------------------------
226// Query
227// ---------------------------------------------------------------------------
228
229/// Whether this target gates `perm` at all (fixed at compile time for most permissions; a few are
230/// decided by the OS version, e.g. Android motion below API 29).
231#[must_use]
232pub fn gate(perm: Permission) -> Gate {
233 imp::gate(perm)
234}
235
236/// What the OS will do if `perm` is used now. Never blocks.
237///
238/// On the web, and for `Notifications` on Apple platforms, the platform can only answer
239/// asynchronously: this returns the last value this process observed, or [`Status::Unknown`] before
240/// the first observation. Use [`status_future`] when the answer must be authoritative.
241#[must_use]
242pub fn status(perm: Permission) -> Status {
243 imp::status(perm)
244}
245
246/// [`status`], but always authoritative: it waits for the platform's answer where that is
247/// asynchronous, so it never yields [`Status::Unknown`].
248///
249/// `on_done` may run before this returns: on the platforms with a synchronous answer there is
250/// nothing to wait for, and the web has no other thread to defer to.
251pub fn status_async(perm: Permission, on_done: impl FnOnce(Status) + Send + 'static) {
252 imp::status_async(perm, Box::new(on_done));
253}
254
255/// [`status_async`] as a `Future`. Plain oneshot plumbing over the same completion; any executor
256/// can await it, including a test's `block_on`.
257#[must_use]
258pub fn status_future(perm: Permission) -> StatusFuture {
259 let shared = new_state();
260 let sink = shared.clone();
261 imp::status_async(perm, Box::new(move |s| settle(&sink, s)));
262 StatusFuture {
263 shared,
264 done: false,
265 }
266}
267
268/// Whether calling [`request`] would actually put a prompt on screen right now. When this is
269/// `false` the answer is already final for this launch, so draw an "open Settings" path
270/// ([`open_settings`]) rather than a "grant access" button.
271#[must_use]
272pub fn can_prompt(perm: Permission) -> bool {
273 imp::can_prompt(perm)
274}
275
276/// Whether the user has already refused once and a further prompt is still possible: the
277/// platform's signal that an explanation should come first. This is Android's
278/// `shouldShowRequestPermissionRationale`; every other platform answers `false`, because Apple
279/// never re-prompts and the web has no equivalent.
280///
281/// This crate cannot draw the explanation itself (a part must not depend on `day-pieces`), which is
282/// the right split anyway: the copy is yours and belongs in your own `res::str` keys.
283#[must_use]
284pub fn should_show_rationale(perm: Permission) -> bool {
285 imp::should_show_rationale(perm)
286}
287
288// ---------------------------------------------------------------------------
289// Request
290// ---------------------------------------------------------------------------
291
292/// Ask the OS for `perm`, showing the system prompt when [`can_prompt`] says one would appear and
293/// resolving immediately with the current status when it would not.
294///
295/// `on_done` runs on an unspecified thread, possibly the UI thread, so capture a
296/// `day_reactive::Setter` to deliver into UI state. There is no blocking form: every platform
297/// draws the prompt on the thread a blocking call would park.
298///
299/// Concurrent requests for the same permission coalesce: the second caller joins the first, one
300/// prompt appears, and both callbacks receive the same answer.
301pub fn request(perm: Permission, on_done: impl FnOnce(Status) + Send + 'static) {
302 request_boxed(perm, Box::new(on_done));
303}
304
305/// [`request`] as a `Future`.
306///
307/// Dropping it stops you listening; it does **not** take the dialog off the screen, because no
308/// platform can dismiss its own permission prompt programmatically. The user's answer is still
309/// recorded, so the next [`status`] is correct. (This is the one place this crate's futures differ
310/// from `day-part-http`'s, whose `Drop` really does cancel the request.)
311#[must_use]
312pub fn request_future(perm: Permission) -> StatusFuture {
313 let shared = new_state();
314 let sink = shared.clone();
315 request_boxed(perm, Box::new(move |s| settle(&sink, s)));
316 StatusFuture {
317 shared,
318 done: false,
319 }
320}
321
322/// Ask for several permissions in one prompt sequence where the platform batches them (Android
323/// submits a single array; elsewhere they are chained). Answers are positional: `out[i]` is the
324/// status of `perms[i]`.
325pub fn request_many(perms: &[Permission], on_done: impl FnOnce(Vec<Status>) + Send + 'static) {
326 let perms = perms.to_vec();
327 let n = perms.len();
328 if n == 0 {
329 on_done(Vec::new());
330 return;
331 }
332 // Collect into a slot-indexed buffer; the last completion hands the whole vector over. Every
333 // per-permission request already coalesces, so a duplicate in `perms` costs no extra prompt.
334 let state = Arc::new(Mutex::new((
335 vec![Status::Unknown; n],
336 n,
337 Some(Box::new(on_done) as ManyCb),
338 )));
339 for (i, p) in perms.into_iter().enumerate() {
340 let state = state.clone();
341 request_boxed(
342 p,
343 Box::new(move |s| {
344 let finished = {
345 let mut st = lock(&state);
346 st.0[i] = s;
347 st.1 -= 1;
348 if st.1 == 0 { st.2.take() } else { None }
349 };
350 // Outside the lock: the callback is user code and must never run under it.
351 if let Some(cb) = finished {
352 let out = std::mem::take(&mut lock(&state).0);
353 cb(out);
354 }
355 }),
356 );
357 }
358}
359
360/// [`request_many`] as a `Future`.
361#[must_use]
362pub fn request_many_future(perms: &[Permission]) -> StatusesFuture {
363 let shared = Arc::new(Mutex::new(AnswerState::<Vec<Status>>::default()));
364 let sink = shared.clone();
365 request_many(perms, move |v| settle(&sink, v));
366 StatusesFuture {
367 shared,
368 done: false,
369 }
370}
371
372/// Open the OS page where the user can change this app's permissions. `true` if a page was opened.
373///
374/// iOS uses `UIApplication.openSettingsURLString`, macOS the per-permission
375/// `x-apple.systempreferences:` privacy anchor, Android `ACTION_APPLICATION_DETAILS_SETTINGS`, and
376/// HarmonyOS the application-info ability. The web and desktop Linux/Windows have no such
377/// destination and answer `false`.
378pub fn open_settings(perm: Permission) -> bool {
379 imp::open_settings(perm)
380}
381
382// ---------------------------------------------------------------------------
383// Coalescing table
384// ---------------------------------------------------------------------------
385
386type Cb = Box<dyn FnOnce(Status) + Send>;
387type ManyCb = Box<dyn FnOnce(Vec<Status>) + Send>;
388
389/// In-flight requests, keyed by permission: a second caller joins the first rather than putting a
390/// second prompt on screen (which Android answers with an empty grant array and the web answers
391/// with a duplicate dialog). The crate owns this table itself, the way `day-part-http` owns its
392/// cancel-token table; a part cannot use day-core's `present()` rail.
393///
394/// This is a leaf lock: no platform call and no user callback ever runs while it is held.
395fn inflight() -> &'static Mutex<HashMap<Permission, Vec<Cb>>> {
396 static INFLIGHT: std::sync::OnceLock<Mutex<HashMap<Permission, Vec<Cb>>>> =
397 std::sync::OnceLock::new();
398 INFLIGHT.get_or_init(|| Mutex::new(HashMap::new()))
399}
400
401fn request_boxed(perm: Permission, on_done: Cb) {
402 // Fast paths that need no prompt and no table entry.
403 if gate(perm) == Gate::Absent {
404 on_done(Status::Unsupported);
405 return;
406 }
407 let now = status(perm);
408 if matches!(now, Status::Granted | Status::Restricted)
409 || (now == Status::Denied && !can_prompt(perm))
410 {
411 on_done(now);
412 return;
413 }
414
415 let start = {
416 let mut table = lock(inflight());
417 if let Some(waiters) = table.get_mut(&perm) {
418 waiters.push(on_done);
419 false
420 } else {
421 table.insert(perm, vec![on_done]);
422 true
423 }
424 };
425 if start {
426 imp::request(perm, Box::new(move |s| resolve(perm, s)));
427 }
428}
429
430/// Deliver `s` to everyone waiting on `perm`. Called from whatever thread the platform completes
431/// on; takes the waiters out under the lock and invokes them after releasing it.
432fn resolve(perm: Permission, s: Status) {
433 let waiters = lock(inflight()).remove(&perm).unwrap_or_default();
434 for cb in waiters {
435 cb(s);
436 }
437}
438
439// ---------------------------------------------------------------------------
440// Futures
441// ---------------------------------------------------------------------------
442
443/// Shared state between a future and the completion that resolves it.
444///
445/// Locking protocol (the mutex is a leaf lock; no platform or user code runs under it):
446/// - `poll` checks the answer and stores the waker under one acquisition, closing the lost-wakeup
447/// race a check-then-store would open.
448/// - the completion stores the answer, takes the waker, unlocks, then wakes, because an inline
449/// waker (as in tests) re-polls synchronously, which re-takes the lock.
450struct AnswerState<T> {
451 answer: Option<T>,
452 waker: Option<std::task::Waker>,
453}
454
455impl<T> Default for AnswerState<T> {
456 fn default() -> Self {
457 AnswerState {
458 answer: None,
459 waker: None,
460 }
461 }
462}
463
464fn new_state() -> Arc<Mutex<AnswerState<Status>>> {
465 Arc::new(Mutex::new(AnswerState::default()))
466}
467
468fn settle<T>(shared: &Arc<Mutex<AnswerState<T>>>, value: T) {
469 let waker = {
470 let mut st = lock(shared);
471 st.answer = Some(value);
472 st.waker.take()
473 };
474 if let Some(w) = waker {
475 w.wake();
476 }
477}
478
479/// Lock, riding out poisoning: a panic while holding one of this crate's locks leaves plain data
480/// behind (no broken invariants), so the poisoned value is still the truth.
481fn lock<T>(m: &Mutex<T>) -> MutexGuard<'_, T> {
482 match m.lock() {
483 Ok(g) => g,
484 Err(poisoned) => poisoned.into_inner(),
485 }
486}
487
488/// A pending permission answer, from [`status_future`] or [`request_future`].
489///
490/// Dropping one stops you listening. It does not dismiss a prompt that is already on screen (no
491/// platform offers that), so the user's answer is still recorded and the next [`status`] reflects
492/// it. Aborting a `day::task` that awaits one therefore leaves the dialog up.
493pub struct StatusFuture {
494 shared: Arc<Mutex<AnswerState<Status>>>,
495 done: bool,
496}
497
498impl Future for StatusFuture {
499 type Output = Status;
500
501 fn poll(
502 mut self: std::pin::Pin<&mut Self>,
503 cx: &mut std::task::Context<'_>,
504 ) -> std::task::Poll<Status> {
505 let mut st = lock(&self.shared);
506 if let Some(a) = st.answer.take() {
507 drop(st);
508 self.done = true;
509 return std::task::Poll::Ready(a);
510 }
511 st.waker = Some(cx.waker().clone());
512 std::task::Poll::Pending
513 }
514}
515
516impl Drop for StatusFuture {
517 fn drop(&mut self) {
518 if !self.done {
519 lock(&self.shared).waker = None;
520 }
521 }
522}
523
524/// The [`request_many_future`] counterpart of [`StatusFuture`]; same drop semantics.
525pub struct StatusesFuture {
526 shared: Arc<Mutex<AnswerState<Vec<Status>>>>,
527 done: bool,
528}
529
530impl Future for StatusesFuture {
531 type Output = Vec<Status>;
532
533 fn poll(
534 mut self: std::pin::Pin<&mut Self>,
535 cx: &mut std::task::Context<'_>,
536 ) -> std::task::Poll<Vec<Status>> {
537 let mut st = lock(&self.shared);
538 if let Some(a) = st.answer.take() {
539 drop(st);
540 self.done = true;
541 return std::task::Poll::Ready(a);
542 }
543 st.waker = Some(cx.waker().clone());
544 std::task::Poll::Pending
545 }
546}
547
548impl Drop for StatusesFuture {
549 fn drop(&mut self) {
550 if !self.done {
551 lock(&self.shared).waker = None;
552 }
553 }
554}
555
556// ---------------------------------------------------------------------------
557// Shared logic: compiled on every target and unit-tested on any host, so the decisions most
558// likely to be wrong are covered even though parts are not in the workspace's default-members.
559//
560// `allow(dead_code)`: each helper is called by one platform's arm (`classify_android` by Android,
561// `from_web_state` by the web, `merge` by the two with one-to-many permission fan-out), so it looks
562// unused on every other target. Keeping them here rather than in the arms is what makes them
563// testable on a host that can't compile those arms at all.
564// ---------------------------------------------------------------------------
565
566/// Fold the statuses of several native permissions that one portable permission maps onto (Android
567/// `Location` → `{FINE, COARSE}`). Precedence, most to least permissive:
568/// `Granted > Prompt > Denied > Restricted > Unsupported > Unknown`.
569///
570/// `Granted` wins because coarse-only location is still location; `Prompt` outranks `Denied` because
571/// a prompt that can still be shown is the actionable state.
572#[allow(dead_code)]
573pub(crate) fn merge(a: Status, b: Status) -> Status {
574 fn rank(s: Status) -> u8 {
575 match s {
576 Status::Granted => 5,
577 Status::Prompt => 4,
578 Status::Denied => 3,
579 Status::Restricted => 2,
580 Status::Unsupported => 1,
581 Status::Unknown => 0,
582 }
583 }
584 if rank(a) >= rank(b) { a } else { b }
585}
586
587/// Turn Android's three probes into a [`Status`].
588///
589/// `declared` is whether the permission survived into the app's MERGED manifest; without it a
590/// request returns denied in the same frame and Settings cannot help, which is exactly
591/// [`Status::Restricted`].
592///
593/// Day keeps no "already asked" state, so a denied-but-declared permission with no rationale flag
594/// is reported as [`Status::Prompt`] whether the user has never been asked or has permanently
595/// refused. That is safe (asking after a permanent refusal shows no dialog and resolves `Denied`
596/// immediately), and an app that needs the distinction should record it when it calls
597/// [`request`] (docs/permissions.md shows the three-line `day-part-preferences` recipe).
598#[allow(dead_code)]
599pub(crate) fn classify_android(granted: bool, declared: bool, rationale: bool) -> Status {
600 match (granted, declared, rationale) {
601 (true, _, _) => Status::Granted,
602 (false, false, _) => Status::Restricted,
603 (false, true, true) => Status::Denied,
604 (false, true, false) => Status::Prompt,
605 }
606}
607
608/// Map a browser `PermissionStatus.state` string. Unknown values are `Prompt`, not `Unsupported`:
609/// a browser that doesn't recognize `{name:'camera'}` in `permissions.query` can still show the
610/// prompt through `getUserMedia`, so the actionable answer is "ask".
611#[allow(dead_code)]
612pub(crate) fn from_web_state(state: &str) -> Status {
613 match state {
614 "granted" => Status::Granted,
615 "denied" => Status::Denied,
616 _ => Status::Prompt,
617 }
618}
619
620/// Map an Apple framework authorization constant. The four frameworks agree on the low values
621/// (0 notDetermined, 1 restricted, 2 denied, 3 authorized) and differ above them: `PHPhotoLibrary`
622/// uses 4 for `limited` and `UNUserNotificationCenter` 4 for `provisional`, both of which mean the
623/// app may proceed, and `CLLocationManager` uses 4 for `authorizedWhenInUse`.
624#[allow(dead_code)]
625pub(crate) fn from_apple_status(raw: i64) -> Status {
626 match raw {
627 0 => Status::Prompt,
628 1 => Status::Restricted,
629 2 => Status::Denied,
630 3 | 4 => Status::Granted,
631 _ => Status::Unknown,
632 }
633}
634
635// ---------------------------------------------------------------------------
636// Per-OS implementations. Each exposes `gate`, `status`, `status_async`, `can_prompt`,
637// `should_show_rationale`, `request` and `open_settings`.
638// ---------------------------------------------------------------------------
639
640#[cfg(any(target_os = "macos", target_os = "ios"))]
641#[path = "apple.rs"]
642mod imp;
643
644#[cfg(target_os = "android")]
645#[path = "android.rs"]
646mod imp;
647
648// Desktop/embedded Linux has no consent database; HarmonyOS (also `target_os = "linux"`) has one.
649#[cfg(all(target_os = "linux", not(target_env = "ohos")))]
650#[path = "defaults.rs"]
651mod imp;
652
653#[cfg(all(target_os = "linux", target_env = "ohos"))]
654#[path = "ohos.rs"]
655mod imp;
656
657#[cfg(target_os = "windows")]
658#[path = "defaults.rs"]
659mod imp;
660
661#[cfg(target_arch = "wasm32")]
662#[path = "web.rs"]
663mod imp;
664
665// Any other platform: no permission system, and no capability either; nothing here is known to
666// work.
667#[cfg(not(any(
668 target_os = "macos",
669 target_os = "ios",
670 target_os = "windows",
671 target_os = "linux",
672 target_os = "android",
673 target_arch = "wasm32"
674)))]
675mod imp {
676 use super::{Gate, Permission, Status};
677
678 pub fn gate(_perm: Permission) -> Gate {
679 Gate::Absent
680 }
681 pub fn status(_perm: Permission) -> Status {
682 Status::Unsupported
683 }
684 pub fn status_async(_perm: Permission, on_done: Box<dyn FnOnce(Status) + Send>) {
685 on_done(Status::Unsupported);
686 }
687 pub fn can_prompt(_perm: Permission) -> bool {
688 false
689 }
690 pub fn should_show_rationale(_perm: Permission) -> bool {
691 false
692 }
693 pub fn request(_perm: Permission, on_done: Box<dyn FnOnce(Status) + Send>) {
694 on_done(Status::Unsupported);
695 }
696 pub fn open_settings(_perm: Permission) -> bool {
697 false
698 }
699}
700
701// ---------------------------------------------------------------------------
702// Platform-specific permission constants. Each module is `#[cfg]`-gated, so naming a permission
703// that doesn't exist on the compiled target is a compile error rather than a silent `Unsupported`.
704// ---------------------------------------------------------------------------
705
706/// Android permission ids beyond the portable set.
707#[cfg(any(doc, target_os = "android"))]
708pub mod android {
709 use super::Permission;
710
711 pub const ACTIVITY_RECOGNITION: Permission =
712 Permission::Raw("android.permission.ACTIVITY_RECOGNITION");
713 pub const BLUETOOTH_CONNECT: Permission =
714 Permission::Raw("android.permission.BLUETOOTH_CONNECT");
715 pub const BLUETOOTH_SCAN: Permission = Permission::Raw("android.permission.BLUETOOTH_SCAN");
716 pub const READ_CONTACTS: Permission = Permission::Raw("android.permission.READ_CONTACTS");
717 pub const READ_CALENDAR: Permission = Permission::Raw("android.permission.READ_CALENDAR");
718 pub const CALL_PHONE: Permission = Permission::Raw("android.permission.CALL_PHONE");
719 pub const READ_MEDIA_VISUAL_USER_SELECTED: Permission =
720 Permission::Raw("android.permission.READ_MEDIA_VISUAL_USER_SELECTED");
721
722 /// Any other Android permission id.
723 #[must_use]
724 pub const fn raw(name: &'static str) -> Permission {
725 Permission::Raw(name)
726 }
727}
728
729/// HarmonyOS permission names beyond the portable set.
730#[cfg(any(doc, all(target_os = "linux", target_env = "ohos")))]
731pub mod ohos {
732 use super::Permission;
733
734 pub const APPROXIMATELY_LOCATION: Permission =
735 Permission::Raw("ohos.permission.APPROXIMATELY_LOCATION");
736 pub const READ_CONTACTS: Permission = Permission::Raw("ohos.permission.READ_CONTACTS");
737 pub const READ_CALENDAR: Permission = Permission::Raw("ohos.permission.READ_CALENDAR");
738 pub const DISTRIBUTED_DATASYNC: Permission =
739 Permission::Raw("ohos.permission.DISTRIBUTED_DATASYNC");
740
741 /// Any other HarmonyOS permission name.
742 pub const fn raw(name: &'static str) -> Permission {
743 Permission::Raw(name)
744 }
745}
746
747/// Apple authorizations beyond the portable set.
748///
749/// Apple has no permission *strings* (each of these is a per-framework authorization API), so
750/// these ids are this crate's namespace, recognized by its Apple implementation.
751#[cfg(any(doc, target_os = "macos", target_os = "ios"))]
752pub mod apple {
753 use super::Permission;
754
755 pub const SPEECH_RECOGNITION: Permission = Permission::Raw("apple.speech");
756 pub const CONTACTS: Permission = Permission::Raw("apple.contacts");
757 pub const CALENDAR: Permission = Permission::Raw("apple.calendar");
758 pub const REMINDERS: Permission = Permission::Raw("apple.reminders");
759 pub const MEDIA_LIBRARY: Permission = Permission::Raw("apple.media-library");
760 pub const APP_TRACKING: Permission = Permission::Raw("apple.tracking");
761 pub const LOCAL_NETWORK: Permission = Permission::Raw("apple.local-network");
762}
763
764/// Browser Permissions-API names beyond the portable set. The string is passed straight to
765/// `navigator.permissions.query`.
766#[cfg(any(doc, target_arch = "wasm32"))]
767pub mod web {
768 use super::Permission;
769
770 pub const MIDI: Permission = Permission::Raw("midi");
771 pub const CLIPBOARD_READ: Permission = Permission::Raw("clipboard-read");
772 pub const CLIPBOARD_WRITE: Permission = Permission::Raw("clipboard-write");
773 pub const SCREEN_WAKE_LOCK: Permission = Permission::Raw("screen-wake-lock");
774 pub const PERSISTENT_STORAGE: Permission = Permission::Raw("persistent-storage");
775
776 /// Any other Permissions-API name.
777 pub const fn raw(name: &'static str) -> Permission {
778 Permission::Raw(name)
779 }
780}
781
782#[cfg(test)]
783mod tests {
784 use super::*;
785
786 const PORTABLE: [Permission; 7] = [
787 Permission::Location,
788 Permission::LocationAlways,
789 Permission::Camera,
790 Permission::Microphone,
791 Permission::Notifications,
792 Permission::Photos,
793 Permission::Motion,
794 ];
795
796 /// Probing must never panic, whatever the host is: CI runners lack sensors, a camera
797 /// entitlement, and often a window server.
798 #[test]
799 fn probing_never_panics() {
800 for p in PORTABLE
801 .into_iter()
802 .chain([Permission::Raw("nonsense.permission")])
803 {
804 let _ = gate(p);
805 let _ = status(p);
806 let _ = can_prompt(p);
807 let _ = should_show_rationale(p);
808 let _ = p.as_str();
809 }
810 }
811
812 /// The two vocabularies must agree: a target that doesn't gate a capability reports it as
813 /// usable, and one that lacks the capability reports it as absent.
814 #[test]
815 fn gate_and_status_agree() {
816 for p in PORTABLE {
817 match gate(p) {
818 Gate::Ungated => assert_eq!(status(p), Status::Granted, "{p} is ungated"),
819 Gate::Absent => assert_eq!(status(p), Status::Unsupported, "{p} is absent"),
820 Gate::Prompts => assert_ne!(status(p), Status::Unsupported, "{p} prompts"),
821 }
822 }
823 }
824
825 #[test]
826 fn merge_precedence() {
827 assert_eq!(merge(Status::Denied, Status::Granted), Status::Granted);
828 assert_eq!(merge(Status::Prompt, Status::Denied), Status::Prompt);
829 assert_eq!(merge(Status::Restricted, Status::Denied), Status::Denied);
830 assert_eq!(
831 merge(Status::Unknown, Status::Unsupported),
832 Status::Unsupported
833 );
834 assert_eq!(merge(Status::Granted, Status::Granted), Status::Granted);
835 }
836
837 /// The whole Android truth table, including the deliberate never-asked/permanently-denied
838 /// conflation Day accepts by keeping no state of its own.
839 #[test]
840 fn android_truth_table() {
841 assert_eq!(classify_android(true, true, false), Status::Granted);
842 assert_eq!(classify_android(true, false, false), Status::Granted);
843 assert_eq!(classify_android(false, false, false), Status::Restricted);
844 assert_eq!(classify_android(false, true, true), Status::Denied);
845 assert_eq!(classify_android(false, true, false), Status::Prompt);
846 }
847
848 #[test]
849 fn apple_and_web_mappings() {
850 assert_eq!(from_apple_status(0), Status::Prompt);
851 assert_eq!(from_apple_status(1), Status::Restricted);
852 assert_eq!(from_apple_status(2), Status::Denied);
853 assert_eq!(from_apple_status(3), Status::Granted);
854 // limited (Photos) / provisional (notifications) / whenInUse (location) all mean "proceed".
855 assert_eq!(from_apple_status(4), Status::Granted);
856 assert_eq!(from_web_state("granted"), Status::Granted);
857 assert_eq!(from_web_state("denied"), Status::Denied);
858 // An unrecognized name still has a working request path, so "ask" is the useful answer.
859 assert_eq!(from_web_state("weird"), Status::Prompt);
860 }
861
862 /// Labels are a wire format: dayscript asserts on them and they must not drift with the locale.
863 #[test]
864 fn labels_are_stable() {
865 assert_eq!(Status::Granted.label(), "granted");
866 assert_eq!(Status::Prompt.label(), "prompt");
867 assert_eq!(Gate::Ungated.label(), "ungated");
868 assert_eq!(Permission::LocationAlways.as_str(), "location-always");
869 assert_eq!(Permission::Raw("x.y").as_str(), "x.y");
870 }
871
872 /// An empty batch must still call back (and not deadlock on the join counter).
873 #[test]
874 fn request_many_empty_completes() {
875 let seen = Arc::new(Mutex::new(None));
876 let sink = seen.clone();
877 request_many(&[], move |v| *lock(&sink) = Some(v));
878 assert_eq!(*lock(&seen), Some(Vec::new()));
879 }
880}