|
| 1 | +// Copyright [2016] Jean Helou |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | +// you may not use this file except in compliance with the License. |
| 5 | +// You may obtain a copy of the License at |
| 6 | +// |
| 7 | +// http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | +// |
| 9 | +// Unless required by applicable law or agreed to in writing, software |
| 10 | +// distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | +// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | +// See the License for the specific language governing permissions and |
| 13 | +// limitations under the License. |
| 14 | + |
| 15 | +import Carbon |
| 16 | +import Foundation |
| 17 | +import IOKit |
| 18 | +import IOKit.hid |
| 19 | +import IOKit.usb |
| 20 | + |
| 21 | +internal final class IOKeyEventMonitor { |
| 22 | + private let hidManager: IOHIDManager |
| 23 | + fileprivate let MAPPINGS_DEFAULTS_KEY = "keyboardISMapping" |
| 24 | + fileprivate let notificationCenter: CFNotificationCenter |
| 25 | + fileprivate var lastActiveKeyboard: String = "" |
| 26 | + fileprivate var kb2is: [String: TISInputSource] = [String: TISInputSource]() |
| 27 | + fileprivate var defaults: UserDefaults = UserDefaults.standard |
| 28 | + fileprivate var useLocation: Bool |
| 29 | + fileprivate var verbosity: Int |
| 30 | + |
| 31 | + init? (usagePage: Int, usage: Int, useLocation: Bool, verbosity: Int) { |
| 32 | + self.useLocation = useLocation |
| 33 | + self.verbosity = verbosity |
| 34 | + hidManager = IOHIDManagerCreate(kCFAllocatorDefault, IOOptionBits(kIOHIDOptionsTypeNone)) |
| 35 | + notificationCenter = CFNotificationCenterGetDistributedCenter() |
| 36 | + let deviceMatch: CFMutableDictionary = [kIOHIDDeviceUsageKey: usage, kIOHIDDeviceUsagePageKey: usagePage] as NSMutableDictionary |
| 37 | + IOHIDManagerSetDeviceMatching(hidManager, deviceMatch) |
| 38 | + loadMappings() |
| 39 | + } |
| 40 | + |
| 41 | + deinit { |
| 42 | + self.saveMappings() |
| 43 | + let context = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque()) |
| 44 | + IOHIDManagerRegisterInputValueCallback(hidManager, Optional.none, context) |
| 45 | + CFNotificationCenterRemoveObserver(notificationCenter, context, CFNotificationName(kTISNotifySelectedKeyboardInputSourceChanged), nil) |
| 46 | + } |
| 47 | + |
| 48 | + func start() { |
| 49 | + let context = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque()) |
| 50 | + |
| 51 | + observeIputSourceChangedNotification(context: context) |
| 52 | + registerHIDKeyboardCallback(context: context) |
| 53 | + |
| 54 | + IOHIDManagerScheduleWithRunLoop(hidManager, CFRunLoopGetMain(), CFRunLoopMode.defaultMode!.rawValue) |
| 55 | + IOHIDManagerOpen(hidManager, IOOptionBits(kIOHIDOptionsTypeNone)) |
| 56 | + } |
| 57 | + |
| 58 | + private func observeIputSourceChangedNotification(context: UnsafeMutableRawPointer) { |
| 59 | + let inputSourceChanged: CFNotificationCallback = { |
| 60 | + _, observer, _, _, _ in |
| 61 | + let selfPtr = Unmanaged<IOKeyEventMonitor>.fromOpaque(observer!).takeUnretainedValue() |
| 62 | + selfPtr.onInputSourceChanged() |
| 63 | + } |
| 64 | + |
| 65 | + CFNotificationCenterAddObserver(notificationCenter, |
| 66 | + context, inputSourceChanged, |
| 67 | + kTISNotifySelectedKeyboardInputSourceChanged, nil, |
| 68 | + CFNotificationSuspensionBehavior.deliverImmediately) |
| 69 | + } |
| 70 | + |
| 71 | + private func registerHIDKeyboardCallback(context: UnsafeMutableRawPointer) { |
| 72 | + let myHIDKeyboardCallback: IOHIDValueCallback = { |
| 73 | + context, _, sender, _ in |
| 74 | + let selfPtr = Unmanaged<IOKeyEventMonitor>.fromOpaque(context!).takeUnretainedValue() |
| 75 | + let senderDevice = Unmanaged<IOHIDDevice>.fromOpaque(sender!).takeUnretainedValue() |
| 76 | + |
| 77 | + let vendorId = IOHIDDeviceGetProperty(senderDevice, kIOHIDVendorIDKey as CFString) ??? "unknown" |
| 78 | + let productId = IOHIDDeviceGetProperty(senderDevice, kIOHIDProductIDKey as CFString) ??? "unknown" |
| 79 | + let product = IOHIDDeviceGetProperty(senderDevice, kIOHIDProductKey as CFString) ??? "unknown" |
| 80 | + let manufacturer = IOHIDDeviceGetProperty(senderDevice, kIOHIDManufacturerKey as CFString) ??? "unknown" |
| 81 | + let serialNumber = IOHIDDeviceGetProperty(senderDevice, kIOHIDSerialNumberKey as CFString) ??? "unknown" |
| 82 | + let locationId = IOHIDDeviceGetProperty(senderDevice, kIOHIDLocationIDKey as CFString) ??? "unknown" |
| 83 | + let uniqueId = IOHIDDeviceGetProperty(senderDevice, kIOHIDUniqueIDKey as CFString) ??? "unknown" |
| 84 | + |
| 85 | + let keyboard = selfPtr.useLocation |
| 86 | + ? "\(product)-[\(vendorId)-\(productId)-\(manufacturer)-\(serialNumber)-\(locationId)]" |
| 87 | + : "\(product)-[\(vendorId)-\(productId)-\(manufacturer)-\(serialNumber)]" |
| 88 | + |
| 89 | + if selfPtr.verbosity >= TRACE { |
| 90 | + print("received event from keyboard \(keyboard) - \(locationId) - \(uniqueId)") |
| 91 | + } |
| 92 | + selfPtr.onKeyboardEvent(keyboard: keyboard) |
| 93 | + } |
| 94 | + |
| 95 | + IOHIDManagerRegisterInputValueCallback(hidManager, myHIDKeyboardCallback, context) |
| 96 | + } |
| 97 | +} |
| 98 | + |
| 99 | +extension IOKeyEventMonitor { |
| 100 | + func restoreInputSource(keyboard: String) { |
| 101 | + if let targetIs = kb2is[keyboard] { |
| 102 | + if verbosity >= DEBUG { |
| 103 | + print("set input source to \(targetIs) for keyboard \(keyboard)") |
| 104 | + } |
| 105 | + TISSelectInputSource(targetIs) |
| 106 | + } else { |
| 107 | + storeInputSource(keyboard: keyboard) |
| 108 | + } |
| 109 | + } |
| 110 | + |
| 111 | + func storeInputSource(keyboard: String) { |
| 112 | + let currentSource: TISInputSource = TISCopyCurrentKeyboardInputSource().takeUnretainedValue() |
| 113 | + kb2is[keyboard] = currentSource |
| 114 | + saveMappings() |
| 115 | + } |
| 116 | + |
| 117 | + func onInputSourceChanged() { |
| 118 | + storeInputSource(keyboard: lastActiveKeyboard) |
| 119 | + } |
| 120 | + |
| 121 | + func onKeyboardEvent(keyboard: String) { |
| 122 | + guard lastActiveKeyboard != keyboard else { return } |
| 123 | + |
| 124 | + restoreInputSource(keyboard: keyboard) |
| 125 | + lastActiveKeyboard = keyboard |
| 126 | + } |
| 127 | + |
| 128 | + func loadMappings() { |
| 129 | + let selectableIsProperties = [ |
| 130 | + kTISPropertyInputSourceIsEnableCapable: true, |
| 131 | + kTISPropertyInputSourceCategory: kTISCategoryKeyboardInputSource, |
| 132 | + ] as CFDictionary |
| 133 | + let inputSources = TISCreateInputSourceList(selectableIsProperties, false).takeUnretainedValue() as! Array<TISInputSource> |
| 134 | + |
| 135 | + let inputSourcesById = inputSources.reduce([String: TISInputSource]()) { |
| 136 | + (dict, inputSource) -> [String: TISInputSource] in |
| 137 | + var dict = dict |
| 138 | + if let id = unmanagedStringToString(TISGetInputSourceProperty(inputSource, kTISPropertyInputSourceID)) { |
| 139 | + dict[id] = inputSource |
| 140 | + } |
| 141 | + return dict |
| 142 | + } |
| 143 | + |
| 144 | + if let mappings = self.defaults.dictionary(forKey: MAPPINGS_DEFAULTS_KEY) { |
| 145 | + for (keyboardId, inputSourceId) in mappings { |
| 146 | + kb2is[keyboardId] = inputSourcesById[String(describing: inputSourceId)] |
| 147 | + } |
| 148 | + } |
| 149 | + } |
| 150 | + |
| 151 | + func saveMappings() { |
| 152 | + let mappings = kb2is.mapValues(is2Id) |
| 153 | + defaults.set(mappings, forKey: MAPPINGS_DEFAULTS_KEY) |
| 154 | + } |
| 155 | + |
| 156 | + private func is2Id(_ inputSource: TISInputSource) -> String? { |
| 157 | + return unmanagedStringToString(TISGetInputSourceProperty(inputSource, kTISPropertyInputSourceID))! |
| 158 | + } |
| 159 | + |
| 160 | + func unmanagedStringToString(_ p: UnsafeMutableRawPointer?) -> String? { |
| 161 | + if let cfValue = p { |
| 162 | + let value = Unmanaged.fromOpaque(cfValue).takeUnretainedValue() as CFString |
| 163 | + if CFGetTypeID(value) == CFStringGetTypeID() { |
| 164 | + return value as String |
| 165 | + } else { |
| 166 | + return nil |
| 167 | + } |
| 168 | + } else { |
| 169 | + return nil |
| 170 | + } |
| 171 | + } |
| 172 | +} |
| 173 | + |
| 174 | +// Nicer string interpolation of optional strings, see: https://oleb.net/blog/2016/12/optionals-string-interpolation/ |
| 175 | + |
| 176 | +infix operator ???: NilCoalescingPrecedence |
| 177 | + |
| 178 | +public func ???<T>(optional: T?, defaultValue: @autoclosure () -> String) -> String { |
| 179 | + return optional.map { String(describing: $0) } ?? defaultValue() |
| 180 | +} |
0 commit comments