Something went wrong. Try again.
An auto tiler for macOS
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207import AppKitimport Darwinimport Foundation
struct RealityFixtureReply: Codable, Sendable { struct AuxiliaryWindow: Codable, Sendable { let kind: String let number: UInt32 let parentNumber: UInt32? let frameWrites: Int let resizeWrites: Int } struct Window: Codable, Sendable { let number: UInt32 let clampedWrites: Int let adjustedWrites: Int } struct Key: Codable, Sendable { let key: UInt16 let down: Bool let flags: UInt64 let windowID: UInt32 let timestamp: Double }
let id: String let pid: Int32 let error: String? let overflow: Bool? let inputEvents: [Key]? var keyWindowNumber: UInt32? var windows: [Window]? var auxiliaryWindows: [AuxiliaryWindow]?
func received(_ key: UInt16, windowID: UInt32) throws -> Bool { guard error == nil, overflow != true, let inputEvents else { throw RealityError("Fixture keyboard recorder failed or omitted its receipt") } let events = inputEvents.filter { $0.key == key && $0.windowID == windowID } return events.contains(where: \.down) && events.contains { !$0.down } }}
@MainActorfinal class RealityFixture { let process = Process() private let input = Pipe() private let output = Pipe() private var pending = Data()
init(executable: URL, token: String) throws { process.executableURL = executable process.arguments = ["--windows", "1", "--title", token] process.standardInput = input process.standardOutput = output try process.run() }
func ready() async throws { let reply = try await readReply() guard reply.id == "ready", reply.pid == process.processIdentifier, reply.error == nil else { throw RealityError("Fixture returned invalid readiness") } }
func control(_ action: String) async throws -> RealityFixtureReply { let id = UUID().uuidString return try await send(["id": id, "action": action], id: id) }
func setTitle(_ title: String) async throws { struct Request: Encodable { let id: String let action = "title" let window = 1 let title: String } let id = UUID().uuidString _ = try await send(Request(id: id, title: title), id: id) }
func configureTidy(clampHeight: Double? = nil, adjustNextFrame: Bool = false) async throws { struct Request: Encodable { let id: String let action = "configure" let window = 1 let clampWidth: Double? let clampHeight: Double? let adjustNextFrame: Bool } let id = UUID().uuidString _ = try await send( Request( id: id, clampWidth: clampHeight == nil ? nil : 200, clampHeight: clampHeight, adjustNextFrame: adjustNextFrame), id: id) }
private func send(_ request: some Encodable, id: String) async throws -> RealityFixtureReply { var data = try JSONEncoder().encode(request) data.append(10) try input.fileHandleForWriting.write(contentsOf: data) let reply = try await readReply() guard reply.id == id, reply.pid == process.processIdentifier, reply.error == nil else { throw RealityError( "Fixture returned an invalid control acknowledgement: \(String(describing: reply.error))") } return reply }
struct StoppedAXReceipt: Codable, Sendable { let pid: Int32 let parentPID: Int32 let executable: String let state: UInt32 }
func stopAXReplies() async throws -> StoppedAXReceipt { _ = try kernelIdentity() guard kill(process.processIdentifier, SIGSTOP) == 0 else { throw RealityError("Cannot stop owned fixture AX replies: errno \(errno)") } let deadline = ContinuousClock.now.advanced(by: .milliseconds(500)) while ContinuousClock.now < deadline { let receipt = try kernelIdentity() if receipt.state == UInt32(SSTOP) { return receipt } try await Task.sleep(for: .milliseconds(10)) } throw RealityError("Owned fixture did not enter the kernel stopped state") }
func requireStoppedAXReplies() throws -> StoppedAXReceipt { let receipt = try kernelIdentity() guard receipt.state == UInt32(SSTOP) else { throw RealityError("Safety stop: fixture resumed AX replies during the first-run tour") } return receipt }
private func kernelIdentity() throws -> StoppedAXReceipt { guard process.isRunning, let executable = process.executableURL else { throw RealityError("Safety stop: fixture's retained child process is no longer live") } let pid = process.processIdentifier var info = proc_bsdinfo() let size = Int32(MemoryLayout<proc_bsdinfo>.size) var path = [UInt8](repeating: 0, count: 4 * Int(MAXPATHLEN)) guard proc_pidinfo(pid, PROC_PIDTBSDINFO, 0, &info, size) == size, proc_pidpath(pid, &path, UInt32(path.count)) > 0, info.pbi_pid == UInt32(pid), info.pbi_ppid == UInt32(getpid()) else { throw RealityError("Safety stop: fixture kernel child identity could not be verified") } let actual = String(decoding: path.prefix(while: { $0 != 0 }), as: UTF8.self) guard actual == executable.resolvingSymlinksInPath().path else { throw RealityError("Safety stop: fixture kernel executable differs from its retained launch") } return StoppedAXReceipt(pid: pid, parentPID: Int32(info.pbi_ppid), executable: actual, state: info.pbi_status) }
func discardOwnedChild() async throws { if process.isRunning { guard kill(process.processIdentifier, SIGKILL) == 0 else { throw RealityError("Cannot discard owned fixture launch: errno \(errno)") } let deadline = ContinuousClock.now.advanced(by: .seconds(5)) while process.isRunning, ContinuousClock.now < deadline { try await Task.sleep(for: .milliseconds(20)) } } guard !process.isRunning else { throw RealityError("Owned fixture launch survived discard") } }
func close() throws { guard !process.isRunning else { throw RealityError("Cannot close a live fixture's control channel") } try input.fileHandleForWriting.close() try input.fileHandleForReading.close() try output.fileHandleForWriting.close() try output.fileHandleForReading.close() }
private func readReply() async throws -> RealityFixtureReply { let deadline = ContinuousClock.now.advanced(by: .seconds(10)) while ContinuousClock.now < deadline { if let newline = pending.firstIndex(of: 10) { let line = Data(pending[..<newline]) pending.removeSubrange(...newline) return try JSONDecoder().decode(RealityFixtureReply.self, from: line) } var descriptor = pollfd(fd: output.fileHandleForReading.fileDescriptor, events: Int16(POLLIN), revents: 0) let result = poll(&descriptor, 1, 0) if result < 0 { if errno == EINTR { continue } throw RealityError("Polling fixture output failed: errno \(errno)") } if result > 0 { var bytes = [UInt8](repeating: 0, count: 4096) let count = Darwin.read(descriptor.fd, &bytes, bytes.count) guard count > 0 else { throw RealityError("Fixture closed its control output") } pending.append(contentsOf: bytes.prefix(count)) guard pending.count <= 1_048_576 else { throw RealityError("Fixture reply exceeded 1 MiB") } } else { guard process.isRunning else { throw RealityError("Fixture exited before its acknowledgement") } try await Task.sleep(for: .milliseconds(10)) } } throw RealityError("Timed out waiting for the fixture acknowledgement") }}