Open History to see the last commit
1import AppKit
2import SpriteKit
3import ExpeditionCore
4
5/// The full-screen rendering layer never accepts input.
6@MainActor
7private final class OverlayPanel: NSPanel {
8 override var canBecomeKey: Bool { false }
9 override var canBecomeMain: Bool { false }
10}
11
12@MainActor
13final class OverlayController {
14 private let panel: OverlayPanel
15 private let view: SKView
16 private let scene: ExplorerScene
17 private let inputPanel: ExplorerInputPanel
18 private let inputView: ExplorerInputView
19 private var displayOrigin = CGPoint.zero
20 private let windowProvider = WindowProvider()
21 var onPromptRequested: (() -> Void)?
22 var onExplorerMoved: (() -> Void)?
23 var onAgentHandMoved: ((CGPoint) -> Void)?
24 private var agentInputSuppressed = false
25 private var parkedAgentPointer: CGPoint?
26 var onTaskInterrupted: (() -> Void)?
27 private var terrainTimer: Timer?
28 private var featureTimer: Timer?
29 private let featureCapture = WindowFeatureCapture()
30 private let supplementaryCapture = WindowFeatureCapture()
31 private var geometry: TerrainSnapshot?
32 private var lastGeometryTime: TimeInterval?
33 private var geometrySampleElapsed = 0.1
34 private var policy = RuntimePolicy()
35 private var desktopCheck: DispatchWorkItem?
36 private var terrainRefreshCount = 0
37 private var characterHeld = false
38 private let keyboard = ExplorerKeyboardController()
39 private var clickPending = false
40 var onKeyboardControlChanged: ((Bool) -> Void)?
41 private var renderPauseWork: DispatchWorkItem?
42
43 init() {
44 let frame = NSScreen.screens.first?.frame ?? NSRect(x: 0, y: 0, width: 800, height: 600)
45 panel = OverlayPanel(contentRect: frame, styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false)
46 panel.title = "Jerry Overlay"
47 panel.isFloatingPanel = true
48 panel.hidesOnDeactivate = false
49 panel.isOpaque = false
50 panel.backgroundColor = .clear
51 panel.hasShadow = false
52 panel.ignoresMouseEvents = true
53 panel.level = NSWindow.Level(rawValue: NSWindow.Level.statusBar.rawValue + 1)
54 panel.collectionBehavior = [.canJoinAllSpaces, .ignoresCycle, .fullScreenAuxiliary]
55 panel.isReleasedWhenClosed = false
56 panel.isRestorable = false
57 panel.animationBehavior = .none
58
59 scene = ExplorerScene(size: frame.size)
60 inputPanel = ExplorerInputPanel(contentRect: .zero, styleMask: [.borderless, .nonactivatingPanel], backing: .buffered, defer: false)
61 inputPanel.title = "Explorer — drag to move"
62 inputPanel.isFloatingPanel = true
63 inputPanel.hidesOnDeactivate = false
64 inputPanel.becomesKeyOnlyIfNeeded = true
65 inputPanel.isMovable = false
66 inputPanel.isOpaque = false
67 inputPanel.backgroundColor = .clear
68 inputPanel.hasShadow = false
69 inputPanel.level = panel.level
70 inputPanel.collectionBehavior = [.canJoinAllSpaces, .ignoresCycle, .fullScreenAuxiliary]
71 inputPanel.isReleasedWhenClosed = false
72 inputPanel.isRestorable = false
73 inputPanel.animationBehavior = .none
74 inputView = ExplorerInputView(frame: .zero)
75 inputView.autoresizingMask = [.width, .height]
76 inputPanel.contentView = inputView
77 // Keep the hit area above the renderer even if another app or accessibility tool raises it.
78 panel.addChildWindow(inputPanel, ordered: .above)
79 view = SKView(frame: NSRect(origin: .zero, size: frame.size))
80 view.autoresizingMask = [.width, .height]
81 view.allowsTransparency = true
82 view.preferredFramesPerSecond = ExpeditionConfiguration.framesPerSecond
83 panel.contentView = view
84 view.presentScene(scene)
85 scene.onFrame = { [weak self] in self?.updateAgentHitAreas() }
86 scene.onPlacementChanged = { [weak self] frame, state in
87 guard let self else { return }
88 self.inputPanel.setFrame(frame.offsetBy(dx: self.displayOrigin.x, dy: self.displayOrigin.y), display: true)
89 self.onExplorerMoved?()
90 if self.scene.agentMode, let point = self.scene.agentHandPoint, let primary = NSScreen.screens.first {
91 self.onAgentHandMoved?(.init(x: point.x + self.displayOrigin.x, y: primary.frame.maxY - point.y - self.displayOrigin.y))
92 }
93 self.inputView.setAccessibilityValue("\(state) at \(Int(frame.midX)), \(Int(frame.minY))")
94 let wasHeld = self.characterHeld
95 self.characterHeld = state == "held"
96 self.updateRenderingPause(allowFinalFrame: wasHeld && !self.characterHeld)
97 }
98 inputView.onBegin = { [weak self] point in
99 guard let self else { return }
100 self.onTaskInterrupted?()
101 self.setKeyboardControl(false)
102 self.scene.beginDrag(at: self.scenePoint(point))
103 }
104 inputView.onDrag = { [weak self] point in
105 guard let self else { return }
106 self.scene.drag(to: self.scenePoint(point))
107 }
108 inputView.onEnd = { [weak self] in
109 self?.refreshTerrain()
110 self?.scene.endDrag()
111 }
112 keyboard.onPrompt = { [weak self] in self?.onPromptRequested?() }
113 keyboard.onDirection = { [weak self] x, y in self?.scene.setControlDirection(x, y) }
114 keyboard.onLowPointer = { [weak self] in self?.scene.setControlPointerLowered($0) }
115 keyboard.onCrouch = { [weak self] held in self?.scene.setControlCrouch(held) }
116 keyboard.onFastPace = { [weak self] fast in self?.scene.setControlFastPace(fast) }
117 keyboard.onJump = { [weak self] in self?.scene.controlJump() }
118 keyboard.onAimDirection = { [weak self] x, y in self?.scene.setAimDirection(x, y) }
119 keyboard.onAimChanged = { [weak self] active in
120 self?.scene.setGrappleAiming(active)
121 if active { self?.keyboard.showMessage("Hold G and use the arrows to aim at a window's top rim. Release G to fire. Release G to use arrows for movement again.") }
122 }
123 keyboard.onGrapple = { [weak self] in
124 guard let self else { return }
125 self.keyboard.showMessage(self.scene.fireAimedGrapple() ? "Hook fired. Up climbs, Down descends; left/right pumps the swing." : "No reachable top rim there. Hold G and use the arrows to aim at a window's top edge.")
126 }
127 keyboard.onInteract = { [weak self] in self?.clickAtExplorer() }
128 keyboard.onStop = { [weak self] in
129 self?.scene.setKeyboardControl(false)
130 self?.onKeyboardControlChanged?(false)
131 }
132 updateDisplay()
133 let timer = Timer(timeInterval: 0.1, repeats: true) { [weak self] _ in
134 MainActor.assumeIsolated {
135 guard let self, self.policy.shouldPollTerrain else { return }
136 self.refreshTerrain()
137 }
138 }
139 featureCapture.onFeatures = { [weak self] _ in self?.publishTerrain() }
140 supplementaryCapture.onFeatures = { [weak self] _ in self?.publishTerrain() }
141 let featureTimer = Timer(timeInterval: 1.0 / 30, repeats: true) { [weak self] _ in
142 MainActor.assumeIsolated {
143 guard let self, self.policy.shouldPollTerrain, self.featureCapture.enabled else { return }
144 self.publishTerrain()
145 }
146 }
147 self.featureTimer = featureTimer
148 RunLoop.main.add(featureTimer, forMode: .common)
149 terrainTimer = timer
150 RunLoop.main.add(timer, forMode: .common)
151 }
152
153 private func scenePoint(_ point: CGPoint) -> CGPoint {
154 CGPoint(x: point.x - displayOrigin.x, y: point.y - displayOrigin.y)
155 }
156
157 func show() {
158 guard policy.shouldShow, !clickPending else { return }
159 panel.orderFrontRegardless()
160 if !scene.agentMode { inputPanel.order(.above, relativeTo: panel.windowNumber) }
161 else { updateAgentHitAreas() }
162 }
163
164 func updateDisplay() {
165 setKeyboardControl(false)
166 // The first screen owns the menu bar. Do not follow whichever screen has keyboard focus.
167 guard let screen = NSScreen.screens.first else {
168 policy.desktopSupported = false
169 applyPolicy()
170 return
171 }
172 inputView.cancelDrag()
173 displayOrigin = screen.frame.origin
174 panel.setFrame(screen.frame, display: true)
175 scene.size = screen.frame.size
176 let usable = screen.visibleFrame.offsetBy(dx: -screen.frame.minX, dy: -screen.frame.minY)
177 scene.layout(in: usable)
178 refreshTerrain()
179 checkDesktop()
180 show()
181 }
182
183 private func refreshTerrain() {
184 terrainRefreshCount += 1
185 guard let screen = NSScreen.screens.first else { return }
186 let now = ProcessInfo.processInfo.systemUptime
187 geometrySampleElapsed = lastGeometryTime.map { max(1.0 / 120, now - $0) } ?? 0.1
188 lastGeometryTime = now
189 geometry = windowProvider.snapshot(on: screen)
190 if let geometry {
191 let host = geometry.windows.first { $0.id == scene.attachedWindowID && $0.canClimb }?.id
192 let primary = host ?? windowProvider.frontWindowID ?? windowProvider.keyboardWindowID
193 featureCapture.update(terrain: geometry, preferredWindow: primary, running: policy.shouldRun)
194 // Keep the visible keyboard and working window available together, with
195 // no duplicate stream when the explorer transfers onto the keyboard.
196 let secondary = [windowProvider.keyboardWindowID, windowProvider.frontWindowID].compactMap { $0 }.first { $0 != primary }
197 let extra = TerrainSnapshot(windows: geometry.windows.filter { $0.id == secondary }, viewport: geometry.viewport)
198 supplementaryCapture.update(terrain: extra, preferredWindow: secondary, running: policy.shouldRun)
199 }
200 publishTerrain()
201 }
202
203 private func publishTerrain() {
204 guard let geometry else { scene.updateTerrain(nil); return }
205 scene.updateTerrain(TerrainSnapshot(windows: geometry.windows, viewport: geometry.viewport, features: featureCapture.currentFeatures() + supplementaryCapture.currentFeatures()), geometrySampleElapsed: geometrySampleElapsed)
206 }
207 func setExploreInsideWindows(_ enabled: Bool) {
208 featureCapture.enabled = enabled; supplementaryCapture.enabled = enabled
209 if !enabled { featureCapture.stop(); supplementaryCapture.stop() }
210 refreshTerrain()
211 }
212 var windowExplorationStatus: String { featureCapture.status + (supplementaryCapture.currentFeatures().isEmpty ? "" : " · Keyboard/second window: " + supplementaryCapture.status) }
213
214 func beginAgent() { setKeyboardControl(false); scene.setAgentMode(true); setAgentLayer(true); setPaused(false); checkDesktop() }
215 func stopAgent() { parkedAgentPointer = nil; agentInputSuppressed = false; setAgentLayer(false); scene.setAgentMode(false); checkDesktop() }
216 private func setAgentLayer(_ active: Bool) {
217 panel.level = .init(rawValue: active ? NSWindow.Level.popUpMenu.rawValue + 1 : NSWindow.Level.statusBar.rawValue + 1)
218 inputPanel.level = panel.level
219 }
220 func setPhotoMoment(_ active: Bool) { scene.setPhotoMoment(active) }
221 var photoSubject: (windowID: UInt32, frame: CGRect)? {
222 guard panel.isVisible, let primary = NSScreen.screens.first else { return nil }
223 let rect = scene.agentPhotoBounds
224 return (UInt32(panel.windowNumber), CGRect(x: rect.minX + displayOrigin.x, y: primary.frame.maxY - displayOrigin.y - rect.maxY, width: rect.width, height: rect.height))
225 }
226 func setAgentReading(_ reading: Bool) { scene.agentReading = reading }
227 func agentInputVisible(_ visible: Bool) {
228 agentInputSuppressed = !visible
229 if visible && scene.agentMode { parkedAgentPointer = NSEvent.mouseLocation }
230 updateAgentHitAreas()
231 }
232 private func updateAgentHitAreas() {
233 let mouse = NSEvent.mouseLocation
234 if let parked = parkedAgentPointer, hypot(parked.x - mouse.x, parked.y - mouse.y) > 2 { parkedAgentPointer = nil }
235 func update(_ hit: NSPanel) {
236 let parkedUnderCharacter = scene.agentMode && parkedAgentPointer != nil && hit.frame.contains(mouse)
237 let visible = policy.shouldShow && !agentInputSuppressed && !parkedUnderCharacter
238 if visible { if !hit.isVisible { hit.order(.above, relativeTo: panel.windowNumber) } }
239 else if hit.isVisible { hit.orderOut(nil) }
240 }
241 update(inputPanel)
242 }
243 func reachForAgent(_ quartz: CGPoint) async throws -> Bool {
244 guard let primary = NSScreen.screens.first, scene.agentMode else { throw CancellationError() }
245 let point = CGPoint(x: quartz.x - displayOrigin.x, y: primary.frame.maxY - quartz.y - displayOrigin.y)
246 scene.agentTarget = point
247 let deadline = ProcessInfo.processInfo.systemUptime + 100
248 var stable = 0
249 var ascent = 0.0
250 var previousHeight = scene.agentClimbSample?.height
251 var lastTrace = 0.0
252 while stable < 4 {
253 try Task.checkCancellation(); guard scene.agentMode else { throw CancellationError() }
254 if ProcessInfo.processInfo.systemUptime > deadline { throw AgentConnectionError(message: "The explorer could not reach that control in time. Choose a nearer route or move its window.") }
255 #if DEBUG
256 let now = ProcessInfo.processInfo.systemUptime
257 if ProcessInfo.processInfo.arguments.contains("--trace-agent"), now - lastTrace > 1 {
258 print("AGENT REACH", scene.agentDiagnostic, "target", point, "paused", view.isPaused); fflush(stdout); lastTrace = now
259 }
260 #endif
261 if let sample = scene.agentClimbSample {
262 if sample.climbing, let previousHeight { ascent += max(0, sample.height - previousHeight) }
263 previousHeight = sample.height
264 }
265 stable = scene.agentAtTarget ? stable + 1 : 0
266 try await Task.sleep(for: .milliseconds(50))
267 }
268 return ascent >= 240
269 }
270 func setPaused(_ paused: Bool) {
271 if paused { setKeyboardControl(false) }
272 policy.manuallyPaused = paused
273 if paused { applyPolicy() } else { checkDesktop() }
274 }
275 func recordFrontApp() { keyboard.recordFrontApp() }
276 func restoreExternalFocus() { keyboard.restoreExternalFocus() }
277 var explorerScreenFrame: CGRect { inputPanel.frame }
278 var keyboardControlEnabled: Bool { keyboard.isControlling }
279 func setKeyboardControl(_ enabled: Bool, restoreFocus: Bool = false) {
280 if enabled {
281 guard policy.shouldShow else { return }
282 setPaused(false)
283 scene.setKeyboardControl(true)
284 keyboard.start()
285 onKeyboardControlChanged?(true)
286 } else { keyboard.stop(restoreFocus: restoreFocus) }
287 }
288 func requestClickAccess() {
289 ExplorerDesktopClick.requestAccess()
290 keyboard.showMessage("Enable Jerry in Privacy & Security → \(DesktopAccess.Permission.accessibility.title), then return to keyboard control.")
291 }
292 private func clickAtExplorer() {
293 guard keyboard.isControlling, !clickPending, let local = scene.keyboardClickPoint,
294 let screen = NSScreen.screens.first else { return }
295 guard ExplorerDesktopClick.hasAccess else { requestClickAccess(); return }
296 let cocoa = CGPoint(x: local.x + displayOrigin.x, y: local.y + displayOrigin.y)
297 guard !keyboard.panel.frame.contains(cocoa) else {
298 keyboard.showMessage("Move the marker away from the keyboard-control window."); return
299 }
300 let point = ExplorerDesktopClick.quartzPoint(cocoa, primaryTop: screen.frame.maxY)
301 clickPending = true
302 keyboard.beginClick()
303 panel.orderOut(nil); inputPanel.orderOut(nil)
304 DispatchQueue.main.asyncAfter(deadline: .now() + 0.06) { [weak self] in
305 guard let self else { return }
306 if self.keyboard.isControlling && self.policy.shouldRun {
307 self.keyboard.showMessage(ExplorerDesktopClick.press(at: point))
308 }
309 self.clickPending = false
310 self.keyboard.finishClick()
311 if self.policy.shouldShow { self.show() }
312 }
313 }
314
315 func setIdleExploration(_ enabled: Bool) { scene.setIdleExploration(enabled) }
316 var idleExplorationEnabled: Bool { scene.idleExplorationEnabled }
317 var activityStatus: String { scene.activityStatus }
318 var availableActivities: Set<ExplorerActivity> { scene.availableActivities }
319 func requestActivity(_ activity: ExplorerActivity) { setKeyboardControl(false); refreshTerrain(); scene.requestActivity(activity) }
320
321 func setRunWhenExploring(_ enabled: Bool) { scene.setRunWhenExploring(enabled) }
322 func setFasterRopeWork(_ enabled: Bool) { scene.setFasterRopeWork(enabled) }
323 func setGentlePace(_ gentle: Bool) { scene.playbackRate = gentle ? 0.65 : 1 }
324
325 func setSleeping(_ sleeping: Bool) {
326 policy.sleeping = sleeping
327 if !sleeping { updateDisplay(); checkDesktop() }
328 applyPolicy()
329 }
330
331 func desktopChanged() {
332 // Hide during the transition, then read the new Space rather than retaining old anchors.
333 desktopCheck?.cancel()
334 policy.desktopSupported = false
335 applyPolicy()
336 let work = DispatchWorkItem { [weak self] in
337 MainActor.assumeIsolated { self?.checkDesktop() }
338 }
339 desktopCheck = work
340 DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: work)
341 }
342
343 func checkDesktop() {
344 guard !policy.manuallyPaused, !policy.sleeping else { applyPolicy(); return }
345 guard let screen = NSScreen.screens.first else { return }
346 policy.desktopSupported = scene.agentMode || windowProvider.isSupportedDesktop(on: screen)
347 applyPolicy()
348 }
349
350 private func applyPolicy() {
351 if !policy.shouldRun { setKeyboardControl(false); featureCapture.stop(); supplementaryCapture.stop() }
352 if policy.shouldRun { refreshTerrain() }
353 scene.setExpeditionPaused(!policy.shouldRun)
354 if policy.shouldShow { show() }
355 else {
356 inputView.cancelDrag()
357 panel.orderOut(nil)
358 inputPanel.orderOut(nil)
359 }
360 updateRenderingPause()
361 }
362
363 private func updateRenderingPause(allowFinalFrame: Bool = false) {
364 renderPauseWork?.cancel()
365 if policy.shouldRun || (policy.shouldShow && characterHeld) { view.isPaused = false }
366 else if allowFinalFrame && policy.shouldShow {
367 // A paused drag still needs rendering, including its final release position.
368 view.isPaused = false
369 let work = DispatchWorkItem { [weak self] in
370 MainActor.assumeIsolated {
371 guard let self, !self.policy.shouldRun, !self.characterHeld else { return }
372 self.view.isPaused = true
373 }
374 }
375 renderPauseWork = work
376 DispatchQueue.main.asyncAfter(deadline: .now() + 0.06, execute: work)
377 } else { view.isPaused = true }
378 }
379
380 func resetExpedition() { setKeyboardControl(false); refreshTerrain(); scene.resetExpedition() }
381
382 func setDebugVisible(_ visible: Bool) { scene.setDebugVisible(visible) }
383
384 func close() {
385 keyboard.close()
386 desktopCheck?.cancel()
387 renderPauseWork?.cancel()
388 featureCapture.stop(); supplementaryCapture.stop(); featureTimer?.invalidate(); featureTimer = nil
389 terrainTimer?.invalidate()
390 terrainTimer = nil
391 inputView.cancelDrag()
392 scene.onPlacementChanged = nil
393 inputPanel.orderOut(nil)
394 panel.removeChildWindow(inputPanel)
395 inputPanel.close()
396 view.isPaused = true
397 view.presentScene(nil)
398 panel.orderOut(nil)
399 panel.close()
400 }
401 #if DEBUG
402 /// Tests our real AppKit panel/lifecycle integration without synthesising user input,
403 /// sleeping the machine, or changing Spaces on the user's desktop.
404 func runNativeChecks() -> Bool {
405 var passed = true
406 func check(_ condition: Bool, _ name: String) {
407 print("NATIVE \(condition ? "PASS" : "FAIL") \(name)")
408 passed = passed && condition
409 }
410 check(WindowProvider.isScreenRecorder(bundle: "com.apple.screencaptureui", owner: "Screenshot"), "Screenshot selection windows and toolbar are excluded from terrain")
411 check(WindowProvider.isScreenRecorder(bundle: nil, owner: "screencapture"), "the unbundled recording backdrop is excluded from terrain")
412 check(!WindowProvider.isScreenRecorder(bundle: "com.apple.QuickTimePlayerX", owner: "QuickTime Player"), "normal QuickTime playback windows retain their edges")
413 check(!WindowProvider.isScreenRecorder(bundle: nil, owner: "another helper"), "unrelated unbundled windows are not excluded")
414 let display = CGRect(x: 0, y: 0, width: 1710, height: 1107)
415 check(WindowProvider.isKeyboardBackdrop(bundle: "com.apple.inputmethod.AssistiveControl", layer: 2997, frame: display, display: display), "transparent accessibility keyboard backdrops do not occlude terrain")
416 check(!WindowProvider.isKeyboardBackdrop(bundle: "com.apple.inputmethod.AssistiveControl", layer: 101, frame: CGRect(x: 1000, y: 690, width: 600, height: 323), display: display), "the actual floating keyboard still occludes terrain")
417 check(!WindowProvider.isKeyboardBackdrop(bundle: "com.apple.inputmethod.AssistiveControl", layer: 2997, frame: CGRect(x: 0, y: 0, width: 500, height: 100), display: display), "small accessibility panels are not mistaken for full-screen backdrops")
418 check(!WindowProvider.isKeyboardBackdrop(bundle: "another.app", layer: 2997, frame: display, display: display), "other apps retain their real full-screen occluders")
419 let keyboardFrame = CGRect(x: 1048, y: 692, width: 598, height: 323)
420 let journalTerrain = NSPanel(contentRect: .init(x: 180, y: 120, width: 620, height: 480), styleMask: [.titled, .nonactivatingPanel], backing: .buffered, defer: false)
421 journalTerrain.isReleasedWhenClosed = false; journalTerrain.level = .floating
422 check(WindowProvider.isAppTerrainWindow(journalTerrain), "the journal is climbable terrain even when its panel floats above other windows")
423 check(!WindowProvider.isAppTerrainWindow(panel) && !WindowProvider.isAppTerrainWindow(inputPanel), "transparent explorer rendering and drag panels never become terrain")
424 journalTerrain.orderFrontRegardless(); journalTerrain.displayIfNeeded()
425 RunLoop.main.run(until: Date(timeIntervalSinceNow: 0.08))
426 let journalSnapshot = WindowProvider().snapshot(on: NSScreen.screens.first!)
427 check(journalSnapshot?.windows.contains { $0.id == UInt32(journalTerrain.windowNumber) && $0.canClimb } == true, "real app-owned journal panels survive window discovery in stacking order")
428 journalTerrain.close()
429 check(WindowProvider.canClimbWindow(bundle: "com.apple.inputmethod.AssistiveControl", layer: 101, frame: keyboardFrame), "the Accessibility Keyboard has climbable edges and can supply internal holds")
430 check(WindowProvider.canClimbWindow(bundle: "com.apple.KeyboardViewer", layer: 101, frame: keyboardFrame), "Keyboard Viewer floating panels have climbable edges")
431 check(!WindowProvider.canClimbWindow(bundle: "com.apple.inputmethod.AssistiveControl", layer: 2997, frame: display), "keyboard backdrops cannot become climbing or capture targets")
432 check(!WindowProvider.canClimbWindow(bundle: "another.app", layer: 101, frame: keyboardFrame), "unrelated floating overlays remain occluders only")
433 let focus = NSWorkspace.shared.frontmostApplication?.processIdentifier
434 let hatPart = PaintedPart(rect: .init(x: -12, y: 7, width: 24, height: 8), radius: 2, color: ExplorerPalette.hat, material: .felt)
435 check(panel.level.rawValue > Int(CGWindowLevelForKey(.dockWindow)), "explorer is layered above the system Dock")
436 check(hatPart.silhouettePath.boundingBoxOfPath == .init(x: -12, y: -4, width: 24, height: 8), "shadow silhouettes use sprite-local coordinates")
437 let shadowRig = ExplorerRig(), shadowSpace = SKNode()
438 shadowSpace.addChild(shadowRig); shadowRig.position = .init(x: 200, y: 200)
439 shadowRig.setShadowOcclusion(windows: [.init(x: 180, y: 0, width: 200, height: 200)], from: shadowSpace)
440 check(shadowRig.shadowIsVisible(at: .init(x: 0, y: 20)) && !shadowRig.shadowIsVisible(at: .init(x: 0, y: -1)), "supporting window hides shadow beneath its lip")
441 shadowRig.xScale = -1
442 shadowRig.setShadowOcclusion(windows: [.init(x: 180, y: 0, width: 200, height: 200)], from: shadowSpace)
443 check(!shadowRig.shadowIsVisible(at: .init(x: -50, y: -1)) && shadowRig.shadowIsVisible(at: .init(x: 50, y: -1)), "ledge shadow clipping survives mirrored facing")
444 shadowRig.position.y = 180
445 shadowRig.setShadowOcclusion(windows: [.init(x: 180, y: 0, width: 200, height: 200)], from: shadowSpace)
446 check(shadowRig.shadowIsVisible(at: .init(x: 0, y: -1)), "hanging in front of a window keeps its cast shadow")
447 var crackClamps = 0
448 for horizontal in [true, false] {
449 for step in 0..<120 {
450 shadowRig.crackPose = CrackAnimation.pose(horizontal: horizontal, time: Double(step) / 60, offset: Double(step))
451 shadowRig.select(.climbing); shadowRig.render(delta: 0.1)
452 crackClamps += shadowRig.clampedContacts
453 }
454 }
455 check(crackClamps == 0, "crack traverse and vertical climbing stay inside limb reach")
456 shadowRig.crackPose = nil
457 var crouchClamps = 0
458 for step in 0..<120 {
459 shadowRig.crouchAmount = Double(step % 30) / 29
460 shadowRig.select(.walking); shadowRig.synchronizedTime = Double(step) / 60
461 shadowRig.render(delta: 1.0 / 60)
462 crouchClamps += shadowRig.clampedContacts
463 }
464 check(crouchClamps == 0, "crouched walking keeps knees and reaching arms inside limb reach")
465 shadowRig.crouchAmount = 0
466 show()
467 check(panel.isVisible && inputPanel.isVisible, "both panels visible")
468 check(panel.ignoresMouseEvents && !inputPanel.ignoresMouseEvents, "input confined to body panel")
469 check(!panel.canBecomeKey && !inputPanel.canBecomeKey, "panels cannot take keyboard focus")
470 check(inputPanel.frame.width == 48 && inputPanel.frame.height == 76, "body-only hit area")
471 setPaused(true)
472 check(!policy.shouldPollTerrain && view.isPaused, "explicit pause suspends polling and scene")
473 let pausedPolls = terrainRefreshCount
474 RunLoop.main.run(until: Date(timeIntervalSinceNow: 0.3))
475 check(terrainRefreshCount == pausedPolls, "paused timer performs no geometry reads")
476 let original = inputPanel.frame
477 let grab = CGPoint(x: original.midX, y: original.midY)
478 inputView.onBegin?(grab)
479 inputView.onDrag?(CGPoint(x: grab.x + 60, y: grab.y + 30))
480 check(abs(inputPanel.frame.midX - original.midX - 60) < 0.1, "paused drag callback moves body panel")
481 check(!view.isPaused && !policy.shouldRun, "paused drag renders without advancing simulation")
482 inputView.onEnd?()
483 // First-use mask/blur pipeline compilation can delay the final frame.
484 let finalFrameDeadline = Date(timeIntervalSinceNow: 0.75)
485 while !view.isPaused && Date() < finalFrameDeadline {
486 RunLoop.main.run(until: Date(timeIntervalSinceNow: 0.02))
487 }
488 check(view.isPaused, "paused release renders final frame then stops")
489 setSleeping(true)
490 check(!panel.isVisible && !inputPanel.isVisible, "sleep hides all panels")
491 setSleeping(false)
492 check(policy.manuallyPaused && !policy.shouldRun, "wake preserves explicit pause")
493 policy.desktopSupported = false
494 applyPolicy()
495 check(!panel.isVisible && !inputPanel.isVisible && !policy.shouldPollTerrain, "unsupported desktop is hidden and suspended")
496 policy.desktopSupported = true
497 setPaused(false)
498 check(policy.shouldRun && panel.isVisible && inputPanel.isVisible, "return refreshes and resumes")
499 resetExpedition()
500 check(NSWorkspace.shared.frontmostApplication?.processIdentifier == focus, "launch/reset/lifecycle preserve frontmost app")
501 let previousApp = NSWorkspace.shared.frontmostApplication
502 var direction = CGPoint.zero, aimDirection = CGPoint.zero, jumps = 0, clicks = 0, shots = 0, aiming = false, fastPace = false
503 let tester = ExplorerKeyboardController()
504 tester.onDirection = { x, y in direction = .init(x: x, y: y) }
505 tester.onJump = { jumps += 1 }
506 tester.onFastPace = { fastPace = $0 }
507 tester.onInteract = { clicks += 1 }
508 tester.onAimChanged = { aiming = $0 }
509 tester.onAimDirection = { x, y in aimDirection = .init(x: x, y: y) }
510 var crouching = false
511 tester.onCrouch = { crouching = $0 }
512 tester.onGrapple = { shots += 1 }
513 tester.start()
514 RunLoop.main.run(until: Date(timeIntervalSinceNow: 0.08))
515 check(tester.isControlling && tester.panel.canBecomeKey && !panel.canBecomeKey, "manual mode has a dedicated keyboard input target")
516 check(tester.panel.frame.size == .init(width: 1, height: 1) && !tester.panel.isOpaque && tester.panel.ignoresMouseEvents && tester.panel.styleMask == .borderless, "manual input has no visible controls window or mouse hit area")
517 func key(_ code: UInt16, down: Bool = true, repeatKey: Bool = false, flags: NSEvent.ModifierFlags = []) -> NSEvent {
518 NSEvent.keyEvent(with: down ? .keyDown : .keyUp, location: .zero, modifierFlags: flags, timestamp: 0, windowNumber: tester.panel.windowNumber, context: nil, characters: "", charactersIgnoringModifiers: "", isARepeat: repeatKey, keyCode: code)!
519 }
520 check(tester.routeKey(key(124)) == nil && direction.x == 1, "arrow key is consumed and starts player movement")
521 _ = tester.routeKey(key(0))
522 check(direction.x == 0, "opposite movement keys cancel")
523 _ = tester.routeKey(key(0, down: false)); _ = tester.routeKey(key(124, down: false))
524 check(direction == .zero, "key release clears movement")
525 _ = tester.routeKey(key(124, flags: .shift))
526 check(fastPace && direction.x == 1, "Shift movement enables fast pace without clearing directions")
527 _ = tester.routeKey(key(124, down: false))
528 check(!fastPace && direction == .zero, "releasing Shift restores normal pace")
529 _ = tester.routeKey(key(8))
530 check(crouching && direction == .zero, "holding C crouches without stepping off the ledge")
531 _ = tester.routeKey(key(14))
532 check(crouching && clicks == 1 && tester.isControlling, "E retains crouch and manual control")
533 _ = tester.routeKey(key(8, down: false))
534 check(!crouching, "releasing C restores standing posture")
535 _ = tester.routeKey(key(49)); _ = tester.routeKey(key(49, repeatKey: true))
536 _ = tester.routeKey(key(14)); _ = tester.routeKey(key(14, repeatKey: true))
537 check(jumps == 1 && clicks == 2, "jump and click fire once rather than on key repeat")
538 check(tester.routeKey(key(14, flags: .command)) != nil && clicks == 2, "command shortcuts pass through without clicking")
539 _ = tester.routeKey(key(5)); _ = tester.routeKey(key(5, repeatKey: true))
540 check(aiming && shots == 0, "holding G aims without firing or repeating")
541 _ = tester.routeKey(key(124))
542 check(aimDirection.x == 1 && direction == .zero, "G plus Right adjusts aim without moving or pumping the explorer")
543 _ = tester.routeKey(key(126))
544 check(aimDirection == .init(x: 1, y: 1) && direction == .zero, "G plus arrows supports diagonal aim")
545 _ = tester.routeKey(key(5, down: false))
546 check(!aiming && shots == 1, "releasing G fires one aimed shot")
547 check(aimDirection == .zero && direction == .init(x: 1, y: 1), "releasing G restores held arrows to movement")
548 _ = tester.routeKey(key(124, down: false)); _ = tester.routeKey(key(126, down: false))
549 var prompts = 0
550 tester.onPrompt = { prompts += 1 }
551 _ = tester.routeKey(key(124, flags: .shift))
552 _ = tester.routeKey(key(36)); _ = tester.routeKey(key(36, repeatKey: true)); _ = tester.routeKey(key(36, down: false))
553 check(prompts == 1 && direction == .zero && !fastPace, "Return opens one prompt and clears held movement and pace")
554 check(tester.routeKey(key(36, flags: .command)) != nil && prompts == 1, "modified Return passes through without opening a prompt")
555 tester.beginClick()
556 tester.windowDidResignKey(Notification(name: NSWindow.didResignKeyNotification, object: tester.panel))
557 check(tester.isControlling && tester.isPerformingClick, "click-induced focus loss preserves keyboard session")
558 _ = tester.routeKey(key(53))
559 check(!tester.isControlling && !tester.panel.isVisible && direction == .zero, "Escape ends capture and clears held directions")
560 tester.close()
561 check(ExplorerDesktopClick.quartzPoint(.init(x: 120, y: 240), primaryTop: 900) == .init(x: 120, y: 660), "click marker converts to Quartz coordinates")
562 if !ExplorerDesktopClick.hasAccess {
563 check(ExplorerDesktopClick.press(at: .zero).hasPrefix("Allow"), "desktop click is gated without Accessibility permission")
564 }
565 print("NATIVE INFO Accessibility permission: \(ExplorerDesktopClick.hasAccess)")
566 previousApp?.activate(options: [])
567 close()
568 check(!panel.isVisible && !inputPanel.isVisible && terrainTimer == nil, "close removes panels and timer")
569 return passed
570 }
571 #endif
572
573}