import Foundation import AppKit import ScreenCaptureKit import CoreGraphics import Network final class Desktop: @unchecked Sendable { let lock = NSLock() var frame = Data() let width = 960 var height = 600 var bounds = CGDisplayBounds(CGMainDisplayID()) func capture() async throws { let content = try await SCShareableContent.excludingDesktopWindows(false, onScreenWindowsOnly: true) guard let display = content.displays.first(where: { $0.displayID == CGMainDisplayID() }) else { throw NSError(domain: "No display", code: 1) } height = Int(Double(width) * Double(display.height) / Double(display.width)) let filter = SCContentFilter(display: display, excludingWindows: []) let config = SCStreamConfiguration() config.width = width; config.height = height; config.showsCursor = true let image = try await SCScreenshotManager.captureImage(contentFilter: filter, configuration: config) var bytes = [UInt8](repeating: 0, count: width * height * 4) bytes.withUnsafeMutableBytes { raw in let ctx = CGContext(data: raw.baseAddress, width: width, height: height, bitsPerComponent: 8, bytesPerRow: width * 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue)! ctx.draw(image, in: CGRect(x: 0, y: 0, width: width, height: height)) } lock.withLock { frame = Data(bytes) } } func pixels() -> Data { lock.withLock { frame } } } func u16(_ n: Int) -> [UInt8] { [UInt8((n >> 8) & 255), UInt8(n & 255)] } func u32(_ n: Int) -> [UInt8] { [UInt8((n >> 24) & 255), UInt8((n >> 16) & 255), UInt8((n >> 8) & 255), UInt8(n & 255)] } final class Client: @unchecked Sendable { let connection: NWConnection let desktop: Desktop var endian = false, red = 16, green = 8, blue = 0 var buttons: UInt8 = 0 var flags: CGEventFlags = [] init(_ c: NWConnection, _ d: Desktop) { connection = c; desktop = d } func read(_ count: Int) async throws -> Data { var result = Data() while result.count < count { let part: Data = try await withCheckedThrowingContinuation { continuation in connection.receive(minimumIncompleteLength: 1, maximumLength: count - result.count) { data, _, complete, error in if let error { continuation.resume(throwing: error) } else if let data, !data.isEmpty { continuation.resume(returning: data) } else { continuation.resume(throwing: NSError(domain: "Disconnected", code: 1)) } } } result.append(part) } return result } func send(_ data: Data) async throws { try await withCheckedThrowingContinuation { (cont: CheckedContinuation) in connection.send(content: data, completion: .contentProcessed { error in if let error { cont.resume(throwing: error) } else { cont.resume() } }) } } func pointer(_ b: UInt8, _ x: Int, _ y: Int) { let p = CGPoint(x: desktop.bounds.minX + Double(x) * desktop.bounds.width / Double(desktop.width), y: desktop.bounds.minY + Double(y) * desktop.bounds.height / Double(desktop.height)) for (mask, button, down, up) in [(UInt8(1), CGMouseButton.left, CGEventType.leftMouseDown, CGEventType.leftMouseUp), (4, .right, .rightMouseDown, .rightMouseUp)] { if (buttons & mask) != (b & mask) { let event = CGEvent(mouseEventSource: nil, mouseType: (b & mask) != 0 ? down : up, mouseCursorPosition: p, mouseButton: button) event?.flags = flags; event?.post(tap: .cghidEventTap) } } let type: CGEventType = (b & 1) != 0 ? .leftMouseDragged : (b & 4) != 0 ? .rightMouseDragged : .mouseMoved let event = CGEvent(mouseEventSource: nil, mouseType: type, mouseCursorPosition: p, mouseButton: (b & 4) != 0 ? .right : .left) event?.flags = flags; event?.post(tap: .cghidEventTap) if (b & 8) != 0 || (b & 16) != 0 { CGEvent(scrollWheelEvent2Source: nil, units: .line, wheelCount: 1, wheel1: (b & 8) != 0 ? 3 : -3, wheel2: 0, wheel3: 0)?.post(tap: .cghidEventTap) } buttons = b } func key(_ symbol: UInt32, down: Bool) { let codes: [UInt32: CGKeyCode] = [0xff08:51, 0xff09:48, 0xff0d:36, 0xff1b:53, 0xffff:117, 0xff51:123, 0xff52:126, 0xff53:124, 0xff54:125, 0xffe1:56, 0xffe2:60, 0xffe3:59, 0xffe4:62, 0xffe9:58, 0xffea:61, 0xffeb:55, 0xffec:54] let modifiers: [UInt32: CGEventFlags] = [0xffe1:.maskShift, 0xffe2:.maskShift, 0xffe3:.maskControl, 0xffe4:.maskControl, 0xffe9:.maskAlternate, 0xffea:.maskAlternate, 0xffeb:.maskCommand, 0xffec:.maskCommand] if let modifier = modifiers[symbol] { if down { flags.insert(modifier) } else { flags.remove(modifier) } } guard let event = CGEvent(keyboardEventSource: nil, virtualKey: codes[symbol] ?? 0, keyDown: down) else { return } event.flags = flags if codes[symbol] == nil { let value = symbol >= 0x01000000 ? symbol & 0x00ffffff : symbol guard let scalar = UnicodeScalar(value), value >= 32 else { return } let chars = Array(String(scalar).utf16) chars.withUnsafeBufferPointer { event.keyboardSetUnicodeString(stringLength: chars.count, unicodeString: $0.baseAddress!) } } event.post(tap: .cghidEventTap) } func run() async { defer { connection.cancel() } do { try await send(Data("RFB 003.008\n".utf8)); _ = try await read(12) try await send(Data([1,1])); guard try await read(1)[0] == 1 else { return } try await send(Data([0,0,0,0])); _ = try await read(1) let name = Array("Temporary Mac desktop".utf8) try await send(Data(u16(desktop.width) + u16(desktop.height) + [32,24,0,1,0,255,0,255,0,255,16,8,0,0,0,0] + u32(name.count) + name)) while true { let type = try await read(1)[0] switch type { case 0: let p = [UInt8](try await read(19)); guard p[3] == 32 && p[6] == 1 && p[13] <= 24 && p[14] <= 24 && p[15] <= 24 else { return } endian = p[5] != 0; red = Int(p[13]); green = Int(p[14]); blue = Int(p[15]) case 2: let p = [UInt8](try await read(3)); let n = Int(p[1]) * 256 + Int(p[2]); guard n <= 256 else { return }; _ = try await read(n * 4) case 3: _ = try await read(9) let frame = desktop.pixels(); guard !frame.isEmpty else { return } var converted = [UInt8](repeating: 0, count: frame.count) frame.withUnsafeBytes { raw in let p = raw.bindMemory(to: UInt8.self) for i in stride(from: 0, to: frame.count, by: 4) { let v = UInt32(p[i+2]) << red | UInt32(p[i+1]) << green | UInt32(p[i]) << blue for j in 0..<4 { converted[i+j] = UInt8((v >> (endian ? (3-j)*8 : j*8)) & 255) } } } var update = Data([0,0,0,1]) update.append(contentsOf: u16(0)); update.append(contentsOf: u16(0)) update.append(contentsOf: u16(desktop.width)); update.append(contentsOf: u16(desktop.height)) update.append(contentsOf: [0,0,0,0]); update.append(contentsOf: converted) try await send(update) try await Task.sleep(nanoseconds: 350_000_000) case 4: let p = [UInt8](try await read(7)); let symbol = UInt32(p[3]) << 24 | UInt32(p[4]) << 16 | UInt32(p[5]) << 8 | UInt32(p[6]); key(symbol, down: p[0] != 0) case 5: let p = [UInt8](try await read(5)); pointer(p[0], Int(p[1])*256+Int(p[2]), Int(p[3])*256+Int(p[4])) case 6: let p = [UInt8](try await read(7)); let n = Int(p[3]) << 24 | Int(p[4]) << 16 | Int(p[5]) << 8 | Int(p[6]); guard n < 65536 else { return }; _ = try await read(n) default: return } } } catch { } } } let desktop = Desktop() let parameters = NWParameters.tcp parameters.requiredLocalEndpoint = .hostPort(host: "127.0.0.1", port: 5901) let listener = try NWListener(using: parameters) listener.newConnectionHandler = { connection in connection.start(queue: .global()) Task { await Client(connection, desktop).run() } } Task { do { try await desktop.capture() print("Desktop capture ready; \(desktop.width)x\(desktop.height)") fflush(stdout) listener.start(queue: .global()) while true { try await Task.sleep(nanoseconds: 350_000_000); try await desktop.capture() } } catch { print("Capture unavailable: \(error)"); exit(1) } } dispatchMain()