strata_device/
permissions.rs1use std::collections::HashMap;
4use std::sync::{Mutex, OnceLock};
5use strata_dom::Signal;
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
9pub enum PermissionKind {
10 Microphone,
11 Camera,
12 ScreenCapture,
13 Geolocation,
14 Bluetooth,
15 Serial,
16 UsbHid,
17 Midi,
18 Notifications,
19 Biometrics,
20 MotionSensors,
21 BodySensors,
22}
23
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
26pub enum PermissionStatus {
27 Granted,
28 Denied,
29 Prompt,
30 Restricted,
31 Unsupported,
32}
33
34static MOCK_PERMS: OnceLock<Mutex<HashMap<PermissionKind, PermissionStatus>>> = OnceLock::new();
35
36fn mock_perms() -> &'static Mutex<HashMap<PermissionKind, PermissionStatus>> {
37 MOCK_PERMS.get_or_init(|| Mutex::new(HashMap::new()))
38}
39
40pub fn set_mock_permission(kind: PermissionKind, status: Option<PermissionStatus>) {
42 if let Ok(mut map) = mock_perms().lock() {
43 match status {
44 Some(s) => {
45 map.insert(kind, s);
46 }
47 None => {
48 map.remove(&kind);
49 }
50 }
51 }
52}
53
54pub fn clear_mock_permissions() {
56 if let Ok(mut map) = mock_perms().lock() {
57 map.clear();
58 }
59}
60
61pub fn check_permission(kind: PermissionKind) -> PermissionStatus {
63 if let Ok(map) = mock_perms().lock() {
64 if let Some(&status) = map.get(&kind) {
65 return status;
66 }
67 }
68
69 #[cfg(target_os = "linux")]
70 {
71 match kind {
72 PermissionKind::Microphone | PermissionKind::Midi => {
73 if std::path::Path::new("/dev/snd").exists() {
74 PermissionStatus::Granted
75 } else {
76 PermissionStatus::Unsupported
77 }
78 }
79 PermissionKind::Camera => {
80 if std::path::Path::new("/dev/video0").exists() {
81 PermissionStatus::Granted
82 } else {
83 PermissionStatus::Prompt
84 }
85 }
86 PermissionKind::ScreenCapture | PermissionKind::Notifications => {
87 if std::env::var("DBUS_SESSION_BUS_ADDRESS").is_ok()
88 || std::env::var("DISPLAY").is_ok()
89 || std::env::var("WAYLAND_DISPLAY").is_ok()
90 {
91 PermissionStatus::Granted
92 } else {
93 PermissionStatus::Prompt
94 }
95 }
96 PermissionKind::Bluetooth => {
97 if std::path::Path::new("/run/dbus/system_bus_socket").exists() {
98 PermissionStatus::Granted
99 } else {
100 PermissionStatus::Unsupported
101 }
102 }
103 PermissionKind::Serial | PermissionKind::UsbHid => PermissionStatus::Granted,
104 PermissionKind::Geolocation
105 | PermissionKind::Biometrics
106 | PermissionKind::MotionSensors
107 | PermissionKind::BodySensors => PermissionStatus::Prompt,
108 }
109 }
110
111 #[cfg(not(target_os = "linux"))]
112 {
113 let _ = kind;
114 PermissionStatus::Prompt
115 }
116}
117
118pub fn request_permission(kind: PermissionKind) -> PermissionStatus {
121 let status = check_permission(kind);
122 if status == PermissionStatus::Prompt {
123 status
126 } else {
127 status
128 }
129}
130
131pub fn use_permission(kind: PermissionKind) -> Signal<PermissionStatus> {
133 Signal::new(check_permission(kind))
134}