Open History to see the last commit
1import AppKit
2@preconcurrency import ApplicationServices
3
4/// A small hit area above the mouse-ignoring rendering layer. Never takes keyboard focus.
5@MainActor
6final class ExplorerInputPanel: NSPanel {
7 override var canBecomeKey: Bool { false }
8 override var canBecomeMain: Bool { false }
9}
10
11@MainActor
12final class ExplorerInputView: NSView {
13 var onBegin: ((CGPoint) -> Void)?
14 var onDrag: ((CGPoint) -> Void)?
15 var onEnd: (() -> Void)?
16 private var dragging = false
17
18 override var acceptsFirstResponder: Bool { false }
19 override var needsPanelToBecomeKey: Bool { false }
20 override var mouseDownCanMoveWindow: Bool { false }
21 override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true }
22
23 override init(frame frameRect: NSRect) {
24 super.init(frame: frameRect)
25 setAccessibilityElement(true)
26 setAccessibilityRole(.image)
27 setAccessibilityLabel("Explorer — drag to move")
28 toolTip = "Grab me and move me out of the way"
29 }
30
31 required init?(coder: NSCoder) { fatalError("Use init(frame:)") }
32
33 override func draw(_ dirtyRect: NSRect) {
34 // A near-transparent backing keeps the small panel hit-testable on macOS.
35 NSColor.black.withAlphaComponent(0.01).setFill()
36 bounds.fill()
37 }
38
39 override func resetCursorRects() { addCursorRect(bounds, cursor: .openHand) }
40
41 override func mouseDown(with event: NSEvent) {
42 guard event.type == .leftMouseDown else { return }
43 dragging = true
44 NSCursor.closedHand.push()
45 onBegin?(NSEvent.mouseLocation)
46 }
47
48 override func mouseDragged(with event: NSEvent) {
49 guard dragging else { return }
50 onDrag?(NSEvent.mouseLocation)
51 }
52
53 override func mouseUp(with event: NSEvent) {
54 guard dragging else { return }
55 onDrag?(NSEvent.mouseLocation)
56 cancelDrag()
57 }
58
59 func cancelDrag() {
60 guard dragging else { return }
61 dragging = false
62 NSCursor.pop()
63 onEnd?()
64 }
65}
66
67/// Invisible key target used only during manual control. No instruction window or global keyboard monitor.
68@MainActor
69final class ExplorerControlPanel: NSPanel {
70 override var canBecomeKey: Bool { true }
71 override var canBecomeMain: Bool { false }
72}
73
74@MainActor
75final class ExplorerKeyboardController: NSObject, NSWindowDelegate {
76 let panel: ExplorerControlPanel
77 private(set) var lastMessage = ""
78 private var monitor: Any?
79 private var held: Set<UInt16> = []
80 private var previousApp: NSRunningApplication?
81 private var lastExternalApp = NSWorkspace.shared.frontmostApplication
82 private var clickRestore: DispatchWorkItem?
83 private(set) var isPerformingClick = false
84 private var aiming = false
85 var onDirection: ((Double, Double) -> Void)?
86 var onCrouch: ((Bool) -> Void)?
87 var onLowPointer: ((Bool) -> Void)?
88 var onFastPace: ((Bool) -> Void)?
89 var onJump: (() -> Void)?
90 var onAimChanged: ((Bool) -> Void)?
91 var onAimDirection: ((Double, Double) -> Void)?
92 var onGrapple: (() -> Void)?
93 var onInteract: (() -> Void)?
94 var onPrompt: (() -> Void)?
95 var onStop: (() -> Void)?
96 private(set) var isControlling = false
97
98 override init() {
99 panel = ExplorerControlPanel(contentRect: .init(x: 0, y: 0, width: 1, height: 1), styleMask: [.borderless], backing: .buffered, defer: false)
100 super.init()
101 panel.title = "Explorer keyboard input"
102 panel.isOpaque = false; panel.backgroundColor = .clear; panel.hasShadow = false
103 panel.ignoresMouseEvents = true
104 panel.setAccessibilityElement(false)
105 panel.level = .floating
106 panel.isReleasedWhenClosed = false
107 panel.hidesOnDeactivate = false
108 panel.delegate = self
109 }
110
111 func start() {
112 guard !isControlling else { return }
113 recordFrontApp()
114 previousApp = lastExternalApp
115 isControlling = true
116 held.removeAll()
117 showMessage("The crosshair beside his hand is the click point. Hold C to crouch and lower the click point. Down steps off a ledge.")
118 if let screen = NSScreen.screens.first {
119 panel.setFrameTopLeftPoint(.init(x: screen.visibleFrame.minX + 12, y: screen.visibleFrame.maxY - 12))
120 }
121 monitor = NSEvent.addLocalMonitorForEvents(matching: [.keyDown, .keyUp, .flagsChanged]) { [weak self] event in
122 let consumed = MainActor.assumeIsolated { self?.handle(event) == nil }
123 return consumed ? nil : event
124 }
125 NSApp.activate(ignoringOtherApps: true)
126 panel.makeKeyAndOrderFront(nil)
127
128 }
129
130 func recordFrontApp() {
131 if let active = NSWorkspace.shared.frontmostApplication, active.processIdentifier != ProcessInfo.processInfo.processIdentifier {
132 lastExternalApp = active
133 }
134 }
135 func restoreExternalFocus() {
136 if lastExternalApp?.processIdentifier != ProcessInfo.processInfo.processIdentifier { lastExternalApp?.activate(options: []) }
137 }
138 func showMessage(_ text: String) { lastMessage = text }
139
140 /// Local key routing is shared with native checks; repeated actions never click twice.
141 func handle(_ event: NSEvent) -> NSEvent? {
142 guard isControlling, NSApp.keyWindow === panel else { return event }
143 return routeKey(event)
144 }
145 func routeKey(_ event: NSEvent) -> NSEvent? {
146 guard isControlling else { return event }
147 onLowPointer?(event.modifierFlags.contains(.option) && event.modifierFlags.intersection([.command, .control]).isEmpty)
148 onFastPace?(event.modifierFlags.contains(.shift) && event.modifierFlags.intersection([.command, .option, .control]).isEmpty)
149 if event.type == .flagsChanged {
150 if !event.modifierFlags.intersection([.command, .control]).isEmpty { clearDirections() }
151 return event
152 }
153 if event.keyCode == 53, event.type == .keyDown { stop(restoreFocus: true); return nil }
154 guard event.modifierFlags.intersection([.command, .control]).isEmpty else { return event }
155 if [UInt16(36), 76].contains(event.keyCode) {
156 if event.type == .keyDown, !event.isARepeat { clearDirections(); onFastPace?(false); onLowPointer?(false); onPrompt?() }
157 return nil
158 }
159 let moves: Set<UInt16> = [0, 1, 2, 8, 13, 123, 124, 125, 126]
160 if moves.contains(event.keyCode) {
161 if event.type == .keyDown { held.insert(event.keyCode) } else { held.remove(event.keyCode) }
162 updateDirection()
163 return nil
164 }
165 if event.keyCode == 5 {
166 if event.type == .keyDown, !event.isARepeat { aiming = true; onAimChanged?(true); updateDirection() }
167 if event.type == .keyUp, aiming { aiming = false; onGrapple?(); onAimChanged?(false); updateDirection() }
168 return nil
169 }
170 guard [UInt16(49), 14].contains(event.keyCode) else { return event }
171 if event.type == .keyDown, !event.isARepeat {
172 switch event.keyCode { case 49: onJump?(); default: onInteract?() }
173 }
174 return nil
175 }
176
177 private func updateDirection() {
178 let x = (held.isDisjoint(with: [2, 124]) ? 0.0 : 1) - (held.isDisjoint(with: [0, 123]) ? 0.0 : 1)
179 let y = (held.isDisjoint(with: [13, 126]) ? 0.0 : 1) - (held.isDisjoint(with: [1, 125]) ? 0.0 : 1)
180 onCrouch?(held.contains(8))
181 onAimDirection?(aiming ? x : 0, aiming ? y : 0)
182 onDirection?(aiming ? 0 : x, aiming ? 0 : y)
183 }
184 func clearDirections() { held.removeAll(); updateDirection() }
185 func stop(restoreFocus: Bool = false) {
186 guard isControlling else { return }
187 isControlling = false
188 clickRestore?.cancel(); clickRestore = nil; isPerformingClick = false
189 aiming = false; onAimChanged?(false)
190 clearDirections(); onFastPace?(false); onLowPointer?(false)
191 if let monitor { NSEvent.removeMonitor(monitor) }; monitor = nil
192 panel.orderOut(nil)
193 onStop?()
194 if restoreFocus, previousApp?.processIdentifier != ProcessInfo.processInfo.processIdentifier { previousApp?.activate(options: []) }
195 previousApp = nil
196 }
197 func beginClick() { isPerformingClick = true }
198 func finishClick() {
199 guard isControlling, isPerformingClick else { return }
200 // AX actions and ordinary clicks can activate the destination app. Keep
201 // the play session alive and return its key window after event delivery.
202 let work = DispatchWorkItem { [weak self] in
203 MainActor.assumeIsolated {
204 guard let self, self.isControlling, self.isPerformingClick else { return }
205 NSApp.activate(ignoringOtherApps: true)
206 self.panel.makeKeyAndOrderFront(nil)
207 self.held = Set([UInt16(0), 1, 2, 8, 13, 123, 124, 125, 126].filter {
208 CGEventSource.keyState(.combinedSessionState, key: CGKeyCode($0))
209 })
210 self.updateDirection()
211 self.onLowPointer?(CGEventSource.keyState(.combinedSessionState, key: 58) || CGEventSource.keyState(.combinedSessionState, key: 61))
212 self.onFastPace?(CGEventSource.keyState(.combinedSessionState, key: 56) || CGEventSource.keyState(.combinedSessionState, key: 60))
213 if self.aiming && !CGEventSource.keyState(.combinedSessionState, key: 5) {
214 self.aiming = false; self.onAimChanged?(false)
215 self.updateDirection()
216 }
217 self.isPerformingClick = false
218 self.clickRestore = nil
219 }
220 }
221 clickRestore?.cancel(); clickRestore = work
222 DispatchQueue.main.asyncAfter(deadline: .now() + 0.15, execute: work)
223 }
224 func windowDidResignKey(_ notification: Notification) {
225 if !isPerformingClick { stop() }
226 }
227 func close() { stop(); panel.delegate = nil; panel.close() }
228}
229
230/// User-triggered interaction only. E performs one press at the visible hand marker.
231@MainActor
232final class ExplorerDesktopClick {
233 static var hasAccess: Bool { AXIsProcessTrusted() }
234 static func requestAccess() {
235 DesktopAccess.shared.present(.accessibility)
236 }
237 static func quartzPoint(_ point: CGPoint, primaryTop: CGFloat) -> CGPoint {
238 .init(x: point.x, y: primaryTop - point.y)
239 }
240 static func press(at point: CGPoint) -> String {
241 guard hasAccess else { return "Allow Jerry in System Settings → Privacy & Security → \(DesktopAccess.Permission.accessibility.title), then press E again." }
242 var element: AXUIElement?
243 if AXUIElementCopyElementAtPosition(AXUIElementCreateSystemWide(), Float(point.x), Float(point.y), &element) == .success {
244 for _ in 0..<6 {
245 guard let current = element else { break }
246 var pid: pid_t = 0
247 AXUIElementGetPid(current, &pid)
248 guard pid != ProcessInfo.processInfo.processIdentifier else { return "Move the marker away from the explorer's own controls." }
249 var actions: CFArray?
250 if AXUIElementCopyActionNames(current, &actions) == .success,
251 let names = actions as? [String], names.contains(kAXPressAction as String),
252 AXUIElementPerformAction(current, kAXPressAction as CFString) == .success { return "Pressed the control at the hand marker." }
253 var parent: CFTypeRef?
254 guard AXUIElementCopyAttributeValue(current, kAXParentAttribute as CFString, &parent) == .success,
255 let parent, CFGetTypeID(parent) == AXUIElementGetTypeID() else { break }
256 element = (parent as! AXUIElement)
257 }
258 }
259 // Canvas/custom controls may not expose AXPress. Send exactly one ordinary
260 // left click at the same marker. The controller restores its key window.
261 guard let down = CGEvent(mouseEventSource: nil, mouseType: .leftMouseDown, mouseCursorPosition: point, mouseButton: .left),
262 let up = CGEvent(mouseEventSource: nil, mouseType: .leftMouseUp, mouseCursorPosition: point, mouseButton: .left) else { return "Could not create the click." }
263 down.setIntegerValueField(.mouseEventClickState, value: 1)
264 up.setIntegerValueField(.mouseEventClickState, value: 1)
265 down.post(tap: .cghidEventTap); up.post(tap: .cghidEventTap)
266 return "Clicked at the hand marker. Explorer control stays active."
267 }
268}