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 marchersActive: Bool { scene.marchersActive }
317 var marchersStatus: String? { scene.marchersStatus }
318 func setMarchersMode(_ enabled: Bool) { refreshTerrain(); scene.setMarchersMode(enabled) }
319 var idleExplorationEnabled: Bool { scene.idleExplorationEnabled }
320 var activityStatus: String { scene.activityStatus }
321 var availableActivities: Set<ExplorerActivity> { scene.availableActivities }
322 func requestActivity(_ activity: ExplorerActivity) { setKeyboardControl(false); refreshTerrain(); scene.requestActivity(activity) }
323
324 func setRunWhenExploring(_ enabled: Bool) { scene.setRunWhenExploring(enabled) }
325 func setFasterRopeWork(_ enabled: Bool) { scene.setFasterRopeWork(enabled) }
326 func setGentlePace(_ gentle: Bool) { scene.playbackRate = gentle ? 0.65 : 1 }
327
328 func setSleeping(_ sleeping: Bool) {
329 policy.sleeping = sleeping
330 if !sleeping { updateDisplay(); checkDesktop() }
331 applyPolicy()
332 }
333
334 func desktopChanged() {
335 // Hide during the transition, then read the new Space rather than retaining old anchors.
336 desktopCheck?.cancel()
337 policy.desktopSupported = false
338 applyPolicy()
339 let work = DispatchWorkItem { [weak self] in
340 MainActor.assumeIsolated { self?.checkDesktop() }
341 }
342 desktopCheck = work
343 DispatchQueue.main.asyncAfter(deadline: .now() + 0.5, execute: work)
344 }
345
346 func checkDesktop() {
347 guard !policy.manuallyPaused, !policy.sleeping else { applyPolicy(); return }
348 guard let screen = NSScreen.screens.first else { return }
349 policy.desktopSupported = scene.agentMode || windowProvider.isSupportedDesktop(on: screen)
350 applyPolicy()
351 }
352
353 private func applyPolicy() {
354 if !policy.shouldRun { setKeyboardControl(false); featureCapture.stop(); supplementaryCapture.stop() }
355 if policy.shouldRun { refreshTerrain() }
356 scene.setExpeditionPaused(!policy.shouldRun)
357 if policy.shouldShow { show() }
358 else {
359 inputView.cancelDrag()
360 panel.orderOut(nil)
361 inputPanel.orderOut(nil)
362 }
363 updateRenderingPause()
364 }
365
366 private func updateRenderingPause(allowFinalFrame: Bool = false) {
367 renderPauseWork?.cancel()
368 if policy.shouldRun || (policy.shouldShow && characterHeld) { view.isPaused = false }
369 else if allowFinalFrame && policy.shouldShow {
370 // A paused drag still needs rendering, including its final release position.
371 view.isPaused = false
372 let work = DispatchWorkItem { [weak self] in
373 MainActor.assumeIsolated {
374 guard let self, !self.policy.shouldRun, !self.characterHeld else { return }
375 self.view.isPaused = true
376 }
377 }
378 renderPauseWork = work
379 DispatchQueue.main.asyncAfter(deadline: .now() + 0.06, execute: work)
380 } else { view.isPaused = true }
381 }
382
383 func resetExpedition() { setKeyboardControl(false); refreshTerrain(); scene.resetExpedition() }
384
385 func setDebugVisible(_ visible: Bool) { scene.setDebugVisible(visible) }
386
387 func close() {
388 keyboard.close()
389 desktopCheck?.cancel()
390 renderPauseWork?.cancel()
391 featureCapture.stop(); supplementaryCapture.stop(); featureTimer?.invalidate(); featureTimer = nil
392 terrainTimer?.invalidate()
393 terrainTimer = nil
394 inputView.cancelDrag()
395 scene.onPlacementChanged = nil
396 inputPanel.orderOut(nil)
397 panel.removeChildWindow(inputPanel)
398 inputPanel.close()
399 view.isPaused = true
400 view.presentScene(nil)
401 panel.orderOut(nil)
402 panel.close()
403 }
404 #if DEBUG
405 /// Tests our real AppKit panel/lifecycle integration without synthesising user input,
406 /// sleeping the machine, or changing Spaces on the user's desktop.
407 func runNativeChecks() -> Bool {
408 var passed = true
409 func check(_ condition: Bool, _ name: String) {
410 print("NATIVE \(condition ? "PASS" : "FAIL") \(name)")
411 passed = passed && condition
412 }
413 check(WindowProvider.isScreenRecorder(bundle: "com.apple.screencaptureui", owner: "Screenshot"), "Screenshot selection windows and toolbar are excluded from terrain")
414 check(WindowProvider.isScreenRecorder(bundle: nil, owner: "screencapture"), "the unbundled recording backdrop is excluded from terrain")
415 check(!WindowProvider.isScreenRecorder(bundle: "com.apple.QuickTimePlayerX", owner: "QuickTime Player"), "normal QuickTime playback windows retain their edges")
416 check(!WindowProvider.isScreenRecorder(bundle: nil, owner: "another helper"), "unrelated unbundled windows are not excluded")
417 let display = CGRect(x: 0, y: 0, width: 1710, height: 1107)
418 check(WindowProvider.isKeyboardBackdrop(bundle: "com.apple.inputmethod.AssistiveControl", layer: 2997, frame: display, display: display), "transparent accessibility keyboard backdrops do not occlude terrain")
419 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")
420 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")
421 check(!WindowProvider.isKeyboardBackdrop(bundle: "another.app", layer: 2997, frame: display, display: display), "other apps retain their real full-screen occluders")
422 let keyboardFrame = CGRect(x: 1048, y: 692, width: 598, height: 323)
423 let journalTerrain = NSPanel(contentRect: .init(x: 180, y: 120, width: 620, height: 480), styleMask: [.titled, .nonactivatingPanel], backing: .buffered, defer: false)
424 journalTerrain.isReleasedWhenClosed = false; journalTerrain.level = .floating
425 check(WindowProvider.isAppTerrainWindow(journalTerrain), "the journal is climbable terrain even when its panel floats above other windows")
426 check(!WindowProvider.isAppTerrainWindow(panel) && !WindowProvider.isAppTerrainWindow(inputPanel), "transparent explorer rendering and drag panels never become terrain")
427 journalTerrain.orderFrontRegardless(); journalTerrain.displayIfNeeded()
428 RunLoop.main.run(until: Date(timeIntervalSinceNow: 0.08))
429 let journalSnapshot = WindowProvider().snapshot(on: NSScreen.screens.first!)
430 check(journalSnapshot?.windows.contains { $0.id == UInt32(journalTerrain.windowNumber) && $0.canClimb } == true, "real app-owned journal panels survive window discovery in stacking order")
431 journalTerrain.close()
432 check(WindowProvider.canClimbWindow(bundle: "com.apple.inputmethod.AssistiveControl", layer: 101, frame: keyboardFrame), "the Accessibility Keyboard has climbable edges and can supply internal holds")
433 check(WindowProvider.canClimbWindow(bundle: "com.apple.KeyboardViewer", layer: 101, frame: keyboardFrame), "Keyboard Viewer floating panels have climbable edges")
434 check(!WindowProvider.canClimbWindow(bundle: "com.apple.inputmethod.AssistiveControl", layer: 2997, frame: display), "keyboard backdrops cannot become climbing or capture targets")
435 check(!WindowProvider.canClimbWindow(bundle: "another.app", layer: 101, frame: keyboardFrame), "unrelated floating overlays remain occluders only")
436 let focus = NSWorkspace.shared.frontmostApplication?.processIdentifier
437 let hatPart = PaintedPart(rect: .init(x: -12, y: 7, width: 24, height: 8), radius: 2, color: ExplorerPalette.hat, material: .felt)
438 check(panel.level.rawValue > Int(CGWindowLevelForKey(.dockWindow)), "explorer is layered above the system Dock")
439 check(hatPart.silhouettePath.boundingBoxOfPath == .init(x: -12, y: -4, width: 24, height: 8), "shadow silhouettes use sprite-local coordinates")
440 let shadowRig = ExplorerRig(), shadowSpace = SKNode()
441 shadowSpace.addChild(shadowRig); shadowRig.position = .init(x: 200, y: 200)
442 shadowRig.setShadowOcclusion(windows: [.init(x: 180, y: 0, width: 200, height: 200)], from: shadowSpace)
443 check(shadowRig.shadowIsVisible(at: .init(x: 0, y: 20)) && !shadowRig.shadowIsVisible(at: .init(x: 0, y: -1)), "supporting window hides shadow beneath its lip")
444 shadowRig.xScale = -1
445 shadowRig.setShadowOcclusion(windows: [.init(x: 180, y: 0, width: 200, height: 200)], from: shadowSpace)
446 check(!shadowRig.shadowIsVisible(at: .init(x: -50, y: -1)) && shadowRig.shadowIsVisible(at: .init(x: 50, y: -1)), "ledge shadow clipping survives mirrored facing")
447 shadowRig.position.y = 180
448 shadowRig.setShadowOcclusion(windows: [.init(x: 180, y: 0, width: 200, height: 200)], from: shadowSpace)
449 check(shadowRig.shadowIsVisible(at: .init(x: 0, y: -1)), "hanging in front of a window keeps its cast shadow")
450 var crackClamps = 0
451 for horizontal in [true, false] {
452 for step in 0..<120 {
453 shadowRig.crackPose = CrackAnimation.pose(horizontal: horizontal, time: Double(step) / 60, offset: Double(step))
454 shadowRig.select(.climbing); shadowRig.render(delta: 0.1)
455 crackClamps += shadowRig.clampedContacts
456 }
457 }
458 check(crackClamps == 0, "crack traverse and vertical climbing stay inside limb reach")
459 shadowRig.crackPose = nil
460 var crouchClamps = 0
461 for step in 0..<120 {
462 shadowRig.crouchAmount = Double(step % 30) / 29
463 shadowRig.select(.walking); shadowRig.synchronizedTime = Double(step) / 60
464 shadowRig.render(delta: 1.0 / 60)
465 crouchClamps += shadowRig.clampedContacts
466 }
467 check(crouchClamps == 0, "crouched walking keeps knees and reaching arms inside limb reach")
468 shadowRig.crouchAmount = 0
469 show()
470 check(panel.isVisible && inputPanel.isVisible, "both panels visible")
471 check(panel.ignoresMouseEvents && !inputPanel.ignoresMouseEvents, "input confined to body panel")
472 check(!panel.canBecomeKey && !inputPanel.canBecomeKey, "panels cannot take keyboard focus")
473 check(inputPanel.frame.width == 48 && inputPanel.frame.height == 76, "body-only hit area")
474 setPaused(true)
475 check(!policy.shouldPollTerrain && view.isPaused, "explicit pause suspends polling and scene")
476 let pausedPolls = terrainRefreshCount
477 RunLoop.main.run(until: Date(timeIntervalSinceNow: 0.3))
478 check(terrainRefreshCount == pausedPolls, "paused timer performs no geometry reads")
479 let original = inputPanel.frame
480 let grab = CGPoint(x: original.midX, y: original.midY)
481 inputView.onBegin?(grab)
482 inputView.onDrag?(CGPoint(x: grab.x + 60, y: grab.y + 30))
483 check(abs(inputPanel.frame.midX - original.midX - 60) < 0.1, "paused drag callback moves body panel")
484 check(!view.isPaused && !policy.shouldRun, "paused drag renders without advancing simulation")
485 inputView.onEnd?()
486 // First-use mask/blur pipeline compilation can delay the final frame.
487 let finalFrameDeadline = Date(timeIntervalSinceNow: 0.75)
488 while !view.isPaused && Date() < finalFrameDeadline {
489 RunLoop.main.run(until: Date(timeIntervalSinceNow: 0.02))
490 }
491 check(view.isPaused, "paused release renders final frame then stops")
492 setSleeping(true)
493 check(!panel.isVisible && !inputPanel.isVisible, "sleep hides all panels")
494 setSleeping(false)
495 check(policy.manuallyPaused && !policy.shouldRun, "wake preserves explicit pause")
496 policy.desktopSupported = false
497 applyPolicy()
498 check(!panel.isVisible && !inputPanel.isVisible && !policy.shouldPollTerrain, "unsupported desktop is hidden and suspended")
499 policy.desktopSupported = true
500 setPaused(false)
501 check(policy.shouldRun && panel.isVisible && inputPanel.isVisible, "return refreshes and resumes")
502 resetExpedition()
503 check(NSWorkspace.shared.frontmostApplication?.processIdentifier == focus, "launch/reset/lifecycle preserve frontmost app")
504 let previousApp = NSWorkspace.shared.frontmostApplication
505 var direction = CGPoint.zero, aimDirection = CGPoint.zero, jumps = 0, clicks = 0, shots = 0, aiming = false, fastPace = false
506 let tester = ExplorerKeyboardController()
507 tester.onDirection = { x, y in direction = .init(x: x, y: y) }
508 tester.onJump = { jumps += 1 }
509 tester.onFastPace = { fastPace = $0 }
510 tester.onInteract = { clicks += 1 }
511 tester.onAimChanged = { aiming = $0 }
512 tester.onAimDirection = { x, y in aimDirection = .init(x: x, y: y) }
513 var crouching = false
514 tester.onCrouch = { crouching = $0 }
515 tester.onGrapple = { shots += 1 }
516 tester.start()
517 RunLoop.main.run(until: Date(timeIntervalSinceNow: 0.08))
518 check(tester.isControlling && tester.panel.canBecomeKey && !panel.canBecomeKey, "manual mode has a dedicated keyboard input target")
519 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")
520 func key(_ code: UInt16, down: Bool = true, repeatKey: Bool = false, flags: NSEvent.ModifierFlags = []) -> NSEvent {
521 NSEvent.keyEvent(with: down ? .keyDown : .keyUp, location: .zero, modifierFlags: flags, timestamp: 0, windowNumber: tester.panel.windowNumber, context: nil, characters: "", charactersIgnoringModifiers: "", isARepeat: repeatKey, keyCode: code)!
522 }
523 check(tester.routeKey(key(124)) == nil && direction.x == 1, "arrow key is consumed and starts player movement")
524 _ = tester.routeKey(key(0))
525 check(direction.x == 0, "opposite movement keys cancel")
526 _ = tester.routeKey(key(0, down: false)); _ = tester.routeKey(key(124, down: false))
527 check(direction == .zero, "key release clears movement")
528 _ = tester.routeKey(key(124, flags: .shift))
529 check(fastPace && direction.x == 1, "Shift movement enables fast pace without clearing directions")
530 _ = tester.routeKey(key(124, down: false))
531 check(!fastPace && direction == .zero, "releasing Shift restores normal pace")
532 _ = tester.routeKey(key(8))
533 check(crouching && direction == .zero, "holding C crouches without stepping off the ledge")
534 _ = tester.routeKey(key(14))
535 check(crouching && clicks == 1 && tester.isControlling, "E retains crouch and manual control")
536 _ = tester.routeKey(key(8, down: false))
537 check(!crouching, "releasing C restores standing posture")
538 _ = tester.routeKey(key(49)); _ = tester.routeKey(key(49, repeatKey: true))
539 _ = tester.routeKey(key(14)); _ = tester.routeKey(key(14, repeatKey: true))
540 check(jumps == 1 && clicks == 2, "jump and click fire once rather than on key repeat")
541 check(tester.routeKey(key(14, flags: .command)) != nil && clicks == 2, "command shortcuts pass through without clicking")
542 _ = tester.routeKey(key(5)); _ = tester.routeKey(key(5, repeatKey: true))
543 check(aiming && shots == 0, "holding G aims without firing or repeating")
544 _ = tester.routeKey(key(124))
545 check(aimDirection.x == 1 && direction == .zero, "G plus Right adjusts aim without moving or pumping the explorer")
546 _ = tester.routeKey(key(126))
547 check(aimDirection == .init(x: 1, y: 1) && direction == .zero, "G plus arrows supports diagonal aim")
548 _ = tester.routeKey(key(5, down: false))
549 check(!aiming && shots == 1, "releasing G fires one aimed shot")
550 check(aimDirection == .zero && direction == .init(x: 1, y: 1), "releasing G restores held arrows to movement")
551 _ = tester.routeKey(key(124, down: false)); _ = tester.routeKey(key(126, down: false))
552 var prompts = 0
553 tester.onPrompt = { prompts += 1 }
554 _ = tester.routeKey(key(124, flags: .shift))
555 _ = tester.routeKey(key(36)); _ = tester.routeKey(key(36, repeatKey: true)); _ = tester.routeKey(key(36, down: false))
556 check(prompts == 1 && direction == .zero && !fastPace, "Return opens one prompt and clears held movement and pace")
557 check(tester.routeKey(key(36, flags: .command)) != nil && prompts == 1, "modified Return passes through without opening a prompt")
558 tester.beginClick()
559 tester.windowDidResignKey(Notification(name: NSWindow.didResignKeyNotification, object: tester.panel))
560 check(tester.isControlling && tester.isPerformingClick, "click-induced focus loss preserves keyboard session")
561 _ = tester.routeKey(key(53))
562 check(!tester.isControlling && !tester.panel.isVisible && direction == .zero, "Escape ends capture and clears held directions")
563 tester.close()
564 check(ExplorerDesktopClick.quartzPoint(.init(x: 120, y: 240), primaryTop: 900) == .init(x: 120, y: 660), "click marker converts to Quartz coordinates")
565 if !ExplorerDesktopClick.hasAccess {
566 check(ExplorerDesktopClick.press(at: .zero).hasPrefix("Allow"), "desktop click is gated without Accessibility permission")
567 }
568 print("NATIVE INFO Accessibility permission: \(ExplorerDesktopClick.hasAccess)")
569 previousApp?.activate(options: [])
570 close()
571 check(!panel.isVisible && !inputPanel.isVisible && terrainTimer == nil, "close removes panels and timer")
572 return passed
573 }
574 #endif
575
576}