Skip to content

Commit

Permalink
fix: keyboard events don't stop being listened to (closes #18)
Browse files Browse the repository at this point in the history
  • Loading branch information
Louis Pontoise committed Oct 4, 2019
1 parent f9f4565 commit 75db5e9
Showing 1 changed file with 23 additions and 17 deletions.
40 changes: 23 additions & 17 deletions alt-tab-macos/logic/Keyboard.swift
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
import Cocoa

var eventTap: CFMachPort?

func listenToGlobalKeyboardEvents(_ delegate: Application) {
let eventMask = [CGEventType.keyDown, CGEventType.keyUp, CGEventType.flagsChanged].reduce(CGEventMask(0), { $0 | (1 << $1.rawValue) })
let eventTap = CGEvent.tapCreate(
eventTap = CGEvent.tapCreate(
tap: .cgSessionEventTap,
place: .headInsertEventTap,
options: .defaultTap,
Expand All @@ -19,23 +21,27 @@ func listenToGlobalKeyboardEvents(_ delegate: Application) {
}

func keyboardHandler(_ cgEvent: CGEvent, _ delegate: Application) -> Unmanaged<CGEvent>? {
if cgEvent.type == .keyDown || cgEvent.type == .keyUp || cgEvent.type == .flagsChanged, let event = NSEvent.init(cgEvent: cgEvent) {
let keyDown = event.type == .keyDown
let optionKeyEvent = event.keyCode == metaKey
let tabKeyEvent = event.keyCode == tabKey
if optionKeyEvent && event.modifiersDown([metaModifierFlag]) {
delegate.keyDownMeta()
} else if tabKeyEvent && event.modifiersDown([metaModifierFlag]) && keyDown {
delegate.keyDownMetaTab()
// focused app will not receive the event (will not press tab key in that app)
return nil
} else if tabKeyEvent && event.modifiersDown([metaModifierFlag, .shift]) && keyDown {
delegate.keyDownMetaShiftTab()
// focused app will not receive the event (will not press tab key in that app)
return nil
} else if optionKeyEvent && !keyDown {
delegate.keyUpMeta()
if cgEvent.type == .keyDown || cgEvent.type == .keyUp || cgEvent.type == .flagsChanged {
if let event = NSEvent.init(cgEvent: cgEvent) {
let keyDown = event.type == .keyDown
let optionKeyEvent = event.keyCode == metaKey
let tabKeyEvent = event.keyCode == tabKey
if optionKeyEvent && event.modifiersDown([metaModifierFlag]) {
delegate.keyDownMeta()
} else if tabKeyEvent && event.modifiersDown([metaModifierFlag]) && keyDown {
delegate.keyDownMetaTab()
// focused app will not receive the event (will not press tab key in that app)
return nil
} else if tabKeyEvent && event.modifiersDown([metaModifierFlag, .shift]) && keyDown {
delegate.keyDownMetaShiftTab()
// focused app will not receive the event (will not press tab key in that app)
return nil
} else if optionKeyEvent && !keyDown {
delegate.keyUpMeta()
}
}
} else if cgEvent.type == .tapDisabledByUserInput || cgEvent.type == .tapDisabledByTimeout {
CGEvent.tapEnable(tap: eventTap!, enable: true)
}
// focused app will receive the event
return Unmanaged.passRetained(cgEvent)
Expand Down

0 comments on commit 75db5e9

Please sign in to comment.