requestScreenRecordingPermission static method

Future<bool> requestScreenRecordingPermission()

Implementation

static Future<bool> requestScreenRecordingPermission() async {
  if (Platform.isMacOS) {
    final result = await Process.run(
        'sh', ['-c', 'echo ${Platform.environment['USER']}']);
    final username = result.stdout.toString().trim();
    const script =
        'tell application "System Events" to return exists (processes where name is "ControlCenter")';
    final process = await Process.run('osascript', ['-e', script]);
    final isControlCenterRunning = process.stdout.toString().trim() == 'true';

    if (!isControlCenterRunning) {
      await Process.run('open', ['-a', 'ControlCenter']);
      await Future.delayed(const Duration(seconds: 1));
    }

    final script2 = 'tell application "ControlCenter" to activate\n'
        'tell application "System Events"\n'
        '    tell process "ControlCenter"\n'
        '        click menu item "Screen Recording" of menu "File" of menu bar 1\n'
        '        delay 0.5\n'
        '        keystroke "$username" & return\n'
        '    end tell\n'
        'end tell\n';
    await Process.run('osascript', ['-e', script2]);

    await Future.delayed(const Duration(seconds: 1));
    final isScreenRecordingEnabled = await SystemChannels.platform
        .invokeMethod<bool>('isScreenRecordingEnabled');
    return isScreenRecordingEnabled ?? false;
  } else {
    return true;
  }
}