kunkunsh / kunkun

An open source, cross-platform, extensible app launcher.
https://kunkun.sh
46 stars 6 forks source link

Request Screen Record Permission on MacOS #45

Open HuakunShen opened 3 weeks ago

HuakunShen commented 3 weeks ago

Without permission, screencapture command initiated from the app could only capture wallpaper, all windows are ignored.

HuakunShen commented 3 weeks ago
extern crate core_foundation;
extern crate objc;

use objc::runtime::{Object, BOOL, YES, NO};
use objc::{msg_send, sel, sel_impl};
use std::ptr;

#[link(name = "CoreGraphics", kind = "framework")]
extern "C" {
    fn CGRequestScreenCaptureAccess() -> BOOL;
    fn CGPreflightScreenCaptureAccess() -> BOOL;
}

fn request_screen_capture_access() -> bool {
    unsafe {
        let result: BOOL = CGRequestScreenCaptureAccess();
        result == YES
    }
}

fn preflight_screen_capture_access() -> bool {
    unsafe {
        let result: BOOL = CGPreflightScreenCaptureAccess();
        result == YES
    }
}

fn main() {
    // Check if we already have screen capture access
    if preflight_screen_capture_access() {
        println!("Screen capture access already granted");
    } else {
        println!("Requesting screen capture access...");

        // Request screen capture access
        if request_screen_capture_access() {
            println!("Screen capture access granted");
        } else {
            println!("Screen capture access denied or not granted yet");
        }
    }
}

This rust code works.

However, if user denied access when the permission prompt shows up the first time, this script will fail. This requires reseting the permission.

tccutil reset ScreenCapture [bundle identifier]

After deny, the app shows up in settings with the toggle set to off. Have to reset permission first, then request again.