Ariver
2026-06-28 9ba7cd3b47fb91eaaa8d0c3df8b7286a89be1756
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import CoreGraphics
import Foundation
 
enum PostKeyError: Error, CustomStringConvertible {
    case unsupportedArguments([String])
    case eventCreationFailed
 
    var description: String {
        switch self {
        case .unsupportedArguments(let arguments):
            return "Unsupported post-round1-key arguments: \(arguments.joined(separator: " "))"
        case .eventCreationFailed:
            return "CGEvent creation failed."
        }
    }
}
 
struct KeySpec {
    let keyCode: CGKeyCode
    let flags: CGEventFlags
 
    static func parse(arguments: [String]) throws -> KeySpec {
        if arguments.contains("--option-tab") {
            return KeySpec(keyCode: 48, flags: .maskAlternate)
        }
        if arguments.contains("--escape") {
            return KeySpec(keyCode: 53, flags: [])
        }
        if arguments.contains("--command-option-escape") {
            return KeySpec(keyCode: 53, flags: [.maskCommand, .maskAlternate])
        }
 
        throw PostKeyError.unsupportedArguments(arguments)
    }
}
 
func post(_ spec: KeySpec, keyDown: Bool, source: CGEventSource?) throws {
    guard let event = CGEvent(keyboardEventSource: source, virtualKey: spec.keyCode, keyDown: keyDown) else {
        throw PostKeyError.eventCreationFailed
    }
 
    event.flags = keyDown ? spec.flags : []
    event.post(tap: .cghidEventTap)
}
 
do {
    let spec = try KeySpec.parse(arguments: Array(CommandLine.arguments.dropFirst()))
    let source = CGEventSource(stateID: .combinedSessionState)
    try post(spec, keyDown: true, source: source)
    usleep(80_000)
    try post(spec, keyDown: false, source: source)
} catch {
    fputs("post-round1-key failed: \(error)\n", stderr)
    exit(1)
}