Repository: ohueter/autokbisw Branch: master Commit: 56b6a2b4d268 Files: 11 Total size: 53.8 KB Directory structure: gitextract_uxgfe4hp/ ├── .github/ │ └── workflows/ │ ├── release.yml │ └── test.yml ├── .gitignore ├── LICENSE ├── Package.resolved ├── Package.swift ├── README.md ├── Sources/ │ ├── AutokbiswCore/ │ │ ├── IOKeyEventMonitor.swift │ │ └── Logger.swift │ └── autokbisw/ │ └── main.swift └── Tests/ └── autokbiswTests/ └── IOKeyEventMonitorTests.swift ================================================ FILE CONTENTS ================================================ ================================================ FILE: .github/workflows/release.yml ================================================ name: Publish on: push: tags: - '*' jobs: publish: name: Publish binaries for ${{ matrix.os }} ${{ matrix.os_name }} (${{ matrix.arch }}) runs-on: ${{ matrix.os }} strategy: matrix: os: [macos-13, macos-14, macos-15] arch: [arm64, x86_64] include: - os: macos-13 os_name: ventura - os: macos-14 os_name: sonoma - os: macos-15 os_name: sequoia steps: - uses: actions/checkout@v3 - name: Build binary run: swift build --configuration release --arch ${{ matrix.arch }} - name: Generate archive name uses: haya14busa/action-cond@v1 id: archive-name with: cond: ${{ matrix.arch == 'arm64' }} if_true: autokbisw-${{github.ref_name}}.arm64_${{ matrix.os_name }}.tar.gz if_false: autokbisw-${{github.ref_name}}.${{ matrix.os_name }}.tar.gz - name: Create archive run: | cd .build/release tar -czf ${{ steps.archive-name.outputs.value }} autokbisw - name: Generate checksum run: | cd .build/release shasum -a 256 ${{ steps.archive-name.outputs.value }} > SHA256SUM - name: Upload archive to release uses: svenstaro/upload-release-action@v2 with: repo_token: ${{ secrets.GITHUB_TOKEN }} file: .build/release/${{ steps.archive-name.outputs.value }} asset_name: ${{ steps.archive-name.outputs.value }} tag: ${{ github.ref }} overwrite: true - name: Upload checksum artifact uses: actions/upload-artifact@v4 with: name: checksums-${{ matrix.os_name }}-${{ matrix.arch }} path: .build/release/SHA256SUM publish-checksums: needs: publish runs-on: ubuntu-latest steps: - name: Download all checksums uses: actions/download-artifact@v4 with: path: checksums - name: Combine checksums run: | cat checksums/**/SHA256SUM > SHA256SUMS find checksums -type f -name "SHA256SUM" -exec cat {} + > SHA256SUMS echo "Combined checksums:" cat SHA256SUMS - name: Upload combined checksums to release uses: svenstaro/upload-release-action@v2 with: repo_token: ${{ secrets.GITHUB_TOKEN }} file: SHA256SUMS asset_name: SHA256SUMS tag: ${{ github.ref }} overwrite: true ================================================ FILE: .github/workflows/test.yml ================================================ name: Tests on: pull_request jobs: build: name: Test build on ${{ matrix.os }} ${{ matrix.os_name }} runs-on: ${{ matrix.os }} strategy: matrix: include: - os: macos-13 os_name: ventura - os: macos-14 os_name: sonoma - os: macos-15 os_name: sequoia steps: - name: Checkout uses: actions/checkout@v3 - name: Test run: swift test - name: Build run: swift build --configuration release --arch arm64 --arch x86_64 ================================================ FILE: .gitignore ================================================ # General .DS_Store .AppleDouble .LSOverride # Icon must end with two \r Icon # Thumbnails ._* # Files that might appear in the root of a volume .DocumentRevisions-V100 .fseventsd .Spotlight-V100 .TemporaryItems .Trashes .VolumeIcon.icns .com.apple.timemachine.donotpresent # Directories potentially created on remote AFP share .AppleDB .AppleDesktop Network Trash Folder Temporary Items .apdisk # Xcode # # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore ## User settings xcuserdata/ ## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9) *.xcscmblueprint *.xccheckout ## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4) build/ DerivedData/ *.moved-aside *.pbxuser !default.pbxuser *.mode1v3 !default.mode1v3 *.mode2v3 !default.mode2v3 *.perspectivev3 !default.perspectivev3 ## Gcc Patch /*.gcno ## SwiftPM Packages xcuserdata *.xcodeproj .swiftpm .build/ # Test files *Tests.swift.plist ================================================ FILE: LICENSE ================================================ Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ================================================ FILE: Package.resolved ================================================ { "object": { "pins": [ { "package": "swift-argument-parser", "repositoryURL": "https://github.com/apple/swift-argument-parser", "state": { "branch": null, "revision": "e1465042f195f374b94f915ba8ca49de24300a0d", "version": "1.0.2" } } ] }, "version": 1 } ================================================ FILE: Package.swift ================================================ // swift-tools-version:5.1 // The swift-tools-version declares the minimum version of Swift required to build this package. import PackageDescription let package = Package( name: "autokbisw", products: [ .executable(name: "autokbisw", targets: ["autokbisw"]), .library(name: "AutokbiswCore", targets: ["AutokbiswCore"]), ], dependencies: [ // Dependencies declare other packages that this package depends on. // .package(url: /* package url */, from: "1.0.0"), .package(url: "https://github.com/apple/swift-argument-parser", from: "1.0.0"), ], targets: [ // Targets are the basic building blocks of a package. A target can define a module or a test suite. // Targets can depend on other targets in this package, and on products in packages which this package depends on. .target( name: "AutokbiswCore", dependencies: [ .product(name: "ArgumentParser", package: "swift-argument-parser"), ] ), .target( name: "autokbisw", dependencies: ["AutokbiswCore"] ), .testTarget( name: "autokbiswTests", dependencies: ["AutokbiswCore"] ), ] ) ================================================ FILE: README.md ================================================ # autokbisw – Automatic keyboard input language switcher Automatic keyboard input language switching for macOS. `autokbisw` is made for those who use multiple keyboards with different key layouts (e.g. English and French), and frequently switch between them. It runs as a background service and remembers the last active keyboard input language for a specific keyboard and automatically activates it when typing on that keyboard again. ## Features - Automatically switches the keyboard layout (input source) based on the connected keyboard - Identifies keyboards by their product name, hardware ID, and optionally the connected USB port (location ID) - Command-line interface to enable/disable switching for specific keyboards ## Installation The easiest way to install `autokbisw` as a background service is by using [Homebrew](https://brew.sh): ```sh brew install ohueter/tap/autokbisw brew services start autokbisw ``` Please note that `autokbisw` is compiled from source by Homebrew, so a full installation of Xcode.app is required. Installing just the Command Line Tools is not sufficient. `autokbisw` requires privileges to monitor all keyboard input. You need to grant these privileges on the first start of the service. ### Upgrading an existing installation If you already have `autokbisw` installed, you can upgrade it by running the following command: ```sh brew upgrade ohueter/tap/autokbisw ``` This will update the formula to the latest version and reinstall it. ## Getting started - Begin typing with your first keyboard, so it becomes the **active keyboard**. - Select the desired **keyboard layout** for your first keyboard by selecting it in the menu bar or pressing the 🌐 key. - Begin typing with your second keyboard, so it becomes the **active keyboard**. - Select the desired **keyboard layout** for your second keyboard. - Repeat if you are using more keyboards. You should notice that after the first keystroke on any of your keyboards, the keyboard layout automatically switches to the selected one. Note that the keyboard layout switch happens **after** the first keystroke, so you won't have the selected keyboard layout at this time. ## Enabling/disabling switching for specific keyboards By default, `autokbisw` uses device identification data reported by the hardware to determine whether to enable automatic switching. However, some devices report incorrect information: keyboards may identify as mice (and thus be initially disabled), while mice may identify as keyboards (triggering unwanted input source switches). If you encounter either issue, you can manually enable or disable switching for specific devices using the command-line interface. ### Listing Devices To list all known devices and their current status: ```sh autokbisw list ``` This will display a numbered list of devices with their identifier, status (enabled/disabled), and the associated keyboard layout. Note: Devices only appear in this list after they've been used for text input while `autokbisw` was running. ### Enabling/disabling switching To enable keyboard layout switching for a specific keyboard: ```sh autokbisw enable ``` To disable keyboard layout switching for a specific keyboard: ```sh autokbisw disable ``` You can use either the device number (obtained from the `list` subcommand) or the device identifier to specify the keyboard. ## Building from source Clone this repository, make sure you have a full Xcode.app installation, and run the following commands: ```sh cd autokbisw swift build --configuration release ``` The output will provide the path to the built binary, likely `.build/release/autokbisw`. You can run it from the `release` directory as is. ### Command-line arguments ``` OVERVIEW: Automatic keyboard/input source switching for macOS. USAGE: autokbisw [--verbose ] [--location] OPTIONS: -v, --verbose Print verbose output (1 = DEBUG, 2 = TRACE). (default: 0) -l, --location Use locationId to identify keyboards. Note that the locationId changes when you plug a keyboard in a different port. Therefore using the locationId in the keyboards identifiers means the configured language will be associated to a keyboard on a specific port. -h, --help Show help information. SUBCOMMANDS: enable Enable input source switching for . disable Disable input source switching for . list List all known devices and their current status. clear Clear all stored mappings and device settings. See 'autokbisw help ' for detailed help. ``` ## FAQ & Common issues ### The installation fails with an XCode error. On some system configurations, the installation fails with XCode errors similar to those described in GitHub issues [#12](https://github.com/ohueter/autokbisw/issues/12) and [#28](https://github.com/ohueter/autokbisw/issues/28). In order to check if your system is affected, run ```sh xcode-select --print-path ``` in the terminal. The expected output is `/Applications/Xcode.app/Contents/Developer`. If the output on your system is different, run ```sh sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer ``` to set the correct path and (hopefully) fix the compilation. ### autokbisw doesn't work after installation. If `autokbisw` isn't working after the first start of the service, try these solutions: 1. Restart the service: ```sh brew services restart autokbisw ``` 2. Re-grant the required privileges to the service by removing and re-adding the executable under `System Preferences > Security & Privacy > Privacy > Input Monitoring`. The path to add should either be `/usr/local/bin/autokbisw` (on Intel Macs) or `/opt/homebrew/opt/autokbisw/bin/autokbisw` (on Apple M1 Macs). ### autokbisw doesn't work as expected with my Logitech keyboard or mouse. It seems that some Logitech devices miss-identify as keyboard or mouse, although they're actually the respective other kind of device (see GitHub issues [#7](https://github.com/ohueter/autokbisw/issues/7) or [#18](https://github.com/ohueter/autokbisw/issues/18) for examples). If `autokbisw` isn't working for you because of this issue, try enabling/disabling switching for specific devices using the command-line interface (see [Enabling/disabling switching for specific keyboards](#enablingdisabling-switching-for-specific-keyboards)). Open a new issue if it's still not working for your device. ### Can autokbisw be used with the `Automatically switch to a document's input source` option? `autokbisw` is not compatible with the `Automatically switch to a document's input source` system option (found under System Settings > Keyboard > Input sources > Edit…). If the setting is turned on, `autokbisw` might not work as expected (see [#33](https://github.com/ohueter/autokbisw/issues/33)). ### Can autokbisw be used with Karabiner-Elements? `autokbisw` is not compatible with [Karabiner Elements](https://karabiner-elements.pqrs.org/), since it proxies keyboard events. That makes Karabiner appear as the system input device, and `autokbisw` can't detect the original input device. However, you can manually configure Karabiner to switch keyboard layouts based on device ID and other variables, it just won't be _fully_ automated -- see [this GH answer](https://github.com/pqrs-org/Karabiner-Elements/issues/2230#issuecomment-2043513996). ### autokbisw is installed correctly but the background service does not changes the language? Try to unload and reload the plist and reboot (see [discussion for reference](https://github.com/ohueter/autokbisw/discussions/38#discussioncomment-9127439)): ```sh launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.autokbisw.plist launchctl load ~/Library/LaunchAgents/homebrew.mxcl.autokbisw.plist ``` ## Acknowledgements This program was originally developed by [Jean Helou](https://github.com/jeantil/autokbisw) ([@jeantil](https://github.com/jeantil)). ================================================ FILE: Sources/AutokbiswCore/IOKeyEventMonitor.swift ================================================ // Copyright 2016 Jean Helou // Copyright 2024 Ole Hüter // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import Carbon import Foundation import IOKit import IOKit.hid import IOKit.usb public final class IOKeyEventMonitor { private let log: Logger private let hidManager: IOHIDManager fileprivate let notificationCenter: CFNotificationCenter fileprivate let MAPPINGS_DEFAULTS_KEY = "keyboardISMapping" fileprivate var defaults: UserDefaults = .standard fileprivate let MAPPING_ENABLED_KEY = "mappingEnabled" var deviceEnabled: [String: Bool] = [:] fileprivate let assignmentLock = NSLock() var lastActiveKeyboard: String? var kb2is: [String: TISInputSource] = .init() fileprivate var useLocation: Bool public init? (usagePage: Int, usage: Int, useLocation: Bool, verbosity: Int, userDefaults: UserDefaults = .standard) { self.useLocation = useLocation log = Logger(verbosity: verbosity) defaults = userDefaults hidManager = IOHIDManagerCreate(kCFAllocatorDefault, IOOptionBits(kIOHIDOptionsTypeNone)) notificationCenter = CFNotificationCenterGetDistributedCenter() let deviceMatch: CFMutableDictionary = [kIOHIDDeviceUsageKey: usage, kIOHIDDeviceUsagePageKey: usagePage] as NSMutableDictionary IOHIDManagerSetDeviceMatching(hidManager, deviceMatch) loadMappings() } deinit { self.saveMappings() stopObservingSettingsChanges() let context = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque()) IOHIDManagerRegisterInputValueCallback(hidManager, Optional.none, context) CFNotificationCenterRemoveObserver(notificationCenter, context, CFNotificationName(kTISNotifySelectedKeyboardInputSourceChanged), nil) } public func start() { let context = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque()) observeIputSourceChangedNotification(context: context) registerHIDKeyboardCallback(context: context) IOHIDManagerScheduleWithRunLoop(hidManager, CFRunLoopGetMain(), CFRunLoopMode.defaultMode!.rawValue) IOHIDManagerOpen(hidManager, IOOptionBits(kIOHIDOptionsTypeNone)) startObservingSettingsChanges() } private func observeIputSourceChangedNotification(context: UnsafeMutableRawPointer) { let inputSourceChanged: CFNotificationCallback = { _, observer, _, _, _ in let selfPtr = Unmanaged.fromOpaque(observer!).takeUnretainedValue() selfPtr.onInputSourceChanged() } CFNotificationCenterAddObserver(notificationCenter, context, inputSourceChanged, kTISNotifySelectedKeyboardInputSourceChanged, nil, CFNotificationSuspensionBehavior.deliverImmediately) } private func registerHIDKeyboardCallback(context: UnsafeMutableRawPointer) { let myHIDKeyboardCallback: IOHIDValueCallback = { context, _, sender, _ in let selfPtr = Unmanaged.fromOpaque(context!).takeUnretainedValue() let senderDevice = Unmanaged.fromOpaque(sender!).takeUnretainedValue() let conformsToKeyboard = selfPtr.deviceConformsToKeyboard(senderDevice) let vendorId = selfPtr.deviceProperty(senderDevice, kIOHIDVendorIDKey) let productId = selfPtr.deviceProperty(senderDevice, kIOHIDProductIDKey) let product = selfPtr.deviceProperty(senderDevice, kIOHIDProductKey) let manufacturer = selfPtr.deviceProperty(senderDevice, kIOHIDManufacturerKey) let serialNumber = selfPtr.deviceProperty(senderDevice, kIOHIDSerialNumberKey) let locationId = selfPtr.deviceProperty(senderDevice, kIOHIDLocationIDKey) let uniqueId = selfPtr.deviceProperty(senderDevice, kIOHIDUniqueIDKey) let keyboard = selfPtr.useLocation ? "\(product)-[\(vendorId)-\(productId)-\(manufacturer)-\(serialNumber)-\(locationId)]" : "\(product)-[\(vendorId)-\(productId)-\(manufacturer)-\(serialNumber)]" selfPtr.log.trace("received event from device \(keyboard) - \(locationId) - \(uniqueId) - conformsToKeyboard: \(conformsToKeyboard)") selfPtr.onKeyboardEvent(keyboard: keyboard, conformsToKeyboard: conformsToKeyboard) } IOHIDManagerRegisterInputValueCallback(hidManager, myHIDKeyboardCallback, context) } private func deviceProperty(_ device: IOHIDDevice, _ key: String) -> String { guard let value = IOHIDDeviceGetProperty(device, key as CFString) else { return "unknown" } return String(describing: value) } private func deviceConformsToKeyboard(_ device: IOHIDDevice) -> Bool { return IOHIDDeviceConformsTo(device, UInt32(kHIDPage_GenericDesktop), UInt32(kHIDUsage_GD_Keyboard)) } } // MARK: - Input Source Management public extension IOKeyEventMonitor { func restoreInputSource(keyboard: String) { guard let targetIs = kb2is[keyboard] else { log.trace("No previous mapping saved for \(keyboard), awaiting the user to select the right one") return } log.debug("Setting input source for keyboard \(keyboard): \(targetIs)") // This will trigger onInputSourceChanged() TISSelectInputSource(targetIs) } func storeInputSource(keyboard: String, conformsToKeyboard: Bool? = nil) { let currentSource: TISInputSource = TISCopyCurrentKeyboardInputSource().takeUnretainedValue() kb2is[keyboard] = currentSource // Only set a default value for deviceEnabled if conformsToKeyboard is provided if let isKeyboard = conformsToKeyboard, deviceEnabled[keyboard] == nil { log.debug("Enabling device by default because it is recognized as a keyboard") deviceEnabled[keyboard] = isKeyboard } saveMappings() } func onInputSourceChanged() { assignmentLock.lock() // lastActiveKeyboard can be nil only if the language is changed between // program start and the first keypress, so we can ignore this edge case if let lastActiveKeyboard = lastActiveKeyboard { storeInputSource(keyboard: lastActiveKeyboard) } assignmentLock.unlock() } func onKeyboardEvent(keyboard: String, conformsToKeyboard: Bool? = nil) { guard lastActiveKeyboard != keyboard else { log.trace("change: ignoring event from keyboard \(keyboard) because active device hasn't changed") return } log.debug("change: keyboard changed from \(lastActiveKeyboard ?? "nil") to \(keyboard)") let isEnabled = deviceEnabled[keyboard] ?? true guard isEnabled else { log.trace("change: ignoring event from keyboard \(keyboard) because device is disabled") return } assignmentLock.lock() if kb2is[keyboard] == nil { // This keyboard has no mapping yet, store the current input source log.debug("New device detected: \(keyboard), storing current input source") storeInputSource(keyboard: keyboard, conformsToKeyboard: conformsToKeyboard) } else { // Keyboard is different from the previously used keyboard, restore settings. restoreInputSource(keyboard: keyboard) } lastActiveKeyboard = keyboard assignmentLock.unlock() } } // MARK: - Device Management public extension IOKeyEventMonitor { func enableDevice(_ keyboard: String) { deviceEnabled[keyboard] = true saveMappings() } func disableDevice(_ keyboard: String) { deviceEnabled[keyboard] = false saveMappings() } func enableDeviceByNumber(_ number: Int) { let devices = Array(deviceEnabled.keys).sorted() guard number > 0, number <= devices.count else { print("Invalid device number") return } let keyboard = devices[number - 1] deviceEnabled[keyboard] = true saveMappings() } func disableDeviceByNumber(_ number: Int) { let devices = Array(deviceEnabled.keys).sorted() guard number > 0, number <= devices.count else { print("Invalid device number") return } let keyboard = devices[number - 1] deviceEnabled[keyboard] = false saveMappings() } func getDevicesString() -> String { return deviceEnabled .sorted { $0.key < $1.key } .enumerated() .map { index, entry -> String in let (keyboard, isEnabled) = entry let number = index + 1 let status = isEnabled ? "enabled" : "disabled" var layoutInfo = "no layout stored" if let source = kb2is[keyboard] { let name = TISGetInputSourceProperty(source, kTISPropertyLocalizedName) let localizedName = unmanagedStringToString(name) ?? "unknown" let id = is2Id(source) ?? "unknown" layoutInfo = "\(localizedName) (\(id))" } return "\(number). \(keyboard): \(status) - \(layoutInfo)" } .joined(separator: "\n") } } // MARK: - Persistence extension IOKeyEventMonitor { func loadMappings() { kb2is.removeAll() deviceEnabled.removeAll() let selectableIsProperties = [ kTISPropertyInputSourceIsEnableCapable: true, kTISPropertyInputSourceCategory: kTISCategoryKeyboardInputSource ?? "" as CFString, ] as CFDictionary let inputSources = TISCreateInputSourceList(selectableIsProperties, false).takeUnretainedValue() as! [TISInputSource] let inputSourcesById = inputSources.reduce([String: TISInputSource]()) { dict, inputSource -> [String: TISInputSource] in var dict = dict if let id = unmanagedStringToString(TISGetInputSourceProperty(inputSource, kTISPropertyInputSourceID)) { dict[id] = inputSource } return dict } if let mappings = defaults.dictionary(forKey: MAPPINGS_DEFAULTS_KEY) { for (keyboardId, inputSourceId) in mappings { kb2is[keyboardId] = inputSourcesById[String(describing: inputSourceId)] } } if let enabledMappings = defaults.dictionary(forKey: MAPPING_ENABLED_KEY) as? [String: Bool] { deviceEnabled = enabledMappings } } func saveMappings() { withPausedSettingsObserver { let mappings = kb2is.mapValues(is2Id) defaults.set(mappings, forKey: MAPPINGS_DEFAULTS_KEY) defaults.set(deviceEnabled, forKey: MAPPING_ENABLED_KEY) defaults.synchronize() postSettingsChangedNotification() } log.trace("Saved keyboard mappings to UserDefaults") } public func clearAllSettings() { withPausedSettingsObserver { kb2is.removeAll() deviceEnabled.removeAll() lastActiveKeyboard = nil defaults.removeObject(forKey: MAPPINGS_DEFAULTS_KEY) defaults.removeObject(forKey: MAPPING_ENABLED_KEY) defaults.synchronize() postSettingsChangedNotification() } } } // MARK: - Settings Change Notifications private extension IOKeyEventMonitor { private func startObservingSettingsChanges() { log.trace("Starting UserDefaults observation") let context = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque()) let callback: CFNotificationCallback = { _, observer, _, _, _ in let selfPtr = Unmanaged.fromOpaque(observer!).takeUnretainedValue() selfPtr.log.trace("Received settings change notification") selfPtr.onSettingsChanged() } CFNotificationCenterAddObserver( notificationCenter, context, callback, "com.autokbisw.settingsChanged" as CFString, nil, .deliverImmediately ) } private func stopObservingSettingsChanges() { let context = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque()) CFNotificationCenterRemoveObserver( notificationCenter, context, CFNotificationName("com.autokbisw.settingsChanged" as CFString), nil ) } private func postSettingsChangedNotification() { log.trace("Posting settings changed notification") CFNotificationCenterPostNotification( notificationCenter, CFNotificationName("com.autokbisw.settingsChanged" as CFString), nil, nil, true ) } private func withPausedSettingsObserver(_ operation: () -> T) -> T { stopObservingSettingsChanges() defer { startObservingSettingsChanges() } return operation() } private func onSettingsChanged() { loadMappings() // If mappings are empty, settings were cleared in another instance if kb2is.isEmpty, deviceEnabled.isEmpty { lastActiveKeyboard = nil } log.trace("Reloaded mappings due to UserDefaults change") } } // MARK: - Utilities extension IOKeyEventMonitor { private func is2Id(_ inputSource: TISInputSource) -> String? { return unmanagedStringToString(TISGetInputSourceProperty(inputSource, kTISPropertyInputSourceID))! } func unmanagedStringToString(_ p: UnsafeMutableRawPointer?) -> String? { if let cfValue = p { let value = Unmanaged.fromOpaque(cfValue).takeUnretainedValue() as CFString if CFGetTypeID(value) == CFStringGetTypeID() { return value as String } else { return nil } } else { return nil } } } ================================================ FILE: Sources/AutokbiswCore/Logger.swift ================================================ import Foundation public let DEBUG = 1 public let TRACE = 2 public struct Logger { let verbosity: Int func trace(_ message: String) { if verbosity >= TRACE { print(message) } } func debug(_ message: String) { if verbosity >= DEBUG { print(message) } } } ================================================ FILE: Sources/autokbisw/main.swift ================================================ // Copyright 2016 Jean Helou // Copyright 2024 Ole Hüter // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. import ArgumentParser import AutokbiswCore import Foundation struct Autokbisw: ParsableCommand { private static let defaultUsagePage: Int = 0x01 private static let defaultUsage: Int = 6 private static func createMonitor(useLocation: Bool = false, verbosity: Int = 0) -> IOKeyEventMonitor? { IOKeyEventMonitor( usagePage: defaultUsagePage, usage: defaultUsage, useLocation: useLocation, verbosity: verbosity ) } static var configuration = CommandConfiguration( abstract: "Automatic keyboard/input source switching for macOS.", subcommands: [Enable.self, Disable.self, List.self, Clear.self] ) @Option( name: .shortAndLong, help: ArgumentHelp( "Print verbose output (1 = DEBUG, 2 = TRACE).", valueName: "verbosity" ) ) var verbose = 0 @Flag( name: .shortAndLong, help: ArgumentHelp( "Use locationId to identify keyboards.", discussion: "Note that the locationId changes when you plug a keyboard in a different port. Therefore using the locationId in the keyboards identifiers means the configured language will be associated to a keyboard on a specific port." ) ) var location = false mutating func run() throws { if verbose > 0 { print("Starting with useLocation: \(location) - verbosity: \(verbose)") } let monitor = Autokbisw.createMonitor(useLocation: location, verbosity: verbose) monitor?.start() CFRunLoopRun() } struct Enable: ParsableCommand { static var configuration = CommandConfiguration( commandName: "enable", abstract: "Enable input source switching for ." ) @Argument(help: "The device identifier or number (from list command) to enable") var keyboard: String func run() throws { let monitor = Autokbisw.createMonitor() if let number = Int(keyboard) { monitor?.enableDeviceByNumber(number) } else { monitor?.enableDevice(keyboard) } } } struct Disable: ParsableCommand { static var configuration = CommandConfiguration( commandName: "disable", abstract: "Disable input source switching for ." ) @Argument(help: "The device identifier or number (from list command) to disable") var keyboard: String func run() throws { let monitor = Autokbisw.createMonitor() if let number = Int(keyboard) { monitor?.disableDeviceByNumber(number) } else { monitor?.disableDevice(keyboard) } } } struct List: ParsableCommand { static var configuration = CommandConfiguration( commandName: "list", abstract: "List all known devices and their current status." ) func run() throws { let monitor = Autokbisw.createMonitor() print(monitor?.getDevicesString() ?? "") } } struct Clear: ParsableCommand { static var configuration = CommandConfiguration( commandName: "clear", abstract: "Clear all stored mappings and device settings." ) func run() throws { let monitor = Autokbisw.createMonitor() monitor?.clearAllSettings() print("All stored settings have been cleared.") } } } Autokbisw.main() ================================================ FILE: Tests/autokbiswTests/IOKeyEventMonitorTests.swift ================================================ // Copyright 2024 Ole Hüter // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. @testable import AutokbiswCore import XCTest class IOKeyEventMonitorTests: XCTestCase { var monitor: IOKeyEventMonitor! var mockUserDefaults: UserDefaults! override func setUp() { super.setUp() mockUserDefaults = UserDefaults(suiteName: #file) // Create an in-memory UserDefaults mockUserDefaults.removePersistentDomain(forName: #file) // Ensure it's empty // Initialize the monitor before each test monitor = IOKeyEventMonitor(usagePage: 0x01, usage: 6, useLocation: true, verbosity: 0, userDefaults: mockUserDefaults) } override func tearDown() { // Clean up after each test mockUserDefaults.removePersistentDomain(forName: #file) monitor = nil mockUserDefaults = nil super.tearDown() } func testInitialization() { XCTAssertNotNil(monitor, "IOKeyEventMonitor should be successfully initialized") } func testStoreAndRestoreInputSource() { let testKeyboard = "TestKeyboard-[1-2-TestManufacturer-123-456]" // Store a mock input source monitor.storeInputSource(keyboard: testKeyboard) // Verify that the input source was stored XCTAssertNotNil(monitor.kb2is[testKeyboard], "Input source should be stored for the test keyboard") // Attempt to restore the input source monitor.restoreInputSource(keyboard: testKeyboard) // We can't easily verify if TISSelectInputSource was called correctly, // but we can check that no error was thrown } func testOnKeyboardEvent() { let testKeyboard1 = "TestKeyboard1-[1-2-TestManufacturer-123-456]" let testKeyboard2 = "TestKeyboard2-[3-4-TestManufacturer-789-012]" monitor.onKeyboardEvent(keyboard: testKeyboard1) XCTAssertEqual(monitor.lastActiveKeyboard, testKeyboard1, "Last active keyboard should be updated") monitor.onKeyboardEvent(keyboard: testKeyboard2) XCTAssertEqual(monitor.lastActiveKeyboard, testKeyboard2, "Last active keyboard should be updated to the new keyboard") } func testEnableDevice() { let testKeyboard = "TestKeyboard-[1-2-TestManufacturer-123-456]" monitor.enableDevice(testKeyboard) XCTAssertTrue(monitor.deviceEnabled[testKeyboard] ?? false, "Device should be enabled") } func testDisableDevice() { let testKeyboard = "TestKeyboard-[1-2-TestManufacturer-123-456]" monitor.disableDevice(testKeyboard) XCTAssertFalse(monitor.deviceEnabled[testKeyboard] ?? true, "Device should be disabled") } func testClearAllSettings() { let testKeyboard = "TestKeyboard-[1-2-TestManufacturer-123-456]" monitor.storeInputSource(keyboard: testKeyboard) monitor.enableDevice(testKeyboard) monitor.clearAllSettings() XCTAssertTrue(monitor.kb2is.isEmpty, "kb2is should be empty after clearing settings") XCTAssertTrue(monitor.deviceEnabled.isEmpty, "deviceEnabled should be empty after clearing settings") XCTAssertNil(monitor.lastActiveKeyboard, "lastActiveKeyboard should be nil after clearing settings") } func testStoreInputSourceWithConformsToKeyboard() { let testKeyboard = "TestKeyboard-[1-2-TestManufacturer-123-456]" // Test storing with conformsToKeyboard = true monitor.storeInputSource(keyboard: testKeyboard, conformsToKeyboard: true) XCTAssertTrue(monitor.deviceEnabled[testKeyboard] ?? false, "Device should be enabled when conformsToKeyboard is true") // Clear settings monitor.clearAllSettings() // Test storing with conformsToKeyboard = false monitor.storeInputSource(keyboard: testKeyboard, conformsToKeyboard: false) XCTAssertFalse(monitor.deviceEnabled[testKeyboard] ?? true, "Device should be disabled when conformsToKeyboard is false") // Test storing without conformsToKeyboard monitor.clearAllSettings() monitor.storeInputSource(keyboard: testKeyboard) XCTAssertNil(monitor.deviceEnabled[testKeyboard], "Device enabled status should not be set when conformsToKeyboard is not provided") } func testOnKeyboardEventWithConformsToKeyboard() { let testKeyboard = "TestKeyboard-[1-2-TestManufacturer-123-456]" // Test with conformsToKeyboard = true monitor.onKeyboardEvent(keyboard: testKeyboard, conformsToKeyboard: true) XCTAssertTrue(monitor.deviceEnabled[testKeyboard] ?? false, "Device should be enabled when conformsToKeyboard is true") XCTAssertEqual(monitor.lastActiveKeyboard, testKeyboard, "Last active keyboard should be updated") // Clear settings monitor.clearAllSettings() // Test with conformsToKeyboard = false monitor.onKeyboardEvent(keyboard: testKeyboard, conformsToKeyboard: false) XCTAssertFalse(monitor.deviceEnabled[testKeyboard] ?? true, "Device should be disabled when conformsToKeyboard is false") XCTAssertEqual(monitor.lastActiveKeyboard, testKeyboard, "Last active keyboard should be updated even for disabled device") } func testPrintDevices() { let testKeyboard1 = "TestKeyboard1-[1-2-TestManufacturer-123-456]" let testKeyboard2 = "TestKeyboard2-[3-4-TestManufacturer-789-012]" monitor.enableDevice(testKeyboard1) monitor.disableDevice(testKeyboard2) let output = monitor.getDevicesString() XCTAssertTrue(output.contains("\(testKeyboard1): enabled"), "Output should show TestKeyboard1 as enabled") XCTAssertTrue(output.contains("\(testKeyboard2): disabled"), "Output should show TestKeyboard2 as disabled") } func testEnableDeviceByNumber() { let testKeyboard1 = "ATestKeyboard1-[1-2-TestManufacturer-123-456]" let testKeyboard2 = "BTestKeyboard2-[3-4-TestManufacturer-789-012]" // Setup initial state monitor.enableDevice(testKeyboard1) monitor.enableDevice(testKeyboard2) monitor.disableDevice(testKeyboard2) // Should be: keyboard1 enabled, keyboard2 disabled // Enable device #2 (testKeyboard2) monitor.enableDeviceByNumber(2) XCTAssertTrue(monitor.deviceEnabled[testKeyboard2] ?? false, "Device #2 should be enabled") XCTAssertTrue(monitor.deviceEnabled[testKeyboard1] ?? false, "Device #1 should remain enabled") } func testDisableDeviceByNumber() { let testKeyboard1 = "ATestKeyboard1-[1-2-TestManufacturer-123-456]" let testKeyboard2 = "BTestKeyboard2-[3-4-TestManufacturer-789-012]" // Setup initial state monitor.enableDevice(testKeyboard1) monitor.enableDevice(testKeyboard2) // Disable device #1 (testKeyboard1) monitor.disableDeviceByNumber(1) XCTAssertFalse(monitor.deviceEnabled[testKeyboard1] ?? true, "Device #1 should be disabled") XCTAssertTrue(monitor.deviceEnabled[testKeyboard2] ?? false, "Device #2 should remain enabled") } func testDeviceNumbering() { let testKeyboard1 = "XTestKeyboard1-[1-2-TestManufacturer-123-456]" let testKeyboard2 = "BTestKeyboard2-[3-4-TestManufacturer-789-012]" monitor.enableDevice(testKeyboard1) monitor.enableDevice(testKeyboard2) let output = monitor.getDevicesString() let lines = output.split(separator: "\n") XCTAssertTrue(lines[0].starts(with: "1. BTestKeyboard2"), "Second device should be numbered 1") XCTAssertTrue(lines[1].starts(with: "2. XTestKeyboard1"), "First device should be numbered 2") } func testInvalidDeviceNumber() { let testKeyboard = "TestKeyboard-[1-2-TestManufacturer-123-456]" monitor.enableDevice(testKeyboard) // Test invalid numbers monitor.enableDeviceByNumber(0) // Too low monitor.enableDeviceByNumber(2) // Too high monitor.disableDeviceByNumber(0) // Too low monitor.disableDeviceByNumber(2) // Too high // State should remain unchanged XCTAssertTrue(monitor.deviceEnabled[testKeyboard] ?? false, "Device state should not change with invalid number") } func testAddNewKeyboardBasedOnMapping() { let testKeyboard = "TestKeyboard-[1-2-TestManufacturer-123-456]" // Test first keyboard with conformsToKeyboard = true monitor.onKeyboardEvent(keyboard: testKeyboard, conformsToKeyboard: true) XCTAssertNotNil(monitor.kb2is[testKeyboard], "Keyboard should have input source mapping") XCTAssertTrue(monitor.deviceEnabled[testKeyboard] ?? false, "Keyboard should be enabled when conformsToKeyboard is true") // Clear settings and test with conformsToKeyboard = false monitor.clearAllSettings() monitor.onKeyboardEvent(keyboard: testKeyboard, conformsToKeyboard: false) XCTAssertNotNil(monitor.kb2is[testKeyboard], "Keyboard should have input source mapping") XCTAssertFalse(monitor.deviceEnabled[testKeyboard] ?? true, "Keyboard should be disabled when conformsToKeyboard is false") // Test that subsequent events don't change the mapping or enabled state monitor.onKeyboardEvent(keyboard: testKeyboard, conformsToKeyboard: true) XCTAssertFalse(monitor.deviceEnabled[testKeyboard] ?? true, "Enabled state should not change for existing keyboard") // Test with a second keyboard let testKeyboard2 = "TestKeyboard2-[3-4-TestManufacturer-789-012]" monitor.onKeyboardEvent(keyboard: testKeyboard2, conformsToKeyboard: true) XCTAssertNotNil(monitor.kb2is[testKeyboard2], "Second keyboard should have input source mapping") XCTAssertTrue(monitor.deviceEnabled[testKeyboard2] ?? false, "Second keyboard should be enabled") XCTAssertFalse(monitor.deviceEnabled[testKeyboard] ?? true, "First keyboard should remain disabled") } }