Files
s41r4j-pixie/apps/desktop/src-tauri/src/permissions.rs
T
s41r4jandClaude Opus 5.5 bb25820147 Add M1 desktop shell: tray, notch panel, hold-to-talk, permissions wizard
- Accessory (no Dock) Tauri 2 app with tray icon from the tray-template slot
- Panel: status window level, all Spaces, excluded from screen capture, shown
  without taking focus, positioned top-centre of the cursor's screen
- Hold ctrl+option via polled CGEventSourceFlagsState (no permission needed);
  tap to dismiss, Escape cancels; launch/close sounds on open/close
- Permissions wizard: detect/request/deep-link for Microphone, Screen Recording,
  Accessibility, Speech Recognition, Files & Folders
- slot:// protocol so the UI loads media by slot name only

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-05 02:10:07 +05:30

317 lines
11 KiB
Rust

//! Permissions wizard backend (BUILD-SPEC §9): detect each state, request it, or deep-link
//! to the right System Settings pane.
use serde::Serialize;
use std::sync::Mutex;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PermState {
Granted,
Denied,
Restricted,
NotDetermined,
/// API can't distinguish denied from not-yet-asked (Screen Recording, Accessibility).
NotGranted,
/// Not checked yet: checking would itself trigger the prompt (Files & Folders).
Unchecked,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize)]
#[serde(rename_all = "snake_case")]
pub enum PermId {
Microphone,
Screen,
Accessibility,
Speech,
Files,
}
impl PermId {
const ALL: [PermId; 5] =
[PermId::Microphone, PermId::Screen, PermId::Accessibility, PermId::Speech, PermId::Files];
fn parse(s: &str) -> Option<Self> {
Self::ALL.into_iter().find(|p| p.meta().0 == s)
}
/// (id, label, why, required, settings anchor)
fn meta(self) -> (&'static str, &'static str, &'static str, bool, &'static str) {
match self {
PermId::Microphone => ("microphone", "Microphone", "Hear you while you hold ⌃⌥.", true, "Privacy_Microphone"),
PermId::Screen => ("screen", "Screen Recording", "See what you're looking at when you ask about it.", true, "Privacy_ScreenCapture"),
PermId::Accessibility => ("accessibility", "Accessibility", "Point at buttons and type into fields for you.", true, "Privacy_Accessibility"),
PermId::Speech => ("speech", "Speech Recognition", "Turn your voice into text on this Mac.", false, "Privacy_SpeechRecognition"),
PermId::Files => ("files", "Desktop, Documents & Downloads", "Find and save files where you keep them.", false, "Privacy_FilesAndFolders"),
}
}
fn settings_url(self) -> String {
format!("x-apple.systempreferences:com.apple.preference.security?{}", self.meta().4)
}
}
#[derive(Debug, Clone, Serialize)]
pub struct PermissionInfo {
id: &'static str,
label: &'static str,
why: &'static str,
required: bool,
state: PermState,
/// Screen Recording only takes effect after a relaunch.
restart_hint: bool,
}
static FILES_STATE: Mutex<Option<PermState>> = Mutex::new(None);
fn info(id: PermId) -> PermissionInfo {
let (sid, label, why, required, _) = id.meta();
PermissionInfo {
id: sid,
label,
why,
required,
state: state(id),
restart_hint: id == PermId::Screen,
}
}
fn state(id: PermId) -> PermState {
match id {
PermId::Files => FILES_STATE.lock().ok().and_then(|s| *s).unwrap_or(PermState::Unchecked),
#[cfg(target_os = "macos")]
_ => native::state(id),
#[cfg(not(target_os = "macos"))]
_ => PermState::Granted,
}
}
/// Mic, Screen Recording and Accessibility are needed for the core loop.
pub fn required_granted() -> bool {
PermId::ALL
.into_iter()
.filter(|p| p.meta().3)
.all(|p| state(p) == PermState::Granted)
}
/// Reading the three folders is the only way to learn (and trigger) their TCC state.
fn check_files() -> PermState {
let Some(home) = std::env::var_os("HOME").map(std::path::PathBuf::from) else {
return PermState::Unchecked;
};
let mut result = PermState::Granted;
for dir in ["Desktop", "Documents", "Downloads"] {
if let Err(e) = std::fs::read_dir(home.join(dir)) {
log::info!("files permission: ~/{dir}: {e}");
if e.kind() == std::io::ErrorKind::PermissionDenied {
result = PermState::Denied;
}
}
}
if let Ok(mut s) = FILES_STATE.lock() {
*s = Some(result);
}
result
}
fn open_settings(id: PermId) {
let url = id.settings_url();
if let Err(e) = std::process::Command::new("open").arg(&url).spawn() {
log::warn!("open {url}: {e}");
}
}
#[tauri::command]
pub async fn permissions_status() -> Vec<PermissionInfo> {
tauri::async_runtime::spawn_blocking(|| PermId::ALL.into_iter().map(info).collect())
.await
.unwrap_or_default()
}
/// Ask for a permission. Shows the system prompt when macOS still allows one; otherwise
/// opens the matching System Settings pane. The UI polls `permissions_status` for the result.
#[tauri::command]
pub async fn permission_request(id: String) -> Result<PermissionInfo, String> {
let pid = PermId::parse(&id).ok_or_else(|| format!("unknown permission `{id}`"))?;
tauri::async_runtime::spawn_blocking(move || {
match pid {
PermId::Files => {
if check_files() == PermState::Denied {
open_settings(pid);
}
}
#[cfg(target_os = "macos")]
_ => {
if !native::request(pid) {
open_settings(pid);
}
}
#[cfg(not(target_os = "macos"))]
_ => {}
}
info(pid)
})
.await
.map_err(|e| e.to_string())
}
#[tauri::command]
pub fn permission_open_settings(id: String) -> Result<(), String> {
let pid = PermId::parse(&id).ok_or_else(|| format!("unknown permission `{id}`"))?;
open_settings(pid);
Ok(())
}
#[cfg(target_os = "macos")]
mod native {
use super::{PermId, PermState};
use block2::RcBlock;
use objc2::rc::{autoreleasepool, Retained};
use objc2::runtime::{AnyClass, AnyObject, Bool};
use objc2::{class, msg_send};
use objc2_foundation::{NSBundle, NSString};
use std::ffi::c_void;
#[link(name = "CoreGraphics", kind = "framework")]
extern "C" {
fn CGPreflightScreenCaptureAccess() -> bool;
fn CGRequestScreenCaptureAccess() -> bool;
}
#[link(name = "ApplicationServices", kind = "framework")]
extern "C" {
fn AXIsProcessTrusted() -> bool;
fn AXIsProcessTrustedWithOptions(options: *const c_void) -> bool;
}
#[link(name = "AVFoundation", kind = "framework")]
extern "C" {}
#[link(name = "Speech", kind = "framework")]
extern "C" {}
/// AVMediaTypeAudio's value.
const AV_MEDIA_TYPE_AUDIO: &str = "soun";
fn av_status(raw: isize) -> PermState {
// AVAuthorizationStatus: 0 notDetermined, 1 restricted, 2 denied, 3 authorized
match raw {
0 => PermState::NotDetermined,
1 => PermState::Restricted,
2 => PermState::Denied,
_ => PermState::Granted,
}
}
fn speech_status(raw: isize) -> PermState {
// SFSpeechRecognizerAuthorizationStatus: 0 notDetermined, 1 denied, 2 restricted, 3 authorized
match raw {
0 => PermState::NotDetermined,
1 => PermState::Denied,
2 => PermState::Restricted,
_ => PermState::Granted,
}
}
/// Requesting mic/speech access without a usage string aborts the process, so check
/// the Info.plist (bundled, or embedded by tauri-build in dev) first.
fn has_usage_string(key: &str) -> bool {
let bundle = NSBundle::mainBundle();
let key = NSString::from_str(key);
let value: Option<Retained<AnyObject>> =
unsafe { msg_send![&bundle, objectForInfoDictionaryKey: &*key] };
value.is_some()
}
fn mic_class() -> Option<&'static AnyClass> {
AnyClass::get(c"AVCaptureDevice")
}
fn speech_class() -> Option<&'static AnyClass> {
AnyClass::get(c"SFSpeechRecognizer")
}
pub fn state(id: PermId) -> PermState {
autoreleasepool(|_| match id {
PermId::Screen => {
if unsafe { CGPreflightScreenCaptureAccess() } { PermState::Granted } else { PermState::NotGranted }
}
PermId::Accessibility => {
if unsafe { AXIsProcessTrusted() } { PermState::Granted } else { PermState::NotGranted }
}
PermId::Microphone => match mic_class() {
Some(cls) => {
let media = NSString::from_str(AV_MEDIA_TYPE_AUDIO);
let raw: isize = unsafe { msg_send![cls, authorizationStatusForMediaType: &*media] };
av_status(raw)
}
None => PermState::NotGranted,
},
PermId::Speech => match speech_class() {
Some(cls) => speech_status(unsafe { msg_send![cls, authorizationStatus] }),
None => PermState::NotGranted,
},
PermId::Files => unreachable!("files handled by caller"),
})
}
/// Returns `true` if a system prompt was (or may have been) shown; `false` means the
/// user must flip the switch in System Settings themselves.
pub fn request(id: PermId) -> bool {
let current = state(id);
if current == PermState::Granted {
return true;
}
autoreleasepool(|_| match id {
PermId::Screen => {
// Prompts once per install; afterwards only System Settings can grant it.
unsafe { CGRequestScreenCaptureAccess() };
false
}
PermId::Accessibility => {
let key = NSString::from_str("AXTrustedCheckOptionPrompt");
let yes: Retained<AnyObject> = unsafe { msg_send![class!(NSNumber), numberWithBool: true] };
let opts: Retained<AnyObject> =
unsafe { msg_send![class!(NSDictionary), dictionaryWithObject: &*yes, forKey: &*key] };
unsafe { AXIsProcessTrustedWithOptions(Retained::as_ptr(&opts) as *const c_void) };
true
}
PermId::Microphone => {
if current != PermState::NotDetermined || !has_usage_string("NSMicrophoneUsageDescription") {
return false;
}
let Some(cls) = mic_class() else { return false };
let media = NSString::from_str(AV_MEDIA_TYPE_AUDIO);
let done = RcBlock::new(|granted: Bool| log::info!("microphone granted: {}", granted.as_bool()));
unsafe {
let _: () = msg_send![cls, requestAccessForMediaType: &*media, completionHandler: &*done];
}
true
}
PermId::Speech => {
if current != PermState::NotDetermined || !has_usage_string("NSSpeechRecognitionUsageDescription") {
return false;
}
let Some(cls) = speech_class() else { return false };
let done = RcBlock::new(|status: isize| log::info!("speech recognition status: {status}"));
unsafe {
let _: () = msg_send![cls, requestAuthorization: &*done];
}
true
}
PermId::Files => unreachable!("files handled by caller"),
})
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn ids_round_trip_and_settings_urls() {
for p in PermId::ALL {
assert_eq!(PermId::parse(p.meta().0), Some(p));
assert!(p.settings_url().starts_with("x-apple.systempreferences:com.apple.preference.security?Privacy_"));
}
assert_eq!(PermId::parse("camera"), None);
}
}