Something went wrong. Try again.
An auto tiler for macOS
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385import AppKitimport ApplicationServicesimport CoreGraphicsimport Darwinimport Foundationimport ParcelPlatformimport RealityDriverSupport
final class DriverPipeServer { private var workers: [Int32: DriverAppThread] = [:] private var quitting = false private let fence = DriverInputFence() private var fenceStarted = false private var registrations: [Int32: Set<UInt32>] = [:] private var inputReceipts: [DriverInputReceipt] = []
func run(input: FileHandle = .standardInput, output: FileHandle = .standardOutput) throws { precondition(!Thread.isMainThread) var operationError: (any Error)? do { try serve(input: input, output: output) } catch { operationError = error } var failures: [String] = [] do { try DriverInput.balance.release() } catch { failures.append("Key teardown failed: \(error)") } for worker in workers.values { worker.shutdown() } if fenceStarted { do { try fence.stop() } catch { failures.append("Input fence teardown failed: \(error)") } } if !failures.isEmpty { throw DriverError( "Safety stop: \(failures.joined(separator: "; ")); operation: \(String(describing: operationError))") } if let operationError { throw operationError } }
private func serve(input: FileHandle, output: FileHandle) throws { var framer = DriverLineFramer() var buffer = [UInt8](repeating: 0, count: 4096) while true { try DriverInput.balance.requireRunning() var descriptor = pollfd(fd: input.fileDescriptor, events: Int16(POLLIN), revents: 0) let ready = Darwin.poll(&descriptor, 1, 100) if ready == 0 { continue } if ready < 0 { if errno == EINTR { continue } throw DriverError("Request pipe poll failed: \(errno)") } let count = Darwin.read(input.fileDescriptor, &buffer, buffer.count) if count == 0 { break } if count < 0 { if errno == EINTR { continue } throw DriverError("Request pipe read failed: \(errno)") } for line in framer.append(Data(buffer.prefix(count))) { try output.write(contentsOf: DriverWire.encodeResponse(response(for: line))) } if quitting { return } } if let tail = framer.finish() { try output.write(contentsOf: DriverWire.encodeResponse(response(for: tail))) } }
private func response(for line: DriverLine) -> DriverResponse { let data: Data switch line { case .rejected(let prefix, let reason): return DriverWire.failure(for: prefix, error: DriverError(reason)) case .request(let request): data = request } let request: DriverRequest do { request = try DriverWire.decodeRequest(data) } catch { return DriverWire.failure(for: data, error: error) } inputReceipts = [] do { guard !quitting else { throw DriverError("Driver is quitting") } return try execute(request) } catch { let operationError = error do { try DriverInput.balance.release() } catch { return DriverResponse( id: request.id, error: "Safety stop: \(operationError); key cleanup failed: \(error)", input: inputReceipts) } return DriverResponse(id: request.id, error: String(describing: operationError), input: inputReceipts) } }
private func execute(_ request: DriverRequest) throws -> DriverResponse { let id = request.id switch request.command { case .preflight: return DriverResponse( id: id, preflight: DriverPreflight( axTrusted: AXIsProcessTrusted(), postEventAccess: CGPreflightPostEventAccess(), screenRecording: CGPreflightScreenCaptureAccess(), processID: getpid(), parentProcessID: getppid())) case .inputState: return DriverResponse(id: id, inputState: DriverInputState.capture()) case .releaseOwnedKeys: try DriverInput.balance.release() return DriverResponse(id: id, inputState: DriverInputState.capture()) case .recoverKey(let pid, let windowID, let key): let target = try inputTarget() guard target == DriverInputTarget(pid: pid, windowID: windowID, fixture: true) else { throw DriverError("Safety stop: recovery requires the exact frontmost registered fixture") } inputReceipts = [DriverInputReceipt(target: target, outcome: "attempted recovery key-up", virtualKey: key)] try DriverKeyBalance.recover(key: key, target: target) inputReceipts = [ DriverInputReceipt( target: target, outcome: "recovery key-up; combined state verified", virtualKey: key, delivery: .fixture) ] return DriverResponse(id: id, input: inputReceipts, inputState: DriverInputState.capture()) case .register(let pid, let windowID): try requireAX() try DriverWindowMetadata.requireOwner(pid: pid, windowID: windowID) let worker = workers[pid] ?? DriverAppThread(pid: pid) workers[pid] = worker let warnings = try worker.perform { try $0.register(windowID: windowID) } registrations[pid, default: []].insert(windowID) DriverInput.balance.register(pid: pid, windowID: windowID) return DriverResponse(id: id, identificationWarnings: warnings) case .standardWindows(let pid, let candidates): try requireAX() guard pid != getpid() else { throw DriverError("The driver cannot identify its own windows") } let worker = workers[pid] ?? DriverAppThread(pid: pid) workers[pid] = worker let result = try worker.perform { try $0.standardWindowIDs(candidates: Set(candidates)) } return DriverResponse( id: id, identificationWarnings: result.warnings, windowIDs: result.ids, identifiedWindowIDs: result.identified) case .key(let key, let flags, let expectation): let target = try inputTarget() inputReceipts = [DriverInputReceipt(target: target, outcome: "attempted", virtualKey: key)] try startFence() let tag = try fence.arm(target: target, expectation: expectation, virtualKey: key) try requireVoiceOverExpectation(expectation, flags: flags) try DriverInput.key( virtualKey: key, flags: flags, tag: tag, target: target, requireTarget: { guard try self.inputTarget() == target else { throw DriverError("Safety stop: shortcut target changed; input withheld") } }, confirmDelivery: { let result = try self.fence.confirm(tag: tag) self.inputReceipts = [ DriverInputReceipt( target: target, outcome: result.outcome, virtualKey: key, delivery: result.delivery) ] }) return DriverResponse(id: id, input: inputReceipts) case .heldKeys(let first, let second, let flags, let holdMilliseconds, let secondExpectation): let modifierTarget = try inputTarget() try requireVoiceOverExpectation(secondExpectation, flags: flags) try startFence() var target: DriverInputTarget? var keyIndex = 0 let keys = [first, second] let expectations: [DriverKeyExpectation] = [.shortcut, secondExpectation] try DriverInput.heldKeys( first: first, second: second, flags: flags, holdMilliseconds: holdMilliseconds, modifierTarget: modifierTarget, requireModifierTarget: { guard try self.inputTarget() == modifierTarget else { throw DriverError("Safety stop: modifier target changed; input withheld") } }, beforeKey: { let current = try self.inputTarget() target = current self.inputReceipts.append( DriverInputReceipt(target: current, outcome: "attempted", virtualKey: keys[keyIndex])) let tag = try self.fence.arm( target: current, expectation: expectations[keyIndex], virtualKey: keys[keyIndex]) return (tag, current) }, afterKey: { tag in guard let target else { preconditionFailure("Held key has no target") } let result = try self.fence.confirm(tag: tag) self.inputReceipts[keyIndex] = DriverInputReceipt( target: target, outcome: result.outcome, virtualKey: keys[keyIndex], delivery: result.delivery) keyIndex += 1 }) return DriverResponse(id: id, input: inputReceipts) case .minimize(let pid, let windowID): try registeredWorker(pid: pid).perform { try $0.minimize(windowID: windowID) } case .drag(let pid, let windowID, let fromX, let fromY, let toX, let toY, let flags): let worker = try registeredWorker(pid: pid) let frame = try worker.perform { try $0.window(windowID).frame } let from = CGPoint(x: fromX, y: fromY) guard frame.contains(from) else { throw DriverError("Drag must start inside its registered window") } let target = try inputTarget(dragWindow: windowID) guard target.pid == pid else { throw DriverError("Safety stop: drag PID is not frontmost") } inputReceipts = [DriverInputReceipt(target: target, outcome: "attempted drag")] let frames = try DriverInput.drag( pid: pid, windowID: windowID, from: from, to: CGPoint(x: toX, y: toY), flags: flags, target: target, requirePickup: { try worker.perform { try $0.requirePickup(windowID: windowID, point: from) } }, requireTarget: { guard try self.inputTarget(dragWindow: windowID) == target else { throw DriverError("Safety stop: drag target changed") } }) return DriverResponse( id: id, dragFrames: frames, input: [ DriverInputReceipt( target: target, outcome: "native AX pickup ownership verified; drag delivered; CG readbacks retained; exchange must be checked" ) ]) case .move(let pid, let windowID, let x, let y, let width, let height): let worker = try registeredWorker(pid: pid) let target = CGRect(x: x, y: y, width: width, height: height) try DriverDisplays.requireReachableFrame(target) let preserve = try DriverMainThread.perform { VoiceOverStatus.isRunning || NSWorkspace.shared.isSwitchControlEnabled } let frame = try worker.perform { try $0.move(windowID: windowID, target: target, preserveEnhancedUI: preserve) } return DriverResponse(id: id, frame: frame) case .focus(let pid, let windowID): let worker = try registeredWorker(pid: pid) try worker.perform { _ = try $0.window(windowID) } try DriverMainThread.perform { guard let app = NSRunningApplication(processIdentifier: pid), app.activate() else { throw DriverError("Could not activate PID \(pid)") } } try worker.perform { try $0.focus(windowID: windowID) } case .close(let pid, let windowID): try registeredWorker(pid: pid).perform { try $0.close(windowID: windowID) } case .increments(let pid, let windowID): let value = try registeredWorker(pid: pid).perform { try $0.increments(windowID: windowID) } return DriverResponse(id: id, increments: value) case .pressTourTidy(let pid, let windowID, let launchDate, let control): return try pressTour(id: id, pid: pid, windowID: windowID, launchDate: launchDate, control: control) case .clickTourTidy(let pid, let windowID, let launchDate): return try pressTour( id: id, pid: pid, windowID: windowID, launchDate: launchDate, control: .tidy, method: .mouse) case .captureTour(let pid, let windowID, let launchDate, let directory, let optedIn): try Self.requireParcelTourLaunch(pid: pid, launchDate: launchDate) try DriverWindowMetadata.requireVisibleOwner(pid: pid, windowID: windowID) let capture = try DriverScreenCapture.capture( directory: directory, optedIn: optedIn, windowID: windowID) try Self.requireParcelTourLaunch(pid: pid, launchDate: launchDate) try DriverWindowMetadata.requireVisibleOwner(pid: pid, windowID: windowID) return DriverResponse(id: id, captures: [capture]) case .capture(let directory, let optedIn): return DriverResponse( id: id, captures: [try DriverScreenCapture.capture(directory: directory, optedIn: optedIn)]) case .missionControlChords: let chords: [DriverChord] if let domain = UserDefaults.standard.persistentDomain(forName: "com.apple.symbolichotkeys") { let data = try PropertyListSerialization.data(fromPropertyList: domain, format: .binary, options: 0) chords = try DriverSymbolicChords.parse(data) } else { chords = [] } return DriverResponse(id: id, chords: chords) case .captureDesktop(let directory, let optedIn): return DriverResponse( id: id, captures: try DriverDesktopCapture.capture(directory: directory, optedIn: optedIn)) case .missionControlSnapshot: try requireAX() let pid = try DriverMainThread.perform { guard let app = NSRunningApplication.runningApplications(withBundleIdentifier: "com.apple.dock").first else { throw DriverError("Dock is not running") } return app.processIdentifier } let worker = workers[pid] ?? DriverAppThread(pid: pid) workers[pid] = worker let nodes = try worker.perform { try $0.element.missionControlSnapshot() } return DriverResponse(id: id, nodes: nodes) case .quit: try DriverInput.balance.release() quitting = true } return DriverResponse(id: id) }
private func pressTour( id: UInt64, pid: Int32, windowID: UInt32, launchDate: Double, control: DriverTourControl, method: DriverTourInputMethod = .ax ) throws -> DriverResponse { try requireAX() try Self.requireParcelTourLaunch(pid: pid, launchDate: launchDate) let target = DriverInputTarget(pid: pid, windowID: windowID, panel: true) inputReceipts = [ DriverInputReceipt( target: target, outcome: "attempted external \(control.rawValue) \(method.rawValue) delivery") ] let worker = workers[pid] ?? DriverAppThread(pid: pid) workers[pid] = worker let (receipt, warnings) = try worker.perform { let warnings = try $0.register(windowID: windowID) let receipt = try $0.pressTourTidy( windowID: windowID, launchDate: launchDate, control: control, method: method ) { try Self.requireParcelTourLaunch(pid: pid, launchDate: launchDate) } return (receipt, warnings) } inputReceipts = [ DriverInputReceipt( target: target, outcome: "external enabled \(control.rawValue) AXButton \(method.rawValue) acknowledged; observed effect required", delivery: .panel) ] return DriverResponse(id: id, identificationWarnings: warnings, input: inputReceipts, tourPress: receipt) }
private static func requireParcelTourLaunch(pid: Int32, launchDate: Double) throws { try DriverConsoleState.requireCurrent() try DriverMainThread.perform { guard let host = NSRunningApplication(processIdentifier: getppid()), !host.isTerminated, host.bundleIdentifier == "dev.vinnymac.parcel", let hostURL = host.bundleURL, let app = NSRunningApplication(processIdentifier: pid), !app.isTerminated, app.bundleIdentifier == "dev.vinnymac.parcel", let appURL = app.bundleURL, appURL.resolvingSymlinksInPath() == hostURL.resolvingSymlinksInPath(), app.launchDate?.timeIntervalSince1970 == launchDate else { throw DriverError("Safety stop: Tidy press requires the exact owned Parcel launch") } } }
private func requireVoiceOverExpectation(_ expectation: DriverKeyExpectation, flags: UInt64) throws { guard expectation == .voiceOverShortcut else { return } guard flags & 0x000C_0000 == 0x000C_0000, try DriverMainThread.perform({ VoiceOverStatus.isRunning }) else { throw DriverError("Safety stop: VoiceOver shortcut expectation requires live VoiceOver and Control Option") } }
private func startFence() throws { if !fenceStarted { try fence.start() fenceStarted = true } }
private func inputTarget(dragWindow: UInt32? = nil) throws -> DriverInputTarget { try requireAX() try DriverConsoleState.requireCurrent() let identity = try DriverMainThread.perform { guard let app = NSWorkspace.shared.frontmostApplication else { throw DriverError("Safety stop: no frontmost app; input withheld") } let host = NSRunningApplication(processIdentifier: getppid()) let parcel = app.bundleIdentifier == "dev.vinnymac.parcel" && app.bundleURL?.resolvingSymlinksInPath() == host?.bundleURL?.resolvingSymlinksInPath() return (app.processIdentifier, app.executableURL?.lastPathComponent == "FixtureApp", parcel) } guard identity.2 || registrations[identity.0]?.isEmpty == false else { throw DriverError("Safety stop: frontmost PID \(identity.0) has no owned test windows; input withheld") } let worker = workers[identity.0] ?? DriverAppThread(pid: identity.0) workers[identity.0] = worker let target = try worker.perform { try $0.inputTarget(fixture: identity.1, parcel: identity.2) } try target.requireOwned(registered: registrations[identity.0] ?? [], dragWindow: dragWindow) let current = try DriverMainThread.perform { NSWorkspace.shared.frontmostApplication?.processIdentifier } guard current == target.pid else { throw DriverError("Safety stop: foreground changed during ownership check") } return target }
private func registeredWorker(pid: Int32) throws -> DriverAppThread { try requireAX() guard let worker = workers[pid] else { throw DriverError("No registered windows for PID \(pid)") } return worker }
private func requireAX() throws { guard AXIsProcessTrusted() else { throw DriverError("Accessibility is required for the signed driver") } }}