diff --git a/slab/menuband/Sources/MenuBand/LocalKeyCapture.swift b/slab/menuband/Sources/MenuBand/LocalKeyCapture.swift index 9cd03b5e6b..13f6b393ff 100644 --- a/slab/menuband/Sources/MenuBand/LocalKeyCapture.swift +++ b/slab/menuband/Sources/MenuBand/LocalKeyCapture.swift @@ -85,6 +85,18 @@ final class LocalKeyCapture { !hasKeyWindow && (!keepsCaptureArmed || !hasProtectedTrackDrumInput) } + /// While percussion owns the trackpad, a tap-to-click that lands on our + /// own menu bar piano is still a drum hit, not a press: the hidden + /// pointer often rests there. Treating it as a status-item press waits + /// for a `statusClicked` that the local click shield swallows, and the + /// orphan check then drops focus 0.3 s later. Reclaim instead. + static func shouldReclaimCaptureAfterResign( + keepsCaptureArmed: Bool, + hasProtectedTrackDrumInput: Bool + ) -> Bool { + keepsCaptureArmed && hasProtectedTrackDrumInput + } + /// TrackDrum contacts arrive just before AppKit synthesizes a click from /// the same physical tap. Protect only that narrow handoff, so an external /// mouse click or keyboard app switch still exits focused performance. @@ -171,7 +183,13 @@ final class LocalKeyCapture { SessionDiagnostics.shared.record(.captureResigned, reason: .resignedKey, source: .localCapture, state: stillKeyInApp) guard !stillKeyInApp else { return } - if self.isOwnStatusItemPress?() == true { + let protectedInput = CACurrentMediaTime() <= self.protectedResignUntil + let ownPress = self.isOwnStatusItemPress?() == true + debugLog("capture resigned: ownStatusItemPress=\(ownPress) trackDrumProtected=\(protectedInput) keepsArmed=\(self.keepsCaptureArmedOnResign) buttons=\(NSEvent.pressedMouseButtons) appActive=\(NSApp.isActive)") + if ownPress, !Self.shouldReclaimCaptureAfterResign( + keepsCaptureArmed: self.keepsCaptureArmedOnResign, + hasProtectedTrackDrumInput: protectedInput + ) { // A press on our own piano. Hold capture through the // click; `statusClicked` re-arms after the mouse-up. // If the press ends and nothing re-keyed us, let go. @@ -231,6 +249,15 @@ final class LocalKeyCapture { } let keyInApp = NSApp.windows.contains { $0.isKeyWindow } if !keyInApp && !NSApp.isActive { + if Self.shouldReclaimCaptureAfterResign( + keepsCaptureArmed: self.keepsCaptureArmedOnResign, + hasProtectedTrackDrumInput: CACurrentMediaTime() <= self.protectedResignUntil + ) { + SessionDiagnostics.shared.record(.capturePreserved, reason: .trackDrumShield, source: .localCapture) + debugLog("status-item press orphaned during trackpad percussion — reclaiming capture") + self.arm() + return + } SessionDiagnostics.shared.record(.focusExitRequested, reason: .statusItemOrphaned, source: .localCapture) self.disarm(reason: .resignedKey) } diff --git a/slab/menuband/Sources/MenuBand/MenuBandController.swift b/slab/menuband/Sources/MenuBand/MenuBandController.swift index 9bbf4d15e9..c07bbbfbc3 100644 --- a/slab/menuband/Sources/MenuBand/MenuBandController.swift +++ b/slab/menuband/Sources/MenuBand/MenuBandController.swift @@ -257,6 +257,19 @@ final class MenuBandController { /// hammer stays one ←/→-while-Space step away. private var spaceMode: SpaceMode = .reverse private var spaceKeyHeld = false + /// The reverse clip is a one-shot of up to `captureSeconds` (90 s), so a + /// Space key-up that never arrives — Tab's pad handoff, a focus change + /// under the held key — leaves it playing for over a minute. While Space + /// is held this polls the physical key and ends the gesture itself the + /// moment the key is really up. Armed only when the key-state read + /// agreed with the key-down, so a keyboard the API can't see never has + /// its real hold cut short. + private var spaceWatchdog: Timer? + private var spaceKeyStateTrusted = false + private static let spaceKeyCode = CGKeyCode(49) + private static func physicalSpaceIsDown() -> Bool { + CGEventSource.keyState(.hidSystemState, key: spaceKeyCode) + } /// Space hammer. HOLDING Space in hammer mode re-strikes whatever notes /// are held or latched like a randomized hammer: stochastic timing @@ -3985,6 +3998,14 @@ final class MenuBandController { // Handed ⌘/⌥: a modifier held by the other hand leaves this key a // plain note, and that note is consumed — it must never fall through // to the focused app as a shortcut. + // A Space key-up can go missing when the capture route changes + // under a held key. The physical key state is the truth: if Space is + // up on the keyboard but still held here, end it before this key. + if spaceKeyHeld, spaceKeyStateTrusted, keyCode != 49, isDown, !isRepeat, + !Self.physicalSpaceIsDown() { + debugLog("space key-up never arrived; ending \(spaceMode.rawValue) on key \(keyCode)") + endSpace() + } let chord = Self.chordFlags(rawFlags: flags.rawValue, hand: chordHand(forKeyCode: keyCode)) let hasMod = chord.modifier @@ -4780,17 +4801,44 @@ final class MenuBandController { /// Space went down: start whatever the current mode does. private func beginSpace() { spaceKeyHeld = true - debugLog("space down mode=\(spaceMode.rawValue)") + spaceKeyStateTrusted = Self.physicalSpaceIsDown() + debugLog("space down mode=\(spaceMode.rawValue) hidKeyState=\(spaceKeyStateTrusted)") switch spaceMode { case .reverse: rewind() case .hammer: beginHammer() } + if spaceKeyStateTrusted { startSpaceWatchdog() } + } + + private func startSpaceWatchdog() { + DispatchQueue.main.async { [weak self] in + guard let self, self.spaceKeyHeld else { return } + self.spaceWatchdog?.invalidate() + let timer = Timer(timeInterval: 0.1, repeats: true) { [weak self] _ in + guard let self else { return } + guard self.spaceKeyHeld else { self.stopSpaceWatchdog(); return } + if !Self.physicalSpaceIsDown() { + debugLog("space watchdog: key is up but no key-up arrived — ending \(self.spaceMode.rawValue)") + self.endSpace() + } + } + RunLoop.main.add(timer, forMode: .common) + self.spaceWatchdog = timer + } + } + + private func stopSpaceWatchdog() { + spaceWatchdog?.invalidate() + spaceWatchdog = nil } /// Space came up: end the current mode's gesture. Each end is safe to /// call when nothing began (a key-up after a mode switch, say). private func endSpace() { spaceKeyHeld = false + debugLog("space up mode=\(spaceMode.rawValue)") + if Thread.isMainThread { stopSpaceWatchdog() } + else { DispatchQueue.main.async { [weak self] in self?.stopSpaceWatchdog() } } switch spaceMode { case .reverse: rewindRelease() case .hammer: endHammer() @@ -5008,6 +5056,14 @@ final class MenuBandController { } func releaseAllHeldNotes() { + // A blanket release also lets go of Space. Focus loss, Tab's pad + // handoff and the panic path all land here, and any of them can + // swallow the key-up that would have ended the dive or the hammer — + // the reverse then plays on with nothing holding it. + if spaceKeyHeld { + debugLog("release-all ends held Space") + endSpace() + } cancelHammer() heldLock.lock() let noteSnapshot = heldNotes diff --git a/slab/menuband/Sources/MenuBand/SessionDiagnosticObservers.swift b/slab/menuband/Sources/MenuBand/SessionDiagnosticObservers.swift index 2c0d4ca22a..5410da9bb0 100644 --- a/slab/menuband/Sources/MenuBand/SessionDiagnosticObservers.swift +++ b/slab/menuband/Sources/MenuBand/SessionDiagnosticObservers.swift @@ -36,8 +36,14 @@ final class SessionDiagnosticObservers { let token = workspace.addObserver(forName: NSWorkspace.didActivateApplicationNotification, object: nil, queue: .main) { notification in let app = notification.userInfo?[NSWorkspace.applicationUserInfoKey] as? NSRunningApplication - diagnostics.record(.workspaceActivation, - state: app?.processIdentifier == ProcessInfo.processInfo.processIdentifier) + let isSelf = app?.processIdentifier == ProcessInfo.processInfo.processIdentifier + diagnostics.record(.workspaceActivation, state: isSelf) + if !isSelf { + // Which app took the front is the one fact a defocus + // post-mortem always needs; the ledger carries no identifiers, + // so it goes to the debug log. + debugLog("workspace activated: \(app?.bundleIdentifier ?? "?") pid=\(app?.processIdentifier ?? -1)") + } } observers.append((workspace, token)) } diff --git a/slab/menuband/Sources/MenuBand/SessionDiagnostics.swift b/slab/menuband/Sources/MenuBand/SessionDiagnostics.swift index 97a11e6f51..fd1aec1af5 100644 --- a/slab/menuband/Sources/MenuBand/SessionDiagnostics.swift +++ b/slab/menuband/Sources/MenuBand/SessionDiagnostics.swift @@ -23,7 +23,7 @@ final class SessionDiagnostics { case invalidOutput, stalledOutput, engineStopped } enum Source: String, Codable { - case app, localCapture, globalKeyboard, commandSpace, bendTab, quietFocus, audio + case app, localCapture, globalKeyboard, commandSpace, bendTab, quietFocus, audio, gestureTap } struct Row: Codable { let schema: Int diff --git a/slab/menuband/Sources/MenuBand/Shapedown.swift b/slab/menuband/Sources/MenuBand/Shapedown.swift index caf7c2bc6a..8f05712fcf 100644 --- a/slab/menuband/Sources/MenuBand/Shapedown.swift +++ b/slab/menuband/Sources/MenuBand/Shapedown.swift @@ -302,7 +302,18 @@ final class ShapedownGestureTap { guard let refcon else { return Unmanaged.passUnretained(event) } let me = Unmanaged.fromOpaque(refcon).takeUnretainedValue() if type == .tapDisabledByTimeout || type == .tapDisabledByUserInput { - if let tap = me.tap { CGEvent.tapEnable(tap: tap, enable: true) } + // A disabled shield passes the trackpad's synthesized clicks + // straight to whatever sits under the hidden pointer; the + // ledger has to show that window so a defocus can be read. + SessionDiagnostics.shared.record(.tapDisabled, + reason: type == .tapDisabledByTimeout ? .timeout : .userInput, + source: .gestureTap) + if let tap = me.tap { + CGEvent.tapEnable(tap: tap, enable: true) + SessionDiagnostics.shared.record(.tapReenabled, source: .gestureTap, + state: CGEvent.tapIsEnabled(tap: tap)) + } + debugLog("trackpad click shield tap disabled (\(type.rawValue)) — re-enabled") return Unmanaged.passUnretained(event) } if type == .leftMouseDown { @@ -360,9 +371,11 @@ final class ShapedownGestureTap { self.thread = thread let started = ready.wait(timeout: .now() + 0.25) == .success guard started, CGEvent.tapIsEnabled(tap: tap) else { + SessionDiagnostics.shared.record(.tapFailed, source: .gestureTap) stop() return false } + SessionDiagnostics.shared.record(.tapStarted, source: .gestureTap) return true } diff --git a/slab/menuband/Tests/MenuBandTests/ShapedownTests.swift b/slab/menuband/Tests/MenuBandTests/ShapedownTests.swift index a75d88b7a5..f0a1e55f26 100644 --- a/slab/menuband/Tests/MenuBandTests/ShapedownTests.swift +++ b/slab/menuband/Tests/MenuBandTests/ShapedownTests.swift @@ -387,6 +387,26 @@ final class ShapedownTests: XCTestCase { ) } + func testTrackDrumTapOnOwnStatusItemReclaimsCapture() { + // Tap-to-click during percussion, hidden pointer parked on the + // menu bar piano: reclaim rather than wait for a swallowed click. + XCTAssertTrue(LocalKeyCapture.shouldReclaimCaptureAfterResign( + keepsCaptureArmed: true, + hasProtectedTrackDrumInput: true + )) + // A real press on the piano outside percussion keeps the old path. + XCTAssertFalse(LocalKeyCapture.shouldReclaimCaptureAfterResign( + keepsCaptureArmed: false, + hasProtectedTrackDrumInput: true + )) + // Percussion armed, but no tap in the protected window: an external + // click or app switch still exits. + XCTAssertFalse(LocalKeyCapture.shouldReclaimCaptureAfterResign( + keepsCaptureArmed: true, + hasProtectedTrackDrumInput: false + )) + } + func testTrackDrumShieldClickDoesNotEndFocusedCapture() { XCTAssertFalse(LocalKeyCapture.shouldEndCaptureAfterResign( hasKeyWindow: false,