hex/native/permission_guide.m
Kit Langton 0744db0d35
permissions: follow macOS 27.3's System & App Protection Override (#2565)
macOS 27.3 renames the Accessibility list again and stops taking a tile
dragged into it, so the 480x116 drag guide sat over the pane's own
controls and asked for something the list refuses.

- Accessibility names the list "System & App Protection Override" on
  27.3+, keeps "Device Control and Data Access" on 27.0 through 27.2,
  and "Accessibility" below 27.
- hex_permission_drag_supported says whether a list takes the tile. On
  27.3 the Accessibility guide is a compact bar with no tile and no
  flight, saying to click the Privacy & Security notification or add Hex
  with +, placed below System Settings (above it when there is no room)
  so it never covers the pane's + and list controls.
- The Rune UI reads it too: the tour's Accessibility row uses the newer
  name and points at the notification and + instead of a drag.

Microphone, Screen Recording, System Audio, and macOS below 27.3 keep
their guide unchanged.
2026-11-23 14:16:14 -08:00

815 lines
32 KiB
Objective-C

#import <AppKit/AppKit.h>
#import <AVFoundation/AVFoundation.h>
#import <ApplicationServices/ApplicationServices.h>
#import <CoreGraphics/CoreGraphics.h>
#import <CoreImage/CoreImage.h>
#import <QuartzCore/QuartzCore.h>
#import <dlfcn.h>
typedef NS_ENUM(NSInteger, HexPermission) {
HexPermissionAccessibility = 1,
HexPermissionMicrophone = 2,
HexPermissionSystemAudio = 3,
HexPermissionScreenRecording = 4,
};
static NSPanel *guidePanel;
static NSTimer *guideTimer;
static BOOL sawSettingsWindow;
static HexPermission activePermission;
/// The pane the guide points at, opened again when Settings is closed under
/// it, at most `guideReopenLimit` times before the guide gives up.
static NSURL *guideSettingsURL;
static NSUInteger guideReopens;
static const NSUInteger guideReopenLimit = 2;
static NSView *guideTile;
/// The tile flies on its own from the click in Hex's window to its place in
/// the guide, so the eye can follow it to System Settings.
static NSPanel *flightPanel;
static CALayer *flightLayer;
static NSTimer *flightTimer;
static NSPoint flightOrigin;
static CFTimeInterval flightShownAt;
static CFTimeInterval flightStartedAt;
static const CGFloat flightPadding = 40;
static const CFTimeInterval flightLift = 0.18;
static const CFTimeInterval flightDuration = 0.62;
/// Settings that has not opened by then gets no flight.
static const CFTimeInterval flightPatience = 4;
@interface HexDragView : NSView <NSDraggingSource>
@property(nonatomic, strong) NSURL *bundleURL;
@property(nonatomic, strong) NSImage *appIcon;
@property(nonatomic, copy) NSString *appName;
@property(nonatomic, strong) NSEvent *mouseDownEvent;
@end
/// The name System Settings lists the app under.
static NSString *hexAppName(NSURL *bundleURL) {
NSString *name = [[NSFileManager defaultManager] displayNameAtPath:bundleURL.path];
if ([name.pathExtension.lowercaseString isEqualToString:@"app"]) {
name = name.stringByDeletingPathExtension;
}
return name.length > 0 ? name : @"Hex";
}
/// macOS 27 renamed the Accessibility list to Device Control and Data Access.
static BOOL accessibilityRenamed(void) {
NSOperatingSystemVersion version = {27, 0, 0};
return [NSProcessInfo.processInfo isOperatingSystemAtLeastVersion:version];
}
/// macOS 27.3 renamed the list again to System & App Protection Override and
/// stopped accepting tiles dragged into it; the pane adds apps with its own +
/// control instead. macOS 27.0 through 27.2 still takes the dragged tile.
static BOOL accessibilityProtected(void) {
NSOperatingSystemVersion version = {27, 3, 0};
return [NSProcessInfo.processInfo isOperatingSystemAtLeastVersion:version];
}
/// The name of the Privacy & Security list each permission lives in.
const char *hex_permission_list_name(int permission) {
switch ((HexPermission)permission) {
case HexPermissionAccessibility:
if (accessibilityProtected()) {
return "System & App Protection Override";
}
return accessibilityRenamed() ? "Device Control and Data Access" : "Accessibility";
case HexPermissionMicrophone:
return "Microphone";
case HexPermissionSystemAudio:
return "System Audio Recording Only";
case HexPermissionScreenRecording:
return "Screen & System Audio Recording";
}
return "Privacy & Security";
}
/// Whether Hex's guide can offer a tile for `permission` to drop into its
/// list. System Settings' Microphone list only holds apps that asked, so Hex
/// switches it on instead, and macOS 27.3's System & App Protection Override
/// refuses dropped tiles: it asks for a click on the Privacy & Security
/// notification and adds apps with the pane's own + control. macOS 27.0
/// through 27.2 still takes the dragged tile.
bool hex_permission_drag_supported(int permission) {
switch ((HexPermission)permission) {
case HexPermissionAccessibility:
return !accessibilityProtected();
case HexPermissionMicrophone:
return NO;
case HexPermissionSystemAudio:
case HexPermissionScreenRecording:
return YES;
}
return NO;
}
/// Asks macOS to register this running binary in Accessibility and show its
/// prompt when untrusted.
bool hex_prompt_accessibility_trust(void) {
NSDictionary *options = @{(__bridge NSString *)kAXTrustedCheckOptionPrompt: @YES};
return AXIsProcessTrustedWithOptions((__bridge CFDictionaryRef)options);
}
/// Writes the running `.app` bundle's identifier as UTF-8 into `buf`,
/// returning its byte length, or 0 outside a `.app` bundle.
size_t hex_running_app_bundle_id(char *buf, size_t cap) {
if (buf == NULL || cap == 0) {
return 0;
}
NSURL *bundleURL = NSBundle.mainBundle.bundleURL.standardizedURL;
if (![bundleURL.pathExtension.lowercaseString isEqualToString:@"app"]) {
return 0;
}
NSString *identifier = NSBundle.mainBundle.bundleIdentifier;
const char *utf8 = identifier.UTF8String;
if (utf8 == NULL) {
return 0;
}
size_t len = strlen(utf8);
if (len == 0 || len > cap) {
return 0;
}
memcpy(buf, utf8, len);
return len;
}
static BOOL isDark(NSAppearance *appearance) {
NSAppearanceName match = [appearance bestMatchFromAppearancesWithNames:@[
NSAppearanceNameAqua,
NSAppearanceNameDarkAqua,
]];
return [match isEqualToString:NSAppearanceNameDarkAqua];
}
/// The app's tile as System Settings will list it: icon and name.
static void drawTile(NSRect bounds, NSImage *icon, NSString *name, BOOL dark) {
NSBezierPath *background = [NSBezierPath bezierPathWithRoundedRect:bounds
xRadius:8
yRadius:8];
[[NSColor colorWithWhite:(dark ? 0.18 : 0.89) alpha:1] setFill];
[background fill];
[[NSColor colorWithWhite:(dark ? 1 : 0) alpha:0.10] setStroke];
background.lineWidth = 1;
[background stroke];
[icon drawInRect:NSMakeRect(10, 6, 32, 32)];
NSDictionary *attributes = @{
NSFontAttributeName: [NSFont systemFontOfSize:13 weight:NSFontWeightSemibold],
NSForegroundColorAttributeName: [NSColor colorWithWhite:(dark ? 0.94 : 0.12) alpha:1],
};
[name drawAtPoint:NSMakePoint(52, 14) withAttributes:attributes];
}
@implementation HexDragView
- (instancetype)initWithFrame:(NSRect)frame bundleURL:(NSURL *)bundleURL {
self = [super initWithFrame:frame];
if (self) {
_bundleURL = bundleURL;
_appIcon = [[NSWorkspace sharedWorkspace] iconForFile:bundleURL.path];
_appIcon.size = NSMakeSize(32, 32);
_appName = hexAppName(bundleURL);
}
return self;
}
- (BOOL)acceptsFirstMouse:(NSEvent *)event {
return YES;
}
- (void)resetCursorRects {
[self addCursorRect:self.bounds cursor:NSCursor.openHandCursor];
}
- (void)drawRect:(NSRect)dirtyRect {
[super drawRect:dirtyRect];
drawTile(self.bounds, self.appIcon, self.appName, isDark(self.effectiveAppearance));
}
- (void)mouseDown:(NSEvent *)event {
self.mouseDownEvent = event;
}
- (void)mouseDragged:(NSEvent *)event {
if (self.mouseDownEvent == nil) {
return;
}
CGFloat dx = event.locationInWindow.x - self.mouseDownEvent.locationInWindow.x;
CGFloat dy = event.locationInWindow.y - self.mouseDownEvent.locationInWindow.y;
if (hypot(dx, dy) < 3) {
return;
}
NSDraggingItem *item = [[NSDraggingItem alloc] initWithPasteboardWriter:self.bundleURL];
NSBitmapImageRep *representation = [self bitmapImageRepForCachingDisplayInRect:self.bounds];
[self cacheDisplayInRect:self.bounds toBitmapImageRep:representation];
NSImage *snapshot = [[NSImage alloc] initWithSize:self.bounds.size];
[snapshot addRepresentation:representation];
[item setDraggingFrame:self.bounds contents:snapshot];
NSDraggingSession *session = [self beginDraggingSessionWithItems:@[ item ]
event:self.mouseDownEvent
source:self];
session.animatesToStartingPositionsOnCancelOrFail = YES;
session.draggingFormation = NSDraggingFormationNone;
self.mouseDownEvent = nil;
}
- (NSDragOperation)draggingSession:(NSDraggingSession *)session
sourceOperationMaskForDraggingContext:(NSDraggingContext)context {
return NSDragOperationCopy;
}
@end
static CGRect currentSettingsFrame(void) {
CFArrayRef windowInfo = CGWindowListCopyWindowInfo(
kCGWindowListOptionOnScreenOnly | kCGWindowListExcludeDesktopElements,
kCGNullWindowID
);
NSArray *windows = CFBridgingRelease(windowInfo);
CGRect best = CGRectNull;
for (NSDictionary *window in windows) {
NSString *owner = window[(id)kCGWindowOwnerName];
if (![owner isEqualToString:@"System Settings"] &&
![owner isEqualToString:@"System Preferences"]) {
continue;
}
if ([window[(id)kCGWindowLayer] integerValue] != 0) {
continue;
}
CGRect frame;
if (!CGRectMakeWithDictionaryRepresentation(
(__bridge CFDictionaryRef)window[(id)kCGWindowBounds], &frame)) {
continue;
}
if (frame.size.width < 300 || frame.size.height < 200) {
continue;
}
if (CGRectIsNull(best) || frame.size.width * frame.size.height >
best.size.width * best.size.height) {
best = frame;
}
}
return best;
}
static NSString *const settingsBundleID = @"com.apple.systempreferences";
/// Bumped by every pane request, so an older request's retries stand down.
static NSUInteger settingsRequest;
/// Whether System Settings is the application in front, so the guide has
/// somewhere to point and must not float over anything else.
static BOOL settingsFrontmost(void) {
NSRunningApplication *front = NSWorkspace.sharedWorkspace.frontmostApplication;
return [front.bundleIdentifier isEqualToString:settingsBundleID];
}
static BOOL settingsHasWindow(void) {
NSArray<NSRunningApplication *> *apps =
[NSRunningApplication runningApplicationsWithBundleIdentifier:settingsBundleID];
if (apps.count == 0) {
return NO;
}
pid_t pid = apps.firstObject.processIdentifier;
NSArray *windows = CFBridgingRelease(CGWindowListCopyWindowInfo(
kCGWindowListOptionOnScreenOnly | kCGWindowListExcludeDesktopElements, kCGNullWindowID));
for (NSDictionary *window in windows) {
if ([window[(id)kCGWindowOwnerPID] intValue] == pid &&
[window[(id)kCGWindowLayer] integerValue] == 0) {
return YES;
}
}
return NO;
}
/// Bit 0: System Settings has an open window.
/// Bit 1: System Settings is the frontmost application.
/// Bit 2: Hex is the active application.
int hex_permission_settings_state(void) {
NSCAssert(NSThread.isMainThread, @"settings state must run on the main thread");
BOOL open = settingsHasWindow();
BOOL frontmost = settingsFrontmost();
BOOL active = NSApp.isActive;
return (open ? 1 : 0) | (frontmost ? 2 : 0) | (active ? 4 : 0);
}
/// Whether System Settings still has a real window anywhere, on another
/// Space or minimized included, rather than having been closed.
static BOOL settingsWindowExists(void) {
NSArray<NSRunningApplication *> *apps =
[NSRunningApplication runningApplicationsWithBundleIdentifier:settingsBundleID];
if (apps.count == 0) {
return NO;
}
pid_t pid = apps.firstObject.processIdentifier;
NSArray *windows = CFBridgingRelease(
CGWindowListCopyWindowInfo(kCGWindowListOptionAll, kCGNullWindowID));
for (NSDictionary *window in windows) {
if ([window[(id)kCGWindowOwnerPID] intValue] != pid ||
[window[(id)kCGWindowLayer] integerValue] != 0) {
continue;
}
CGRect frame;
if (CGRectMakeWithDictionaryRepresentation(
(__bridge CFDictionaryRef)window[(id)kCGWindowBounds], &frame) &&
frame.size.width >= 300 && frame.size.height >= 200) {
return YES;
}
}
return NO;
}
/// Opens System Settings at `url`. A System Settings that isn't running yet
/// drops the pane in the URL while it restores the pane it showed last, so
/// after a cold launch the URL goes again once its window is up and settled.
static void openSettingsPaneMayQuit(NSURL *url, BOOL mayQuit) {
NSArray<NSRunningApplication *> *running =
[NSRunningApplication runningApplicationsWithBundleIdentifier:settingsBundleID];
BOOL cold = running.count == 0;
NSUInteger request = ++settingsRequest;
// A Settings window left on another Space would pull the whole screen
// there, away from Hex. Quit it so it opens fresh on this Space.
if (mayQuit && !cold && !settingsHasWindow() && settingsWindowExists()) {
NSRunningApplication *settings = running.firstObject;
[settings terminate];
__block NSUInteger waits = 0;
[NSTimer scheduledTimerWithTimeInterval:0.05 repeats:YES block:^(NSTimer *timer) {
waits += 1;
if (request != settingsRequest) {
[timer invalidate];
return;
}
if (!settings.terminated && waits < 40) {
return;
}
[timer invalidate];
openSettingsPaneMayQuit(url, NO);
}];
return;
}
[[NSWorkspace sharedWorkspace] openURL:url];
if (!cold) {
return;
}
__block NSUInteger polls = 0;
[NSTimer scheduledTimerWithTimeInterval:0.1 repeats:YES block:^(NSTimer *timer) {
polls += 1;
if (request != settingsRequest || polls > 100) {
[timer invalidate];
return;
}
if (!settingsHasWindow()) {
return;
}
[timer invalidate];
for (NSNumber *delay in @[ @0.35, @1.2 ]) {
dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay.doubleValue * NSEC_PER_SEC)),
dispatch_get_main_queue(), ^{
if (request == settingsRequest) {
[[NSWorkspace sharedWorkspace] openURL:url];
}
});
}
}];
}
static void openSettingsPane(NSURL *url) {
openSettingsPaneMayQuit(url, YES);
}
static NSRect appKitFrame(CGRect frame) {
NSScreen *primary = NSScreen.screens.firstObject;
if (primary == nil) {
return NSRectFromCGRect(frame);
}
return NSMakeRect(
frame.origin.x,
primary.frame.size.height - frame.origin.y - frame.size.height,
frame.size.width,
frame.size.height
);
}
/// TCC's own answer for `service`, read fresh each time: 0 granted, 1
/// refused, 2 not asked yet, or -1 when the preflight is unavailable.
static int tccPreflight(CFStringRef service) {
static int (*preflight)(CFStringRef, CFDictionaryRef);
static dispatch_once_t once;
dispatch_once(&once, ^{
void *handle = dlopen(
"/System/Library/PrivateFrameworks/TCC.framework/Versions/A/TCC", RTLD_NOW);
if (handle != NULL) {
preflight = dlsym(handle, "TCCAccessPreflight");
}
});
return preflight != NULL ? preflight(service, NULL) : -1;
}
/// System Audio Recording has no public query; TCC's preflight answers it.
/// Without it, the guide waits for System Settings to close.
static BOOL systemAudioGranted(void) {
return tccPreflight(CFSTR("kTCCServiceAudioCapture")) == 0;
}
/// Screen Recording, read from TCC: `CGPreflightScreenCaptureAccess` keeps
/// the answer it read first for the life of the process, so a grant made in
/// System Settings while Hex runs never reached the guide and it hung there
/// until Hex restarted. TCC's preflight reads it now; the CoreGraphics one
/// remains only for a system where that preflight is unavailable.
static BOOL screenRecordingGranted(void) {
int status = tccPreflight(CFSTR("kTCCServiceScreenCapture"));
return status >= 0 ? status == 0 : CGPreflightScreenCaptureAccess();
}
/// AVFoundation keeps the microphone answer it read first until Hex itself
/// asks, so a grant that came another way (macOS prompting when CoreAudio
/// opened an input, or the switch in System Settings) reads from TCC.
int hex_microphone_preflight(void) {
return tccPreflight(CFSTR("kTCCServiceMicrophone"));
}
static BOOL permissionGranted(void) {
switch (activePermission) {
// What System Settings shows now: the preflights keep their launch
// answer until Hex restarts.
case HexPermissionAccessibility:
return AXIsProcessTrusted();
case HexPermissionMicrophone:
return [AVCaptureDevice authorizationStatusForMediaType:AVMediaTypeAudio] ==
AVAuthorizationStatusAuthorized ||
hex_microphone_preflight() == 0;
case HexPermissionSystemAudio:
return systemAudioGranted();
case HexPermissionScreenRecording:
return screenRecordingGranted();
}
return NO;
}
static void endFlight(void) {
[flightTimer invalidate];
flightTimer = nil;
[flightPanel orderOut:nil];
flightPanel = nil;
flightLayer = nil;
guideTile.hidden = NO;
guidePanel.alphaValue = 1;
}
static void closeGuide(void) {
endFlight();
[guideTimer invalidate];
guideTimer = nil;
[guidePanel orderOut:nil];
guidePanel = nil;
guideTile = nil;
guideSettingsURL = nil;
sawSettingsWindow = NO;
}
/// Whether the guide for `permission` is open, in front or waiting behind
/// another app for System Settings to come back.
bool hex_permission_guide_active(int permission) {
NSCAssert(NSThread.isMainThread, @"permission guide must run on the main thread");
return guidePanel != nil && activePermission == (HexPermission)permission;
}
/// Closes the guide for `permission`: Hex read the grant itself (Screen
/// Recording through a fresh helper, since this process's own preflight keeps
/// the launch answer), so there is nothing left for the tile to point at.
void hex_close_permission_guide(int permission) {
NSCAssert(NSThread.isMainThread, @"permission guide must run on the main thread");
if (guidePanel == nil || activePermission != (HexPermission)permission) {
return;
}
closeGuide();
}
static CGFloat clamp01(CGFloat value) {
return MIN(MAX(value, 0), 1);
}
static CGFloat easeInOutCubic(CGFloat t) {
return t < 0.5 ? 4 * t * t * t : 1 - pow(-2 * t + 2, 3) / 2;
}
static CGFloat easeOutCubic(CGFloat t) {
return 1 - pow(1 - t, 3);
}
/// Where the tile lands: its slot in the guide, in screen coordinates.
static NSPoint tileTarget(void) {
NSRect slot = [guideTile convertRect:guideTile.bounds toView:nil];
NSRect screen = [guidePanel convertRectToScreen:slot];
return NSMakePoint(NSMidX(screen), NSMidY(screen));
}
static void placeFlight(NSPoint center, CGFloat scale, CGFloat blur, CGFloat opacity) {
NSSize size = flightPanel.frame.size;
[flightPanel setFrameOrigin:NSMakePoint(center.x - size.width / 2, center.y - size.height / 2)];
[CATransaction begin];
[CATransaction setDisableActions:YES];
flightLayer.transform = CATransform3DMakeScale(scale, scale, 1);
flightLayer.opacity = (float)opacity;
[flightLayer setValue:@(blur) forKeyPath:@"filters.blur.inputRadius"];
[CATransaction commit];
}
static void stepFlight(void) {
CFTimeInterval now = CACurrentMediaTime();
if (flightStartedAt == 0) {
// Lifted out of the row, waiting for System Settings to open.
if (now - flightShownAt > flightPatience) {
endFlight();
return;
}
CGFloat t = easeOutCubic(clamp01((now - flightShownAt) / flightLift));
placeFlight(NSMakePoint(flightOrigin.x, flightOrigin.y + 12 * t), 0.7 + 0.1 * t,
4 * (1 - t), t);
return;
}
CGFloat t = clamp01((now - flightStartedAt) / flightDuration);
CGFloat e = easeInOutCubic(t);
NSPoint start = NSMakePoint(flightOrigin.x, flightOrigin.y + 12);
NSPoint end = tileTarget();
CGFloat distance = hypot(end.x - start.x, end.y - start.y);
NSPoint control = NSMakePoint((start.x + end.x) / 2,
MAX(start.y, end.y) + MIN(160, distance * 0.25));
CGFloat u = 1 - e;
NSPoint point = NSMakePoint(u * u * start.x + 2 * u * e * control.x + e * e * end.x,
u * u * start.y + 2 * u * e * control.y + e * e * end.y);
placeFlight(point, 0.8 + 0.2 * e, 6 * sin(M_PI * e), 1);
guidePanel.alphaValue = easeOutCubic(clamp01((t - 0.45) / 0.55));
if (t >= 1) {
endFlight();
}
}
/// The click that asked for the guide, when it was in one of Hex's windows.
static BOOL clickInHexWindow(NSPoint point) {
for (NSWindow *window in NSApp.windows) {
if (window.visible && window != guidePanel && window != flightPanel &&
NSPointInRect(point, window.frame)) {
return YES;
}
}
return NO;
}
/// Lifts a copy of the tile out of Hex's window at `origin`.
static void beginFlight(NSPoint origin, NSURL *bundleURL, NSSize tileSize) {
flightOrigin = origin;
flightShownAt = CACurrentMediaTime();
flightStartedAt = 0;
NSImage *icon = [[NSWorkspace sharedWorkspace] iconForFile:bundleURL.path];
icon.size = NSMakeSize(32, 32);
NSString *name = hexAppName(bundleURL);
BOOL dark = isDark(NSApp.effectiveAppearance);
NSImage *image = [NSImage imageWithSize:tileSize
flipped:NO
drawingHandler:^BOOL(NSRect rect) {
drawTile(rect, icon, name, dark);
return YES;
}];
NSSize size = NSMakeSize(tileSize.width + 2 * flightPadding, tileSize.height + 2 * flightPadding);
flightPanel = [[NSPanel alloc] initWithContentRect:NSMakeRect(0, 0, size.width, size.height)
styleMask:NSWindowStyleMaskBorderless |
NSWindowStyleMaskNonactivatingPanel
backing:NSBackingStoreBuffered
defer:NO];
flightPanel.level = NSFloatingWindowLevel + 1;
flightPanel.collectionBehavior = NSWindowCollectionBehaviorCanJoinAllSpaces |
NSWindowCollectionBehaviorFullScreenAuxiliary;
flightPanel.opaque = NO;
flightPanel.backgroundColor = NSColor.clearColor;
flightPanel.hasShadow = NO;
flightPanel.ignoresMouseEvents = YES;
flightPanel.hidesOnDeactivate = NO;
flightPanel.releasedWhenClosed = NO;
NSView *host = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, size.width, size.height)];
host.layer = [CALayer layer];
host.wantsLayer = YES;
host.layerUsesCoreImageFilters = YES;
flightLayer = [CALayer layer];
flightLayer.bounds = CGRectMake(0, 0, tileSize.width, tileSize.height);
flightLayer.position = CGPointMake(size.width / 2, size.height / 2);
flightLayer.contents = image;
flightLayer.contentsScale = NSScreen.mainScreen.backingScaleFactor;
flightLayer.shadowOpacity = 0.25;
flightLayer.shadowRadius = 12;
flightLayer.shadowOffset = CGSizeMake(0, -6);
CIFilter *blur = [CIFilter filterWithName:@"CIGaussianBlur"];
blur.name = @"blur";
[blur setValue:@0 forKey:kCIInputRadiusKey];
flightLayer.filters = @[ blur ];
[host.layer addSublayer:flightLayer];
flightPanel.contentView = host;
placeFlight(origin, 0.7, 4, 0);
[flightPanel orderFrontRegardless];
flightTimer = [NSTimer timerWithTimeInterval:1.0 / 120 repeats:YES block:^(NSTimer *timer) {
(void)timer;
stepFlight();
}];
[[NSRunLoop mainRunLoop] addTimer:flightTimer forMode:NSRunLoopCommonModes];
}
static void updateGuidePosition(void) {
if (permissionGranted()) {
closeGuide();
return;
}
CGRect quartzFrame = currentSettingsFrame();
if (CGRectIsNull(quartzFrame)) {
if (!sawSettingsWindow) {
return;
}
// Settings on another Space or minimized: wait for it, out of sight.
[guidePanel orderOut:nil];
if (settingsWindowExists()) {
return;
}
// Closed with the permission still missing: bring the pane back
// rather than leave the guide pointing at nothing.
if (guideSettingsURL == nil || guideReopens >= guideReopenLimit) {
closeGuide();
return;
}
guideReopens += 1;
sawSettingsWindow = NO;
openSettingsPane(guideSettingsURL);
return;
}
sawSettingsWindow = YES;
if (!settingsFrontmost()) {
// Another app is in front of System Settings: the guide points at
// nothing from there, and must not float over what the person is
// doing. It comes back when System Settings does.
[guidePanel orderOut:nil];
return;
}
NSRect settings = appKitFrame(quartzFrame);
NSSize size = guidePanel.frame.size;
NSScreen *screen = nil;
for (NSScreen *candidate in NSScreen.screens) {
if (NSIntersectsRect(candidate.frame, settings)) {
screen = candidate;
break;
}
}
if (screen == nil) {
screen = NSScreen.mainScreen;
}
NSRect visible = screen != nil ? screen.visibleFrame : settings;
if (activePermission == HexPermissionAccessibility && accessibilityProtected()) {
// macOS 27.3's System & App Protection Override keeps its own + and
// list controls at the bottom of the window, so the bar sits outside
// the window: below it when there is room, above it when there is not,
// never over its list.
CGFloat x = NSMidX(settings) - size.width / 2;
x = MIN(MAX(x, NSMinX(visible) + 8), NSMaxX(visible) - size.width - 8);
CGFloat y = NSMinY(settings) - size.height - 16;
if (y < NSMinY(visible) + 8) {
CGFloat above = NSMaxY(settings) + 16;
y = above <= NSMaxY(visible) - size.height - 8 ? above : NSMinY(visible) + 8;
}
[guidePanel setFrameOrigin:NSMakePoint(x, y)];
} else {
CGFloat x = NSMaxX(settings) - size.width - 16;
CGFloat y = NSMinY(settings) + 16;
x = MIN(MAX(x, NSMinX(visible) + 8), NSMaxX(visible) - size.width - 8);
y = MIN(MAX(y, NSMinY(visible) + 8), NSMaxY(visible) - size.height - 8);
[guidePanel setFrameOrigin:NSMakePoint(x, y)];
}
if (flightPanel != nil && flightStartedAt == 0) {
flightStartedAt = CACurrentMediaTime();
}
if (flightPanel != nil) {
[flightPanel orderFrontRegardless];
}
[guidePanel orderFrontRegardless];
}
void hex_show_permission_guide(int permission) {
NSCAssert(NSThread.isMainThread, @"permission guide must run on the main thread");
NSPoint click = NSEvent.mouseLocation;
BOOL fly = clickInHexWindow(click) &&
!NSWorkspace.sharedWorkspace.accessibilityDisplayShouldReduceMotion;
closeGuide();
activePermission = (HexPermission)permission;
guideReopens = 0;
NSURL *bundleURL = NSBundle.mainBundle.bundleURL.standardizedURL;
NSString *listName = [NSString stringWithUTF8String:hex_permission_list_name(permission)];
NSString *appName = hexAppName(bundleURL);
NSString *pane;
switch (activePermission) {
case HexPermissionAccessibility:
pane = @"Privacy_Accessibility";
break;
case HexPermissionMicrophone:
pane = @"Privacy_Microphone";
break;
case HexPermissionSystemAudio:
pane = @"Privacy_AudioCapture";
break;
case HexPermissionScreenRecording:
pane = @"Privacy_ScreenCapture";
break;
}
// The Microphone list only holds apps that asked, so a refused
// microphone is switched on rather than dragged in; macOS 27.3's
// Accessibility pane no longer takes a dropped tile at all.
BOOL draggable = hex_permission_drag_supported(permission);
// macOS 27.3 gets a compact bar that says where Hex is added instead of a
// drag tile and its flight.
BOOL protected = activePermission == HexPermissionAccessibility && accessibilityProtected();
NSURL *settingsURL = [NSURL URLWithString:[NSString stringWithFormat:
@"x-apple.systempreferences:com.apple.settings.PrivacySecurity.extension?%@", pane]];
openSettingsPane(settingsURL);
guideSettingsURL = settingsURL;
// A development binary has no bundle to list, so it gets the pane alone.
if (![bundleURL.pathExtension.lowercaseString isEqualToString:@"app"]) {
return;
}
NSFont *instructionFont = [NSFont systemFontOfSize:13 weight:NSFontWeightMedium];
NSString *text;
NSSize panelSize;
if (protected) {
text = [NSString stringWithFormat:
@"Click the Privacy & Security notification, or add %@ with + in %@",
appName, listName];
CGFloat width = ceil([text sizeWithAttributes:@{ NSFontAttributeName: instructionFont }].width) + 36;
NSScreen *mainScreen = NSScreen.mainScreen;
if (mainScreen != nil) {
width = MIN(width, mainScreen.visibleFrame.size.width - 32);
}
panelSize = NSMakeSize(MAX(width, 320), 52);
} else if (draggable) {
text = [NSString stringWithFormat:@"↑ Drag %@ into the %@ list above", appName, listName];
panelSize = NSMakeSize(480, 116);
} else {
text = [NSString stringWithFormat:@"↑ Switch on %@ in the %@ list above", appName, listName];
panelSize = NSMakeSize(480, 60);
}
guidePanel = [[NSPanel alloc]
initWithContentRect:NSMakeRect(0, 0, panelSize.width, panelSize.height)
styleMask:NSWindowStyleMaskBorderless |
NSWindowStyleMaskNonactivatingPanel |
NSWindowStyleMaskFullSizeContentView
backing:NSBackingStoreBuffered
defer:NO];
guidePanel.floatingPanel = YES;
guidePanel.level = NSFloatingWindowLevel;
guidePanel.collectionBehavior = NSWindowCollectionBehaviorCanJoinAllSpaces |
NSWindowCollectionBehaviorFullScreenAuxiliary;
guidePanel.opaque = NO;
guidePanel.backgroundColor = NSColor.clearColor;
guidePanel.hasShadow = YES;
guidePanel.hidesOnDeactivate = NO;
guidePanel.releasedWhenClosed = NO;
NSView *content = [[NSView alloc] initWithFrame:NSMakeRect(0, 0, panelSize.width, panelSize.height)];
content.wantsLayer = YES;
content.layer.backgroundColor = NSColor.controlBackgroundColor.CGColor;
content.layer.cornerRadius = protected ? 14 : 20;
content.layer.borderWidth = 1;
content.layer.borderColor = [NSColor colorWithWhite:0 alpha:0.10].CGColor;
NSTextField *instruction = [NSTextField labelWithString:text];
instruction.frame = protected
? NSMakeRect(18, (panelSize.height - 24) / 2, panelSize.width - 36, 24)
: NSMakeRect(18, draggable ? 73 : 18, panelSize.width - 36, 24);
instruction.font = instructionFont;
instruction.textColor = NSColor.labelColor;
[content addSubview:instruction];
if (draggable) {
HexDragView *dragView = [[HexDragView alloc]
initWithFrame:NSMakeRect(18, 17, panelSize.width - 36, 44)
bundleURL:bundleURL];
[content addSubview:dragView];
guideTile = dragView;
}
guidePanel.contentView = content;
if (draggable && fly) {
guideTile.hidden = YES;
guidePanel.alphaValue = 0;
beginFlight(click, bundleURL, guideTile.frame.size);
}
guideTimer = [NSTimer scheduledTimerWithTimeInterval:0.12
repeats:YES
block:^(NSTimer *timer) {
(void)timer;
updateGuidePosition();
}];
updateGuidePosition();
}