Skip to content
Source
Sign inSign up
samwillis/jerry
Open History to see the last commit

DesktopAccess.swift

244 lines15.4 KB

1import AppKit
2import CoreGraphics
3@preconcurrency import ApplicationServices
4​
5extension Notification.Name {
6 static let desktopAccessChanged = Notification.Name("JerryDesktopAccessChanged")
7}
8​
9/// Reads macOS grants rather than assuming a saved preference is permission.
10/// Reading status never prompts or changes a grant.
11@MainActor
12final class DesktopAccess {
13 enum Permission: String, CaseIterable {
14 case accessibility, screenRecording
15 var title: String {
16 if self == .screenRecording { return "Screen Recording" }
17 if #available(macOS 27.0, *) { return "Device Control and Data Access" }
18 return "Accessibility"
19 }
20 var pane: String { self == .accessibility ? "Privacy_Accessibility" : "Privacy_ScreenCapture" }
21 }
22 struct Snapshot: Equatable {
23 var accessibility: Bool
24 var screenRecording: Bool
25 func allows(_ permission: Permission) -> Bool { permission == .accessibility ? accessibility : screenRecording }
26 }
27 static let shared = DesktopAccess()
28 private(set) var snapshot = Snapshot(accessibility: false, screenRecording: false)
29 private var timer: Timer?
30 private var observer: NSObjectProtocol?
31 private var setup: DesktopAccessController?
32 private var requested: Set<Permission> = []
33 private var screenCaptureRejected = false
34​
35 static func needed(for snapshot: Snapshot, defaults: UserDefaults = .standard) -> [Permission] {
36 let clicksUsed = defaults.bool(forKey: "desktopAccessibilityRequested") || defaults.bool(forKey: "desktopAccessibilityGranted")
37 || !(defaults.string(forKey: "agentModelID") ?? "").isEmpty
38 let imagesUsed = defaults.bool(forKey: "exploreInsideWindows") || defaults.bool(forKey: "agentShareImages")
39 return Permission.allCases.filter {
40 !snapshot.allows($0) && ($0 == .accessibility ? clicksUsed : imagesUsed)
41 }
42 }
43 func start() {
44 refresh()
45 guard timer == nil else { return }
46 observer = NotificationCenter.default.addObserver(forName: NSApplication.didBecomeActiveNotification, object: nil, queue: .main) { [weak self] _ in
47 MainActor.assumeIsolated { self?.refresh() }
48 }
49 timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true) { [weak self] _ in
50 MainActor.assumeIsolated {
51 guard let self, self.setup?.window?.isVisible == true || NSApp.isActive else { return }
52 self.refresh()
53 }
54 }
55 }
56 func stop() {
57 timer?.invalidate(); timer = nil
58 if let observer { NotificationCenter.default.removeObserver(observer) }; observer = nil
59 setup?.close(); setup = nil
60 }
61 func refresh() {
62 let next = Snapshot(accessibility: AXIsProcessTrusted(), screenRecording: CGPreflightScreenCaptureAccess() && !screenCaptureRejected)
63 if next.accessibility, !UserDefaults.standard.bool(forKey: "desktopAccessibilityGranted") { UserDefaults.standard.set(true, forKey: "desktopAccessibilityGranted") }
64 let changed = next != snapshot
65 snapshot = next
66 setup?.refresh()
67 if changed { NotificationCenter.default.post(name: .desktopAccessChanged, object: self) }
68 }
69 func captureRejected() {
70 guard !screenCaptureRejected else { return }
71 screenCaptureRejected = true; refresh()
72 if setup?.window?.isVisible != true { present(.screenRecording, openSettings: false) }
73 }
74 func captureStarted() {
75 guard screenCaptureRejected else { return }
76 screenCaptureRejected = false; refresh()
77 }
78 func present(_ permission: Permission, openSettings: Bool = true) {
79 refresh()
80 if setup?.permission != permission {
81 let previousFrame = setup?.window?.isVisible == true ? setup?.window?.frame : nil
82 setup?.close(); setup = DesktopAccessController(permission: permission)
83 if let previousFrame { setup?.preservePosition(from: previousFrame) }
84 }
85 setup?.positionBesideSettings()
86 setup?.window?.orderFront(nil)
87 if openSettings { open(permission) }
88 else if NSWorkspace.shared.frontmostApplication?.bundleIdentifier != "com.apple.systempreferences" {
89 NSApp.activate(ignoringOtherApps: true); setup?.window?.makeKeyAndOrderFront(nil)
90 }
91 }
92 func open(_ permission: Permission) {
93 if permission == .accessibility { UserDefaults.standard.set(true, forKey: "desktopAccessibilityRequested") }
94 if !snapshot.allows(permission), requested.insert(permission).inserted {
95 if permission == .accessibility {
96 _ = AXIsProcessTrustedWithOptions([kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true] as CFDictionary)
97 } else { _ = CGRequestScreenCaptureAccess() }
98 }
99 if let url = URL(string: "x-apple.systempreferences:com.apple.preference.security?" + permission.pane) { NSWorkspace.shared.open(url) }
100 // Let Settings finish opening before one placement attempt. Permission
101 // polling must never move windows or compete with a user dragging them.
102 let guide = setup
103 DispatchQueue.main.asyncAfter(deadline: .now() + 0.6) { [weak guide] in guide?.positionBesideSettings() }
104 }
105​
106 static func setupFrame(size: CGSize, beside settings: CGRect, in visible: CGRect) -> CGRect? {
107 guard size.width <= visible.width, size.height <= visible.height else { return nil }
108 let y = max(visible.minY, min(visible.maxY - size.height, settings.maxY - size.height))
109 let candidates = [
110 CGRect(x: settings.maxX + 12, y: y, width: size.width, height: size.height),
111 CGRect(x: settings.minX - size.width - 12, y: y, width: size.width, height: size.height)
112 ]
113 // If neither side has room, leave the normal-level window where it is.
114 // Never clamp it into the permission list merely to fit it on screen.
115 return candidates.first { visible.contains($0) && !$0.intersects(settings) }
116 }
118​
119/// A real file URL drag: the currently running bundle, never a stale app name.
120@MainActor
121final class JerryApplicationDragView: NSView, NSDraggingSource {
122 let applicationURL: URL
123 private let icon = NSImageView()
124 private var dragStart: NSEvent?
125 init(applicationURL: URL = Bundle.main.bundleURL) {
126 self.applicationURL = applicationURL
127 super.init(frame: .zero)
128 wantsLayer = true; layer?.cornerRadius = 10; layer?.backgroundColor = NotebookTheme.leather.withAlphaComponent(0.09).cgColor
129 icon.image = NSWorkspace.shared.icon(forFile: applicationURL.path); icon.imageScaling = .scaleProportionallyUpOrDown
130 icon.frame = .init(x: 12, y: 12, width: 64, height: 64); addSubview(icon)
131 let name = NSTextField(labelWithString: "Jerry.app"); name.font = NotebookTheme.font(16, weight: .semibold); name.textColor = NotebookTheme.ink
132 name.frame = .init(x: 90, y: 46, width: 205, height: 24); addSubview(name)
133 let hint = NSTextField(labelWithString: "Drag into the permission list"); hint.font = .systemFont(ofSize: 11); hint.textColor = NotebookTheme.faded
134 hint.frame = .init(x: 90, y: 23, width: 215, height: 20); addSubview(hint)
135 toolTip = applicationURL.path
136 setAccessibilityElement(true); setAccessibilityRole(.image); setAccessibilityLabel("Jerry application — drag into System Settings")
137 heightAnchor.constraint(equalToConstant: 88).isActive = true
138 }
139 required init?(coder: NSCoder) { fatalError("Use init(applicationURL:)") }
140 override var mouseDownCanMoveWindow: Bool { false }
141 override func hitTest(_ point: NSPoint) -> NSView? { super.hitTest(point) == nil ? nil : self }
142 override func mouseDown(with event: NSEvent) { dragStart = event }
143 override func mouseUp(with event: NSEvent) { dragStart = nil }
144 override func mouseDragged(with event: NSEvent) {
145 guard let start = dragStart, hypot(event.locationInWindow.x - start.locationInWindow.x, event.locationInWindow.y - start.locationInWindow.y) >= 3 else { return }
146 dragStart = nil
147 let item = NSDraggingItem(pasteboardWriter: applicationURL as NSURL)
148 item.setDraggingFrame(icon.frame, contents: icon.image)
149 beginDraggingSession(with: [item], event: start, source: self)
150 }
151 func draggingSession(_ session: NSDraggingSession, sourceOperationMaskFor context: NSDraggingContext) -> NSDragOperation { [.copy, .link, .generic] }
153​
154@MainActor
155private final class DesktopAccessController: NSWindowController, NSWindowDelegate {
156 let permission: DesktopAccess.Permission
157 private let status = NSTextField(wrappingLabelWithString: "")
158 private let done = NSButton(title: "Not now", target: nil, action: nil)
159 private var next: DesktopAccess.Permission?
160 private var placed = false
161 private var positioning = false
162 init(permission: DesktopAccess.Permission) {
163 self.permission = permission
164 let window = NotebookWindow(contentRect: .init(x: 0, y: 0, width: 380, height: 510), styleMask: [.titled, .closable, .miniaturizable, .fullSizeContentView], backing: .buffered, defer: false)
165 window.title = "Jerry — " + permission.title; window.isReleasedWhenClosed = false; window.level = .normal
166 window.hidesOnDeactivate = false; window.collectionBehavior = [.canJoinAllSpaces, .fullScreenAuxiliary]
167 super.init(window: window)
168 let root = NotebookTheme.install(on: window, title: "Access")
169 let body = NSStackView(); body.orientation = .vertical; body.alignment = .leading; body.spacing = 14; body.translatesAutoresizingMaskIntoConstraints = false; root.addSubview(body)
170 NSLayoutConstraint.activate([body.leadingAnchor.constraint(equalTo: root.leadingAnchor, constant: 22), body.trailingAnchor.constraint(equalTo: root.trailingAnchor, constant: -22), body.topAnchor.constraint(equalTo: root.topAnchor, constant: 14)])
171 func text(_ value: String, size: CGFloat = 12) -> NSTextField {
172 let field = NSTextField(wrappingLabelWithString: value); field.font = NotebookTheme.font(size); field.textColor = NotebookTheme.ink; field.preferredMaxLayoutWidth = 322; return field
173 }
174 func button(_ title: String, _ action: Selector) -> NSButton {
175 let button = NSButton(title: title, target: self, action: action); NotebookTheme.style(button); return button
176 }
177 body.addArrangedSubview(text(permission == .accessibility ? "Let Jerry use your controls" : "Let Jerry see window ledges", size: 20))
178 body.addArrangedSubview(text(permission == .accessibility ? "Accessibility lets Jerry read controls and press buttons in other apps." : "Screen Recording lets Jerry find ledges inside windows. AI image sharing stays a separate choice."))
179 body.addArrangedSubview(button("Open " + permission.title + "…", #selector(openSettings)))
180 body.addArrangedSubview(text("Drag Jerry into the list, then turn on his switch. If there’s no drop target, use + to add this app."))
181 body.addArrangedSubview(JerryApplicationDragView())
182 body.addArrangedSubview(button("Show this app in Finder", #selector(showInFinder)))
183 body.addArrangedSubview(status)
184 body.addArrangedSubview(text("Already listed but still blocked? Remove the old entry from this permission list and add this copy of Jerry."))
185 let actions = NSStackView(); actions.spacing = 8
186 actions.addArrangedSubview(button("Check again", #selector(checkAgain)))
187 actions.addArrangedSubview(button("Restart Jerry", #selector(restart)))
188 done.target = self; done.action = #selector(finish); actions.addArrangedSubview(done); body.addArrangedSubview(actions)
189 body.addArrangedSubview(text("If macOS asks you to quit and reopen, restart Jerry after enabling access."))
190 for view in body.arrangedSubviews { view.widthAnchor.constraint(equalToConstant: 322).isActive = true }
191 window.contentView?.layoutSubtreeIfNeeded()
192 window.setContentSize(.init(width: 380, height: max(510, body.fittingSize.height + 76)))
193 window.center(); window.delegate = self; shouldCascadeWindows = false; refresh()
194 }
195 required init?(coder: NSCoder) { fatalError("Use init(permission:)") }
196 func refresh() {
197 let access = DesktopAccess.shared.snapshot
198 let allowed = access.allows(permission)
199 status.stringValue = allowed ? "✓ macOS allows this copy of Jerry." : "Waiting for macOS to allow access…"
200 status.textColor = allowed ? NotebookTheme.ink : NotebookTheme.rust; status.font = .systemFont(ofSize: 12, weight: .medium)
201 next = allowed ? DesktopAccess.needed(for: access).first : nil
202 done.title = next.map { _ in "Next permission…" } ?? (allowed ? "Done" : "Not now"); NotebookTheme.style(done, primary: allowed)
203 }
204 func preservePosition(from frame: CGRect) {
205 positioning = true
206 window?.setFrameTopLeftPoint(.init(x: frame.minX, y: frame.maxY))
207 positioning = false; placed = true
208 }
209 func windowDidMove(_ notification: Notification) {
210 if !positioning { placed = true } // Respect a manually positioned guide.
211 }
212 func positionBesideSettings() {
213 guard !placed, let window,
214 let pid = NSRunningApplication.runningApplications(withBundleIdentifier: "com.apple.systempreferences").first?.processIdentifier else { return }
215 let entries = CGWindowListCopyWindowInfo([.optionOnScreenOnly, .excludeDesktopElements], kCGNullWindowID) as? [[String: Any]] ?? []
216 let settingsFrames = entries.compactMap { entry -> CGRect? in
217 guard (entry[kCGWindowOwnerPID as String] as? Int32) == pid,
218 (entry[kCGWindowLayer as String] as? Int) == 0,
219 let dictionary = entry[kCGWindowBounds as String] as? [String: Any],
220 let rect = CGRect(dictionaryRepresentation: dictionary as CFDictionary),
221 rect.width >= 400, rect.height >= 300 else { return nil }
222 return CGRect(x: rect.minX, y: (NSScreen.screens.first?.frame.maxY ?? 0) - rect.maxY, width: rect.width, height: rect.height)
223 }
224 guard let settings = settingsFrames.max(by: { $0.width * $0.height < $1.width * $1.height }),
225 let screen = NSScreen.screens.max(by: { lhs, rhs in
226 let a = lhs.frame.intersection(settings), b = rhs.frame.intersection(settings)
227 return (a.isNull ? 0 : a.width * a.height) < (b.isNull ? 0 : b.width * b.height)
228 }) else { return }
229 placed = true
230 guard let frame = DesktopAccess.setupFrame(size: window.frame.size, beside: settings, in: screen.visibleFrame) else { return }
231 positioning = true; window.setFrameOrigin(frame.origin); positioning = false
232 }
233 @objc private func openSettings() { DesktopAccess.shared.open(permission) }
234 @objc private func showInFinder() { NSWorkspace.shared.activateFileViewerSelecting([Bundle.main.bundleURL]) }
235 @objc private func checkAgain() { DesktopAccess.shared.refresh() }
236 @objc private func finish() { if let next { DesktopAccess.shared.present(next) } else { close() } }
237 @objc private func restart() {
238 let task = Process(); task.executableURL = URL(fileURLWithPath: "/bin/sh")
239 task.arguments = ["-c", "sleep 1; /usr/bin/open \"$1\"", "jerry-restart", Bundle.main.bundleURL.path]
240 task.standardOutput = FileHandle.nullDevice; task.standardError = FileHandle.nullDevice
241 do { try task.run(); NSApp.terminate(nil) }
242 catch { status.stringValue = "Couldn’t restart. Quit Jerry and open him again." }
243 }