├── Package.resolved ├── Sources ├── AutokbiswCore │ ├── Logger.swift │ └── IOKeyEventMonitor.swift └── autokbisw │ └── main.swift ├── .github └── workflows │ ├── test.yml │ └── release.yml ├── .gitignore ├── Package.swift ├── README.md ├── Tests └── autokbiswTests │ └── IOKeyEventMonitorTests.swift └── LICENSE /Package.resolved: -------------------------------------------------------------------------------- 1 | { 2 | "object": { 3 | "pins": [ 4 | { 5 | "package": "swift-argument-parser", 6 | "repositoryURL": "https://github.com/apple/swift-argument-parser", 7 | "state": { 8 | "branch": null, 9 | "revision": "e1465042f195f374b94f915ba8ca49de24300a0d", 10 | "version": "1.0.2" 11 | } 12 | } 13 | ] 14 | }, 15 | "version": 1 16 | } 17 | -------------------------------------------------------------------------------- /Sources/AutokbiswCore/Logger.swift: -------------------------------------------------------------------------------- 1 | import Foundation 2 | 3 | public let DEBUG = 1 4 | public let TRACE = 2 5 | 6 | public struct Logger { 7 | let verbosity: Int 8 | 9 | func trace(_ message: String) { 10 | if verbosity >= TRACE { 11 | print(message) 12 | } 13 | } 14 | 15 | func debug(_ message: String) { 16 | if verbosity >= DEBUG { 17 | print(message) 18 | } 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /.github/workflows/test.yml: -------------------------------------------------------------------------------- 1 | name: Tests 2 | 3 | on: pull_request 4 | 5 | jobs: 6 | build: 7 | name: Test build on ${{ matrix.os }} ${{ matrix.os_name }} 8 | runs-on: ${{ matrix.os }} 9 | strategy: 10 | matrix: 11 | include: 12 | - os: macos-13 13 | os_name: ventura 14 | - os: macos-14 15 | os_name: sonoma 16 | - os: macos-15 17 | os_name: sequoia 18 | steps: 19 | - name: Checkout 20 | uses: actions/checkout@v3 21 | 22 | - name: Test 23 | run: swift test 24 | 25 | - name: Build 26 | run: swift build --configuration release --arch arm64 --arch x86_64 27 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # General 2 | .DS_Store 3 | .AppleDouble 4 | .LSOverride 5 | 6 | # Icon must end with two \r 7 | Icon 8 | 9 | # Thumbnails 10 | ._* 11 | 12 | # Files that might appear in the root of a volume 13 | .DocumentRevisions-V100 14 | .fseventsd 15 | .Spotlight-V100 16 | .TemporaryItems 17 | .Trashes 18 | .VolumeIcon.icns 19 | .com.apple.timemachine.donotpresent 20 | 21 | # Directories potentially created on remote AFP share 22 | .AppleDB 23 | .AppleDesktop 24 | Network Trash Folder 25 | Temporary Items 26 | .apdisk 27 | 28 | # Xcode 29 | # 30 | # gitignore contributors: remember to update Global/Xcode.gitignore, Objective-C.gitignore & Swift.gitignore 31 | 32 | ## User settings 33 | xcuserdata/ 34 | 35 | ## compatibility with Xcode 8 and earlier (ignoring not required starting Xcode 9) 36 | *.xcscmblueprint 37 | *.xccheckout 38 | 39 | ## compatibility with Xcode 3 and earlier (ignoring not required starting Xcode 4) 40 | build/ 41 | DerivedData/ 42 | *.moved-aside 43 | *.pbxuser 44 | !default.pbxuser 45 | *.mode1v3 46 | !default.mode1v3 47 | *.mode2v3 48 | !default.mode2v3 49 | *.perspectivev3 50 | !default.perspectivev3 51 | 52 | ## Gcc Patch 53 | /*.gcno 54 | 55 | ## SwiftPM 56 | Packages 57 | xcuserdata 58 | *.xcodeproj 59 | 60 | .swiftpm 61 | 62 | .build/ 63 | 64 | # Test files 65 | *Tests.swift.plist 66 | -------------------------------------------------------------------------------- /Package.swift: -------------------------------------------------------------------------------- 1 | // swift-tools-version:5.1 2 | // The swift-tools-version declares the minimum version of Swift required to build this package. 3 | 4 | import PackageDescription 5 | 6 | let package = Package( 7 | name: "autokbisw", 8 | products: [ 9 | .executable(name: "autokbisw", targets: ["autokbisw"]), 10 | .library(name: "AutokbiswCore", targets: ["AutokbiswCore"]), 11 | ], 12 | dependencies: [ 13 | // Dependencies declare other packages that this package depends on. 14 | // .package(url: /* package url */, from: "1.0.0"), 15 | .package(url: "https://github.com/apple/swift-argument-parser", from: "1.0.0"), 16 | ], 17 | targets: [ 18 | // Targets are the basic building blocks of a package. A target can define a module or a test suite. 19 | // Targets can depend on other targets in this package, and on products in packages which this package depends on. 20 | .target( 21 | name: "AutokbiswCore", 22 | dependencies: [ 23 | .product(name: "ArgumentParser", package: "swift-argument-parser"), 24 | ] 25 | ), 26 | .target( 27 | name: "autokbisw", 28 | dependencies: ["AutokbiswCore"] 29 | ), 30 | .testTarget( 31 | name: "autokbiswTests", 32 | dependencies: ["AutokbiswCore"] 33 | ), 34 | ] 35 | ) 36 | -------------------------------------------------------------------------------- /.github/workflows/release.yml: -------------------------------------------------------------------------------- 1 | name: Publish 2 | 3 | on: 4 | push: 5 | tags: 6 | - '*' 7 | 8 | jobs: 9 | publish: 10 | name: Publish binaries for ${{ matrix.os }} ${{ matrix.os_name }} (${{ matrix.arch }}) 11 | runs-on: ${{ matrix.os }} 12 | strategy: 13 | matrix: 14 | os: [macos-13, macos-14, macos-15] 15 | arch: [arm64, x86_64] 16 | include: 17 | - os: macos-13 18 | os_name: ventura 19 | - os: macos-14 20 | os_name: sonoma 21 | - os: macos-15 22 | os_name: sequoia 23 | steps: 24 | - uses: actions/checkout@v3 25 | 26 | - name: Build binary 27 | run: swift build --configuration release --arch ${{ matrix.arch }} 28 | 29 | - name: Generate archive name 30 | uses: haya14busa/action-cond@v1 31 | id: archive-name 32 | with: 33 | cond: ${{ matrix.arch == 'arm64' }} 34 | if_true: autokbisw-${{github.ref_name}}.arm64_${{ matrix.os_name }}.tar.gz 35 | if_false: autokbisw-${{github.ref_name}}.${{ matrix.os_name }}.tar.gz 36 | 37 | - name: Create archive 38 | run: | 39 | cd .build/release 40 | tar -czf ${{ steps.archive-name.outputs.value }} autokbisw 41 | 42 | - name: Generate checksum 43 | run: | 44 | cd .build/release 45 | shasum -a 256 ${{ steps.archive-name.outputs.value }} > SHA256SUM 46 | 47 | - name: Upload archive to release 48 | uses: svenstaro/upload-release-action@v2 49 | with: 50 | repo_token: ${{ secrets.GITHUB_TOKEN }} 51 | file: .build/release/${{ steps.archive-name.outputs.value }} 52 | asset_name: ${{ steps.archive-name.outputs.value }} 53 | tag: ${{ github.ref }} 54 | overwrite: true 55 | 56 | - name: Upload checksum artifact 57 | uses: actions/upload-artifact@v4 58 | with: 59 | name: checksums-${{ matrix.os_name }}-${{ matrix.arch }} 60 | path: .build/release/SHA256SUM 61 | 62 | publish-checksums: 63 | needs: publish 64 | runs-on: ubuntu-latest 65 | steps: 66 | - name: Download all checksums 67 | uses: actions/download-artifact@v4 68 | with: 69 | path: checksums 70 | 71 | - name: Combine checksums 72 | run: | 73 | cat checksums/**/SHA256SUM > SHA256SUMS 74 | find checksums -type f -name "SHA256SUM" -exec cat {} + > SHA256SUMS 75 | echo "Combined checksums:" 76 | cat SHA256SUMS 77 | 78 | - name: Upload combined checksums to release 79 | uses: svenstaro/upload-release-action@v2 80 | with: 81 | repo_token: ${{ secrets.GITHUB_TOKEN }} 82 | file: SHA256SUMS 83 | asset_name: SHA256SUMS 84 | tag: ${{ github.ref }} 85 | overwrite: true 86 | -------------------------------------------------------------------------------- /Sources/autokbisw/main.swift: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Jean Helou 2 | // Copyright 2024 Ole Hüter 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | 16 | import ArgumentParser 17 | import AutokbiswCore 18 | import Foundation 19 | 20 | struct Autokbisw: ParsableCommand { 21 | private static let defaultUsagePage: Int = 0x01 22 | private static let defaultUsage: Int = 6 23 | 24 | private static func createMonitor(useLocation: Bool = false, verbosity: Int = 0) -> IOKeyEventMonitor? { 25 | IOKeyEventMonitor( 26 | usagePage: defaultUsagePage, 27 | usage: defaultUsage, 28 | useLocation: useLocation, 29 | verbosity: verbosity 30 | ) 31 | } 32 | 33 | static var configuration = CommandConfiguration( 34 | abstract: "Automatic keyboard/input source switching for macOS.", 35 | subcommands: [Enable.self, Disable.self, List.self, Clear.self] 36 | ) 37 | 38 | @Option( 39 | name: .shortAndLong, 40 | help: ArgumentHelp( 41 | "Print verbose output (1 = DEBUG, 2 = TRACE).", 42 | valueName: "verbosity" 43 | ) 44 | ) 45 | var verbose = 0 46 | 47 | @Flag( 48 | name: .shortAndLong, 49 | help: ArgumentHelp( 50 | "Use locationId to identify keyboards.", 51 | 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." 52 | ) 53 | ) 54 | var location = false 55 | 56 | mutating func run() throws { 57 | if verbose > 0 { 58 | print("Starting with useLocation: \(location) - verbosity: \(verbose)") 59 | } 60 | let monitor = Autokbisw.createMonitor(useLocation: location, verbosity: verbose) 61 | monitor?.start() 62 | CFRunLoopRun() 63 | } 64 | 65 | struct Enable: ParsableCommand { 66 | static var configuration = CommandConfiguration( 67 | commandName: "enable", 68 | abstract: "Enable input source switching for ." 69 | ) 70 | 71 | @Argument(help: "The device identifier or number (from list command) to enable") 72 | var keyboard: String 73 | 74 | func run() throws { 75 | let monitor = Autokbisw.createMonitor() 76 | if let number = Int(keyboard) { 77 | monitor?.enableDeviceByNumber(number) 78 | } else { 79 | monitor?.enableDevice(keyboard) 80 | } 81 | } 82 | } 83 | 84 | struct Disable: ParsableCommand { 85 | static var configuration = CommandConfiguration( 86 | commandName: "disable", 87 | abstract: "Disable input source switching for ." 88 | ) 89 | 90 | @Argument(help: "The device identifier or number (from list command) to disable") 91 | var keyboard: String 92 | 93 | func run() throws { 94 | let monitor = Autokbisw.createMonitor() 95 | if let number = Int(keyboard) { 96 | monitor?.disableDeviceByNumber(number) 97 | } else { 98 | monitor?.disableDevice(keyboard) 99 | } 100 | } 101 | } 102 | 103 | struct List: ParsableCommand { 104 | static var configuration = CommandConfiguration( 105 | commandName: "list", 106 | abstract: "List all known devices and their current status." 107 | ) 108 | 109 | func run() throws { 110 | let monitor = Autokbisw.createMonitor() 111 | print(monitor?.getDevicesString() ?? "") 112 | } 113 | } 114 | 115 | struct Clear: ParsableCommand { 116 | static var configuration = CommandConfiguration( 117 | commandName: "clear", 118 | abstract: "Clear all stored mappings and device settings." 119 | ) 120 | 121 | func run() throws { 122 | let monitor = Autokbisw.createMonitor() 123 | monitor?.clearAllSettings() 124 | print("All stored settings have been cleared.") 125 | } 126 | } 127 | } 128 | 129 | Autokbisw.main() 130 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # autokbisw – Automatic keyboard input language switcher 2 | 3 | Automatic keyboard input language switching for macOS. 4 | 5 | `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. 6 | 7 | ## Features 8 | 9 | - Automatically switches the keyboard layout (input source) based on the connected keyboard 10 | - Identifies keyboards by their product name, hardware ID, and optionally the connected USB port (location ID) 11 | - Command-line interface to enable/disable switching for specific keyboards 12 | 13 | ## Installation 14 | 15 | The easiest way to install `autokbisw` as a background service is by using [Homebrew](https://brew.sh): 16 | 17 | ```sh 18 | brew install ohueter/tap/autokbisw 19 | brew services start autokbisw 20 | ``` 21 | 22 | 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. 23 | 24 | `autokbisw` requires privileges to monitor all keyboard input. You need to grant these privileges on the first start of the service. 25 | 26 | ### Upgrading an existing installation 27 | 28 | If you already have `autokbisw` installed, you can upgrade it by running the following command: 29 | 30 | ```sh 31 | brew upgrade ohueter/tap/autokbisw 32 | ``` 33 | 34 | This will update the formula to the latest version and reinstall it. 35 | 36 | ## Getting started 37 | 38 | - Begin typing with your first keyboard, so it becomes the **active keyboard**. 39 | - Select the desired **keyboard layout** for your first keyboard by selecting it in the menu bar or pressing the 🌐 key. 40 | - Begin typing with your second keyboard, so it becomes the **active keyboard**. 41 | - Select the desired **keyboard layout** for your second keyboard. 42 | - Repeat if you are using more keyboards. 43 | 44 | 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. 45 | 46 | ## Enabling/disabling switching for specific keyboards 47 | 48 | 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. 49 | 50 | ### Listing Devices 51 | 52 | To list all known devices and their current status: 53 | 54 | ```sh 55 | autokbisw list 56 | ``` 57 | 58 | This will display a numbered list of devices with their identifier, status (enabled/disabled), and the associated keyboard layout. 59 | 60 | Note: Devices only appear in this list after they've been used for text input while `autokbisw` was running. 61 | 62 | ### Enabling/disabling switching 63 | 64 | To enable keyboard layout switching for a specific keyboard: 65 | 66 | ```sh 67 | autokbisw enable 68 | ``` 69 | 70 | To disable keyboard layout switching for a specific keyboard: 71 | 72 | ```sh 73 | autokbisw disable 74 | ``` 75 | 76 | You can use either the device number (obtained from the `list` subcommand) or the device identifier to specify the keyboard. 77 | 78 | ## Building from source 79 | 80 | Clone this repository, make sure you have a full Xcode.app installation, and run the following commands: 81 | 82 | ```sh 83 | cd autokbisw 84 | swift build --configuration release 85 | ``` 86 | 87 | The output will provide the path to the built binary, likely `.build/release/autokbisw`. You can run it from the `release` directory as is. 88 | 89 | ### Command-line arguments 90 | 91 | ``` 92 | OVERVIEW: Automatic keyboard/input source switching for macOS. 93 | 94 | USAGE: autokbisw [--verbose ] [--location] 95 | 96 | OPTIONS: 97 | -v, --verbose 98 | Print verbose output (1 = DEBUG, 2 = TRACE). (default: 0) 99 | -l, --location Use locationId to identify keyboards. 100 | Note that the locationId changes when you plug a keyboard in a different port. Therefore using the locationId in the keyboards 101 | identifiers means the configured language will be associated to a keyboard on a specific port. 102 | -h, --help Show help information. 103 | 104 | SUBCOMMANDS: 105 | enable Enable input source switching for . 106 | disable Disable input source switching for . 107 | list List all known devices and their current status. 108 | clear Clear all stored mappings and device settings. 109 | 110 | See 'autokbisw help ' for detailed help. 111 | ``` 112 | 113 | ## FAQ & Common issues 114 | 115 | ### The installation fails with an XCode error. 116 | 117 | 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 118 | 119 | ```sh 120 | xcode-select --print-path 121 | ``` 122 | 123 | in the terminal. The expected output is `/Applications/Xcode.app/Contents/Developer`. If the output on your system is different, run 124 | 125 | ```sh 126 | sudo xcode-select --switch /Applications/Xcode.app/Contents/Developer 127 | ``` 128 | 129 | to set the correct path and (hopefully) fix the compilation. 130 | 131 | ### autokbisw doesn't work after installation. 132 | 133 | If `autokbisw` isn't working after the first start of the service, try these solutions: 134 | 135 | 1. Restart the service: 136 | 137 | ```sh 138 | brew services restart autokbisw 139 | ``` 140 | 141 | 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). 142 | 143 | ### autokbisw doesn't work as expected with my Logitech keyboard or mouse. 144 | 145 | 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. 146 | 147 | ### Can autokbisw be used with the `Automatically switch to a document's input source` option? 148 | 149 | `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)). 150 | 151 | ### Can autokbisw be used with Karabiner-Elements? 152 | 153 | `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). 154 | 155 | ### autokbisw is installed correctly but the background service does not changes the language? 156 | 157 | Try to unload and reload the plist and reboot (see [discussion for reference](https://github.com/ohueter/autokbisw/discussions/38#discussioncomment-9127439)): 158 | 159 | ```sh 160 | launchctl unload ~/Library/LaunchAgents/homebrew.mxcl.autokbisw.plist 161 | launchctl load ~/Library/LaunchAgents/homebrew.mxcl.autokbisw.plist 162 | ``` 163 | 164 | ## Acknowledgements 165 | 166 | This program was originally developed by [Jean Helou](https://github.com/jeantil/autokbisw) ([@jeantil](https://github.com/jeantil)). 167 | -------------------------------------------------------------------------------- /Tests/autokbiswTests/IOKeyEventMonitorTests.swift: -------------------------------------------------------------------------------- 1 | // Copyright 2024 Ole Hüter 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 | @testable import AutokbiswCore 16 | import XCTest 17 | 18 | class IOKeyEventMonitorTests: XCTestCase { 19 | var monitor: IOKeyEventMonitor! 20 | var mockUserDefaults: UserDefaults! 21 | 22 | override func setUp() { 23 | super.setUp() 24 | 25 | mockUserDefaults = UserDefaults(suiteName: #file) // Create an in-memory UserDefaults 26 | mockUserDefaults.removePersistentDomain(forName: #file) // Ensure it's empty 27 | 28 | // Initialize the monitor before each test 29 | monitor = IOKeyEventMonitor(usagePage: 0x01, usage: 6, useLocation: true, verbosity: 0, userDefaults: mockUserDefaults) 30 | } 31 | 32 | override func tearDown() { 33 | // Clean up after each test 34 | mockUserDefaults.removePersistentDomain(forName: #file) 35 | monitor = nil 36 | mockUserDefaults = nil 37 | super.tearDown() 38 | } 39 | 40 | func testInitialization() { 41 | XCTAssertNotNil(monitor, "IOKeyEventMonitor should be successfully initialized") 42 | } 43 | 44 | func testStoreAndRestoreInputSource() { 45 | let testKeyboard = "TestKeyboard-[1-2-TestManufacturer-123-456]" 46 | 47 | // Store a mock input source 48 | monitor.storeInputSource(keyboard: testKeyboard) 49 | 50 | // Verify that the input source was stored 51 | XCTAssertNotNil(monitor.kb2is[testKeyboard], "Input source should be stored for the test keyboard") 52 | 53 | // Attempt to restore the input source 54 | monitor.restoreInputSource(keyboard: testKeyboard) 55 | 56 | // We can't easily verify if TISSelectInputSource was called correctly, 57 | // but we can check that no error was thrown 58 | } 59 | 60 | func testOnKeyboardEvent() { 61 | let testKeyboard1 = "TestKeyboard1-[1-2-TestManufacturer-123-456]" 62 | let testKeyboard2 = "TestKeyboard2-[3-4-TestManufacturer-789-012]" 63 | 64 | monitor.onKeyboardEvent(keyboard: testKeyboard1) 65 | XCTAssertEqual(monitor.lastActiveKeyboard, testKeyboard1, "Last active keyboard should be updated") 66 | 67 | monitor.onKeyboardEvent(keyboard: testKeyboard2) 68 | XCTAssertEqual(monitor.lastActiveKeyboard, testKeyboard2, "Last active keyboard should be updated to the new keyboard") 69 | } 70 | 71 | func testEnableDevice() { 72 | let testKeyboard = "TestKeyboard-[1-2-TestManufacturer-123-456]" 73 | monitor.enableDevice(testKeyboard) 74 | XCTAssertTrue(monitor.deviceEnabled[testKeyboard] ?? false, "Device should be enabled") 75 | } 76 | 77 | func testDisableDevice() { 78 | let testKeyboard = "TestKeyboard-[1-2-TestManufacturer-123-456]" 79 | monitor.disableDevice(testKeyboard) 80 | XCTAssertFalse(monitor.deviceEnabled[testKeyboard] ?? true, "Device should be disabled") 81 | } 82 | 83 | func testClearAllSettings() { 84 | let testKeyboard = "TestKeyboard-[1-2-TestManufacturer-123-456]" 85 | monitor.storeInputSource(keyboard: testKeyboard) 86 | monitor.enableDevice(testKeyboard) 87 | 88 | monitor.clearAllSettings() 89 | 90 | XCTAssertTrue(monitor.kb2is.isEmpty, "kb2is should be empty after clearing settings") 91 | XCTAssertTrue(monitor.deviceEnabled.isEmpty, "deviceEnabled should be empty after clearing settings") 92 | XCTAssertNil(monitor.lastActiveKeyboard, "lastActiveKeyboard should be nil after clearing settings") 93 | } 94 | 95 | func testStoreInputSourceWithConformsToKeyboard() { 96 | let testKeyboard = "TestKeyboard-[1-2-TestManufacturer-123-456]" 97 | 98 | // Test storing with conformsToKeyboard = true 99 | monitor.storeInputSource(keyboard: testKeyboard, conformsToKeyboard: true) 100 | XCTAssertTrue(monitor.deviceEnabled[testKeyboard] ?? false, "Device should be enabled when conformsToKeyboard is true") 101 | 102 | // Clear settings 103 | monitor.clearAllSettings() 104 | 105 | // Test storing with conformsToKeyboard = false 106 | monitor.storeInputSource(keyboard: testKeyboard, conformsToKeyboard: false) 107 | XCTAssertFalse(monitor.deviceEnabled[testKeyboard] ?? true, "Device should be disabled when conformsToKeyboard is false") 108 | 109 | // Test storing without conformsToKeyboard 110 | monitor.clearAllSettings() 111 | monitor.storeInputSource(keyboard: testKeyboard) 112 | XCTAssertNil(monitor.deviceEnabled[testKeyboard], "Device enabled status should not be set when conformsToKeyboard is not provided") 113 | } 114 | 115 | func testOnKeyboardEventWithConformsToKeyboard() { 116 | let testKeyboard = "TestKeyboard-[1-2-TestManufacturer-123-456]" 117 | 118 | // Test with conformsToKeyboard = true 119 | monitor.onKeyboardEvent(keyboard: testKeyboard, conformsToKeyboard: true) 120 | XCTAssertTrue(monitor.deviceEnabled[testKeyboard] ?? false, "Device should be enabled when conformsToKeyboard is true") 121 | XCTAssertEqual(monitor.lastActiveKeyboard, testKeyboard, "Last active keyboard should be updated") 122 | 123 | // Clear settings 124 | monitor.clearAllSettings() 125 | 126 | // Test with conformsToKeyboard = false 127 | monitor.onKeyboardEvent(keyboard: testKeyboard, conformsToKeyboard: false) 128 | XCTAssertFalse(monitor.deviceEnabled[testKeyboard] ?? true, "Device should be disabled when conformsToKeyboard is false") 129 | XCTAssertEqual(monitor.lastActiveKeyboard, testKeyboard, "Last active keyboard should be updated even for disabled device") 130 | } 131 | 132 | func testPrintDevices() { 133 | let testKeyboard1 = "TestKeyboard1-[1-2-TestManufacturer-123-456]" 134 | let testKeyboard2 = "TestKeyboard2-[3-4-TestManufacturer-789-012]" 135 | 136 | monitor.enableDevice(testKeyboard1) 137 | monitor.disableDevice(testKeyboard2) 138 | 139 | let output = monitor.getDevicesString() 140 | 141 | XCTAssertTrue(output.contains("\(testKeyboard1): enabled"), "Output should show TestKeyboard1 as enabled") 142 | XCTAssertTrue(output.contains("\(testKeyboard2): disabled"), "Output should show TestKeyboard2 as disabled") 143 | } 144 | 145 | func testEnableDeviceByNumber() { 146 | let testKeyboard1 = "ATestKeyboard1-[1-2-TestManufacturer-123-456]" 147 | let testKeyboard2 = "BTestKeyboard2-[3-4-TestManufacturer-789-012]" 148 | 149 | // Setup initial state 150 | monitor.enableDevice(testKeyboard1) 151 | monitor.enableDevice(testKeyboard2) 152 | monitor.disableDevice(testKeyboard2) // Should be: keyboard1 enabled, keyboard2 disabled 153 | 154 | // Enable device #2 (testKeyboard2) 155 | monitor.enableDeviceByNumber(2) 156 | 157 | XCTAssertTrue(monitor.deviceEnabled[testKeyboard2] ?? false, "Device #2 should be enabled") 158 | XCTAssertTrue(monitor.deviceEnabled[testKeyboard1] ?? false, "Device #1 should remain enabled") 159 | } 160 | 161 | func testDisableDeviceByNumber() { 162 | let testKeyboard1 = "ATestKeyboard1-[1-2-TestManufacturer-123-456]" 163 | let testKeyboard2 = "BTestKeyboard2-[3-4-TestManufacturer-789-012]" 164 | 165 | // Setup initial state 166 | monitor.enableDevice(testKeyboard1) 167 | monitor.enableDevice(testKeyboard2) 168 | 169 | // Disable device #1 (testKeyboard1) 170 | monitor.disableDeviceByNumber(1) 171 | 172 | XCTAssertFalse(monitor.deviceEnabled[testKeyboard1] ?? true, "Device #1 should be disabled") 173 | XCTAssertTrue(monitor.deviceEnabled[testKeyboard2] ?? false, "Device #2 should remain enabled") 174 | } 175 | 176 | func testDeviceNumbering() { 177 | let testKeyboard1 = "XTestKeyboard1-[1-2-TestManufacturer-123-456]" 178 | let testKeyboard2 = "BTestKeyboard2-[3-4-TestManufacturer-789-012]" 179 | 180 | monitor.enableDevice(testKeyboard1) 181 | monitor.enableDevice(testKeyboard2) 182 | 183 | let output = monitor.getDevicesString() 184 | let lines = output.split(separator: "\n") 185 | 186 | XCTAssertTrue(lines[0].starts(with: "1. BTestKeyboard2"), "Second device should be numbered 1") 187 | XCTAssertTrue(lines[1].starts(with: "2. XTestKeyboard1"), "First device should be numbered 2") 188 | } 189 | 190 | func testInvalidDeviceNumber() { 191 | let testKeyboard = "TestKeyboard-[1-2-TestManufacturer-123-456]" 192 | monitor.enableDevice(testKeyboard) 193 | 194 | // Test invalid numbers 195 | monitor.enableDeviceByNumber(0) // Too low 196 | monitor.enableDeviceByNumber(2) // Too high 197 | monitor.disableDeviceByNumber(0) // Too low 198 | monitor.disableDeviceByNumber(2) // Too high 199 | 200 | // State should remain unchanged 201 | XCTAssertTrue(monitor.deviceEnabled[testKeyboard] ?? false, "Device state should not change with invalid number") 202 | } 203 | 204 | func testAddNewKeyboardBasedOnMapping() { 205 | let testKeyboard = "TestKeyboard-[1-2-TestManufacturer-123-456]" 206 | 207 | // Test first keyboard with conformsToKeyboard = true 208 | monitor.onKeyboardEvent(keyboard: testKeyboard, conformsToKeyboard: true) 209 | XCTAssertNotNil(monitor.kb2is[testKeyboard], "Keyboard should have input source mapping") 210 | XCTAssertTrue(monitor.deviceEnabled[testKeyboard] ?? false, "Keyboard should be enabled when conformsToKeyboard is true") 211 | 212 | // Clear settings and test with conformsToKeyboard = false 213 | monitor.clearAllSettings() 214 | monitor.onKeyboardEvent(keyboard: testKeyboard, conformsToKeyboard: false) 215 | XCTAssertNotNil(monitor.kb2is[testKeyboard], "Keyboard should have input source mapping") 216 | XCTAssertFalse(monitor.deviceEnabled[testKeyboard] ?? true, "Keyboard should be disabled when conformsToKeyboard is false") 217 | 218 | // Test that subsequent events don't change the mapping or enabled state 219 | monitor.onKeyboardEvent(keyboard: testKeyboard, conformsToKeyboard: true) 220 | XCTAssertFalse(monitor.deviceEnabled[testKeyboard] ?? true, "Enabled state should not change for existing keyboard") 221 | 222 | // Test with a second keyboard 223 | let testKeyboard2 = "TestKeyboard2-[3-4-TestManufacturer-789-012]" 224 | monitor.onKeyboardEvent(keyboard: testKeyboard2, conformsToKeyboard: true) 225 | XCTAssertNotNil(monitor.kb2is[testKeyboard2], "Second keyboard should have input source mapping") 226 | XCTAssertTrue(monitor.deviceEnabled[testKeyboard2] ?? false, "Second keyboard should be enabled") 227 | XCTAssertFalse(monitor.deviceEnabled[testKeyboard] ?? true, "First keyboard should remain disabled") 228 | } 229 | } 230 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | 2 | Apache License 3 | Version 2.0, January 2004 4 | http://www.apache.org/licenses/ 5 | 6 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 7 | 8 | 1. Definitions. 9 | 10 | "License" shall mean the terms and conditions for use, reproduction, 11 | and distribution as defined by Sections 1 through 9 of this document. 12 | 13 | "Licensor" shall mean the copyright owner or entity authorized by 14 | the copyright owner that is granting the License. 15 | 16 | "Legal Entity" shall mean the union of the acting entity and all 17 | other entities that control, are controlled by, or are under common 18 | control with that entity. For the purposes of this definition, 19 | "control" means (i) the power, direct or indirect, to cause the 20 | direction or management of such entity, whether by contract or 21 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 22 | outstanding shares, or (iii) beneficial ownership of such entity. 23 | 24 | "You" (or "Your") shall mean an individual or Legal Entity 25 | exercising permissions granted by this License. 26 | 27 | "Source" form shall mean the preferred form for making modifications, 28 | including but not limited to software source code, documentation 29 | source, and configuration files. 30 | 31 | "Object" form shall mean any form resulting from mechanical 32 | transformation or translation of a Source form, including but 33 | not limited to compiled object code, generated documentation, 34 | and conversions to other media types. 35 | 36 | "Work" shall mean the work of authorship, whether in Source or 37 | Object form, made available under the License, as indicated by a 38 | copyright notice that is included in or attached to the work 39 | (an example is provided in the Appendix below). 40 | 41 | "Derivative Works" shall mean any work, whether in Source or Object 42 | form, that is based on (or derived from) the Work and for which the 43 | editorial revisions, annotations, elaborations, or other modifications 44 | represent, as a whole, an original work of authorship. For the purposes 45 | of this License, Derivative Works shall not include works that remain 46 | separable from, or merely link (or bind by name) to the interfaces of, 47 | the Work and Derivative Works thereof. 48 | 49 | "Contribution" shall mean any work of authorship, including 50 | the original version of the Work and any modifications or additions 51 | to that Work or Derivative Works thereof, that is intentionally 52 | submitted to Licensor for inclusion in the Work by the copyright owner 53 | or by an individual or Legal Entity authorized to submit on behalf of 54 | the copyright owner. For the purposes of this definition, "submitted" 55 | means any form of electronic, verbal, or written communication sent 56 | to the Licensor or its representatives, including but not limited to 57 | communication on electronic mailing lists, source code control systems, 58 | and issue tracking systems that are managed by, or on behalf of, the 59 | Licensor for the purpose of discussing and improving the Work, but 60 | excluding communication that is conspicuously marked or otherwise 61 | designated in writing by the copyright owner as "Not a Contribution." 62 | 63 | "Contributor" shall mean Licensor and any individual or Legal Entity 64 | on behalf of whom a Contribution has been received by Licensor and 65 | subsequently incorporated within the Work. 66 | 67 | 2. Grant of Copyright License. Subject to the terms and conditions of 68 | this License, each Contributor hereby grants to You a perpetual, 69 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 70 | copyright license to reproduce, prepare Derivative Works of, 71 | publicly display, publicly perform, sublicense, and distribute the 72 | Work and such Derivative Works in Source or Object form. 73 | 74 | 3. Grant of Patent License. Subject to the terms and conditions of 75 | this License, each Contributor hereby grants to You a perpetual, 76 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 77 | (except as stated in this section) patent license to make, have made, 78 | use, offer to sell, sell, import, and otherwise transfer the Work, 79 | where such license applies only to those patent claims licensable 80 | by such Contributor that are necessarily infringed by their 81 | Contribution(s) alone or by combination of their Contribution(s) 82 | with the Work to which such Contribution(s) was submitted. If You 83 | institute patent litigation against any entity (including a 84 | cross-claim or counterclaim in a lawsuit) alleging that the Work 85 | or a Contribution incorporated within the Work constitutes direct 86 | or contributory patent infringement, then any patent licenses 87 | granted to You under this License for that Work shall terminate 88 | as of the date such litigation is filed. 89 | 90 | 4. Redistribution. You may reproduce and distribute copies of the 91 | Work or Derivative Works thereof in any medium, with or without 92 | modifications, and in Source or Object form, provided that You 93 | meet the following conditions: 94 | 95 | (a) You must give any other recipients of the Work or 96 | Derivative Works a copy of this License; and 97 | 98 | (b) You must cause any modified files to carry prominent notices 99 | stating that You changed the files; and 100 | 101 | (c) You must retain, in the Source form of any Derivative Works 102 | that You distribute, all copyright, patent, trademark, and 103 | attribution notices from the Source form of the Work, 104 | excluding those notices that do not pertain to any part of 105 | the Derivative Works; and 106 | 107 | (d) If the Work includes a "NOTICE" text file as part of its 108 | distribution, then any Derivative Works that You distribute must 109 | include a readable copy of the attribution notices contained 110 | within such NOTICE file, excluding those notices that do not 111 | pertain to any part of the Derivative Works, in at least one 112 | of the following places: within a NOTICE text file distributed 113 | as part of the Derivative Works; within the Source form or 114 | documentation, if provided along with the Derivative Works; or, 115 | within a display generated by the Derivative Works, if and 116 | wherever such third-party notices normally appear. The contents 117 | of the NOTICE file are for informational purposes only and 118 | do not modify the License. You may add Your own attribution 119 | notices within Derivative Works that You distribute, alongside 120 | or as an addendum to the NOTICE text from the Work, provided 121 | that such additional attribution notices cannot be construed 122 | as modifying the License. 123 | 124 | You may add Your own copyright statement to Your modifications and 125 | may provide additional or different license terms and conditions 126 | for use, reproduction, or distribution of Your modifications, or 127 | for any such Derivative Works as a whole, provided Your use, 128 | reproduction, and distribution of the Work otherwise complies with 129 | the conditions stated in this License. 130 | 131 | 5. Submission of Contributions. Unless You explicitly state otherwise, 132 | any Contribution intentionally submitted for inclusion in the Work 133 | by You to the Licensor shall be under the terms and conditions of 134 | this License, without any additional terms or conditions. 135 | Notwithstanding the above, nothing herein shall supersede or modify 136 | the terms of any separate license agreement you may have executed 137 | with Licensor regarding such Contributions. 138 | 139 | 6. Trademarks. This License does not grant permission to use the trade 140 | names, trademarks, service marks, or product names of the Licensor, 141 | except as required for reasonable and customary use in describing the 142 | origin of the Work and reproducing the content of the NOTICE file. 143 | 144 | 7. Disclaimer of Warranty. Unless required by applicable law or 145 | agreed to in writing, Licensor provides the Work (and each 146 | Contributor provides its Contributions) on an "AS IS" BASIS, 147 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 148 | implied, including, without limitation, any warranties or conditions 149 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 150 | PARTICULAR PURPOSE. You are solely responsible for determining the 151 | appropriateness of using or redistributing the Work and assume any 152 | risks associated with Your exercise of permissions under this License. 153 | 154 | 8. Limitation of Liability. In no event and under no legal theory, 155 | whether in tort (including negligence), contract, or otherwise, 156 | unless required by applicable law (such as deliberate and grossly 157 | negligent acts) or agreed to in writing, shall any Contributor be 158 | liable to You for damages, including any direct, indirect, special, 159 | incidental, or consequential damages of any character arising as a 160 | result of this License or out of the use or inability to use the 161 | Work (including but not limited to damages for loss of goodwill, 162 | work stoppage, computer failure or malfunction, or any and all 163 | other commercial damages or losses), even if such Contributor 164 | has been advised of the possibility of such damages. 165 | 166 | 9. Accepting Warranty or Additional Liability. While redistributing 167 | the Work or Derivative Works thereof, You may choose to offer, 168 | and charge a fee for, acceptance of support, warranty, indemnity, 169 | or other liability obligations and/or rights consistent with this 170 | License. However, in accepting such obligations, You may act only 171 | on Your own behalf and on Your sole responsibility, not on behalf 172 | of any other Contributor, and only if You agree to indemnify, 173 | defend, and hold each Contributor harmless for any liability 174 | incurred by, or claims asserted against, such Contributor by reason 175 | of your accepting any such warranty or additional liability. 176 | 177 | END OF TERMS AND CONDITIONS 178 | 179 | APPENDIX: How to apply the Apache License to your work. 180 | 181 | To apply the Apache License to your work, attach the following 182 | boilerplate notice, with the fields enclosed by brackets "[]" 183 | replaced with your own identifying information. (Don't include 184 | the brackets!) The text should be enclosed in the appropriate 185 | comment syntax for the file format. We also recommend that a 186 | file or class name and description of purpose be included on the 187 | same "printed page" as the copyright notice for easier 188 | identification within third-party archives. 189 | 190 | Copyright [yyyy] [name of copyright owner] 191 | 192 | Licensed under the Apache License, Version 2.0 (the "License"); 193 | you may not use this file except in compliance with the License. 194 | You may obtain a copy of the License at 195 | 196 | http://www.apache.org/licenses/LICENSE-2.0 197 | 198 | Unless required by applicable law or agreed to in writing, software 199 | distributed under the License is distributed on an "AS IS" BASIS, 200 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 201 | See the License for the specific language governing permissions and 202 | limitations under the License. 203 | -------------------------------------------------------------------------------- /Sources/AutokbiswCore/IOKeyEventMonitor.swift: -------------------------------------------------------------------------------- 1 | // Copyright 2016 Jean Helou 2 | // Copyright 2024 Ole Hüter 3 | // 4 | // Licensed under the Apache License, Version 2.0 (the "License"); 5 | // you may not use this file except in compliance with the License. 6 | // You may obtain a copy of the License at 7 | // 8 | // http://www.apache.org/licenses/LICENSE-2.0 9 | // 10 | // Unless required by applicable law or agreed to in writing, software 11 | // distributed under the License is distributed on an "AS IS" BASIS, 12 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | // See the License for the specific language governing permissions and 14 | // limitations under the License. 15 | 16 | import Carbon 17 | import Foundation 18 | import IOKit 19 | import IOKit.hid 20 | import IOKit.usb 21 | 22 | public final class IOKeyEventMonitor { 23 | private let log: Logger 24 | 25 | private let hidManager: IOHIDManager 26 | fileprivate let notificationCenter: CFNotificationCenter 27 | 28 | fileprivate let MAPPINGS_DEFAULTS_KEY = "keyboardISMapping" 29 | fileprivate var defaults: UserDefaults = .standard 30 | 31 | fileprivate let MAPPING_ENABLED_KEY = "mappingEnabled" 32 | var deviceEnabled: [String: Bool] = [:] 33 | 34 | fileprivate let assignmentLock = NSLock() 35 | var lastActiveKeyboard: String? 36 | var kb2is: [String: TISInputSource] = .init() 37 | 38 | fileprivate var useLocation: Bool 39 | 40 | public init? (usagePage: Int, usage: Int, useLocation: Bool, verbosity: Int, userDefaults: UserDefaults = .standard) { 41 | self.useLocation = useLocation 42 | log = Logger(verbosity: verbosity) 43 | defaults = userDefaults 44 | 45 | hidManager = IOHIDManagerCreate(kCFAllocatorDefault, IOOptionBits(kIOHIDOptionsTypeNone)) 46 | notificationCenter = CFNotificationCenterGetDistributedCenter() 47 | let deviceMatch: CFMutableDictionary = [kIOHIDDeviceUsageKey: usage, kIOHIDDeviceUsagePageKey: usagePage] as NSMutableDictionary 48 | IOHIDManagerSetDeviceMatching(hidManager, deviceMatch) 49 | 50 | loadMappings() 51 | } 52 | 53 | deinit { 54 | self.saveMappings() 55 | stopObservingSettingsChanges() 56 | 57 | let context = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque()) 58 | IOHIDManagerRegisterInputValueCallback(hidManager, Optional.none, context) 59 | CFNotificationCenterRemoveObserver(notificationCenter, context, CFNotificationName(kTISNotifySelectedKeyboardInputSourceChanged), nil) 60 | } 61 | 62 | public func start() { 63 | let context = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque()) 64 | 65 | observeIputSourceChangedNotification(context: context) 66 | registerHIDKeyboardCallback(context: context) 67 | 68 | IOHIDManagerScheduleWithRunLoop(hidManager, CFRunLoopGetMain(), CFRunLoopMode.defaultMode!.rawValue) 69 | IOHIDManagerOpen(hidManager, IOOptionBits(kIOHIDOptionsTypeNone)) 70 | 71 | startObservingSettingsChanges() 72 | } 73 | 74 | private func observeIputSourceChangedNotification(context: UnsafeMutableRawPointer) { 75 | let inputSourceChanged: CFNotificationCallback = { 76 | _, observer, _, _, _ in 77 | let selfPtr = Unmanaged.fromOpaque(observer!).takeUnretainedValue() 78 | selfPtr.onInputSourceChanged() 79 | } 80 | 81 | CFNotificationCenterAddObserver(notificationCenter, 82 | context, inputSourceChanged, 83 | kTISNotifySelectedKeyboardInputSourceChanged, nil, 84 | CFNotificationSuspensionBehavior.deliverImmediately) 85 | } 86 | 87 | private func registerHIDKeyboardCallback(context: UnsafeMutableRawPointer) { 88 | let myHIDKeyboardCallback: IOHIDValueCallback = { 89 | context, _, sender, _ in 90 | let selfPtr = Unmanaged.fromOpaque(context!).takeUnretainedValue() 91 | let senderDevice = Unmanaged.fromOpaque(sender!).takeUnretainedValue() 92 | 93 | let conformsToKeyboard = selfPtr.deviceConformsToKeyboard(senderDevice) 94 | 95 | let vendorId = selfPtr.deviceProperty(senderDevice, kIOHIDVendorIDKey) 96 | let productId = selfPtr.deviceProperty(senderDevice, kIOHIDProductIDKey) 97 | let product = selfPtr.deviceProperty(senderDevice, kIOHIDProductKey) 98 | let manufacturer = selfPtr.deviceProperty(senderDevice, kIOHIDManufacturerKey) 99 | let serialNumber = selfPtr.deviceProperty(senderDevice, kIOHIDSerialNumberKey) 100 | let locationId = selfPtr.deviceProperty(senderDevice, kIOHIDLocationIDKey) 101 | let uniqueId = selfPtr.deviceProperty(senderDevice, kIOHIDUniqueIDKey) 102 | 103 | let keyboard = selfPtr.useLocation 104 | ? "\(product)-[\(vendorId)-\(productId)-\(manufacturer)-\(serialNumber)-\(locationId)]" 105 | : "\(product)-[\(vendorId)-\(productId)-\(manufacturer)-\(serialNumber)]" 106 | 107 | selfPtr.log.trace("received event from device \(keyboard) - \(locationId) - \(uniqueId) - conformsToKeyboard: \(conformsToKeyboard)") 108 | selfPtr.onKeyboardEvent(keyboard: keyboard, conformsToKeyboard: conformsToKeyboard) 109 | } 110 | 111 | IOHIDManagerRegisterInputValueCallback(hidManager, myHIDKeyboardCallback, context) 112 | } 113 | 114 | private func deviceProperty(_ device: IOHIDDevice, _ key: String) -> String { 115 | guard let value = IOHIDDeviceGetProperty(device, key as CFString) else { 116 | return "unknown" 117 | } 118 | return String(describing: value) 119 | } 120 | 121 | private func deviceConformsToKeyboard(_ device: IOHIDDevice) -> Bool { 122 | return IOHIDDeviceConformsTo(device, UInt32(kHIDPage_GenericDesktop), UInt32(kHIDUsage_GD_Keyboard)) 123 | } 124 | } 125 | 126 | // MARK: - Input Source Management 127 | 128 | public extension IOKeyEventMonitor { 129 | func restoreInputSource(keyboard: String) { 130 | guard let targetIs = kb2is[keyboard] else { 131 | log.trace("No previous mapping saved for \(keyboard), awaiting the user to select the right one") 132 | return 133 | } 134 | 135 | log.debug("Setting input source for keyboard \(keyboard): \(targetIs)") 136 | 137 | // This will trigger onInputSourceChanged() 138 | TISSelectInputSource(targetIs) 139 | } 140 | 141 | func storeInputSource(keyboard: String, conformsToKeyboard: Bool? = nil) { 142 | let currentSource: TISInputSource = TISCopyCurrentKeyboardInputSource().takeUnretainedValue() 143 | kb2is[keyboard] = currentSource 144 | 145 | // Only set a default value for deviceEnabled if conformsToKeyboard is provided 146 | if let isKeyboard = conformsToKeyboard, deviceEnabled[keyboard] == nil { 147 | log.debug("Enabling device by default because it is recognized as a keyboard") 148 | deviceEnabled[keyboard] = isKeyboard 149 | } 150 | 151 | saveMappings() 152 | } 153 | 154 | func onInputSourceChanged() { 155 | assignmentLock.lock() 156 | // lastActiveKeyboard can be nil only if the language is changed between 157 | // program start and the first keypress, so we can ignore this edge case 158 | if let lastActiveKeyboard = lastActiveKeyboard { 159 | storeInputSource(keyboard: lastActiveKeyboard) 160 | } 161 | assignmentLock.unlock() 162 | } 163 | 164 | func onKeyboardEvent(keyboard: String, conformsToKeyboard: Bool? = nil) { 165 | guard lastActiveKeyboard != keyboard else { 166 | log.trace("change: ignoring event from keyboard \(keyboard) because active device hasn't changed") 167 | return 168 | } 169 | 170 | log.debug("change: keyboard changed from \(lastActiveKeyboard ?? "nil") to \(keyboard)") 171 | 172 | let isEnabled = deviceEnabled[keyboard] ?? true 173 | guard isEnabled else { 174 | log.trace("change: ignoring event from keyboard \(keyboard) because device is disabled") 175 | return 176 | } 177 | 178 | assignmentLock.lock() 179 | if kb2is[keyboard] == nil { 180 | // This keyboard has no mapping yet, store the current input source 181 | log.debug("New device detected: \(keyboard), storing current input source") 182 | storeInputSource(keyboard: keyboard, conformsToKeyboard: conformsToKeyboard) 183 | } else { 184 | // Keyboard is different from the previously used keyboard, restore settings. 185 | restoreInputSource(keyboard: keyboard) 186 | } 187 | 188 | lastActiveKeyboard = keyboard 189 | assignmentLock.unlock() 190 | } 191 | } 192 | 193 | // MARK: - Device Management 194 | 195 | public extension IOKeyEventMonitor { 196 | func enableDevice(_ keyboard: String) { 197 | deviceEnabled[keyboard] = true 198 | saveMappings() 199 | } 200 | 201 | func disableDevice(_ keyboard: String) { 202 | deviceEnabled[keyboard] = false 203 | saveMappings() 204 | } 205 | 206 | func enableDeviceByNumber(_ number: Int) { 207 | let devices = Array(deviceEnabled.keys).sorted() 208 | guard number > 0, number <= devices.count else { 209 | print("Invalid device number") 210 | return 211 | } 212 | let keyboard = devices[number - 1] 213 | deviceEnabled[keyboard] = true 214 | saveMappings() 215 | } 216 | 217 | func disableDeviceByNumber(_ number: Int) { 218 | let devices = Array(deviceEnabled.keys).sorted() 219 | guard number > 0, number <= devices.count else { 220 | print("Invalid device number") 221 | return 222 | } 223 | let keyboard = devices[number - 1] 224 | deviceEnabled[keyboard] = false 225 | saveMappings() 226 | } 227 | 228 | func getDevicesString() -> String { 229 | return deviceEnabled 230 | .sorted { $0.key < $1.key } 231 | .enumerated() 232 | .map { index, entry -> String in 233 | let (keyboard, isEnabled) = entry 234 | let number = index + 1 235 | let status = isEnabled ? "enabled" : "disabled" 236 | var layoutInfo = "no layout stored" 237 | 238 | if let source = kb2is[keyboard] { 239 | let name = TISGetInputSourceProperty(source, kTISPropertyLocalizedName) 240 | let localizedName = unmanagedStringToString(name) ?? "unknown" 241 | let id = is2Id(source) ?? "unknown" 242 | layoutInfo = "\(localizedName) (\(id))" 243 | } 244 | 245 | return "\(number). \(keyboard): \(status) - \(layoutInfo)" 246 | } 247 | .joined(separator: "\n") 248 | } 249 | } 250 | 251 | // MARK: - Persistence 252 | 253 | extension IOKeyEventMonitor { 254 | func loadMappings() { 255 | kb2is.removeAll() 256 | deviceEnabled.removeAll() 257 | 258 | let selectableIsProperties = [ 259 | kTISPropertyInputSourceIsEnableCapable: true, 260 | kTISPropertyInputSourceCategory: kTISCategoryKeyboardInputSource ?? "" as CFString, 261 | ] as CFDictionary 262 | let inputSources = TISCreateInputSourceList(selectableIsProperties, false).takeUnretainedValue() as! [TISInputSource] 263 | 264 | let inputSourcesById = inputSources.reduce([String: TISInputSource]()) { 265 | dict, inputSource -> [String: TISInputSource] in 266 | var dict = dict 267 | if let id = unmanagedStringToString(TISGetInputSourceProperty(inputSource, kTISPropertyInputSourceID)) { 268 | dict[id] = inputSource 269 | } 270 | return dict 271 | } 272 | 273 | if let mappings = defaults.dictionary(forKey: MAPPINGS_DEFAULTS_KEY) { 274 | for (keyboardId, inputSourceId) in mappings { 275 | kb2is[keyboardId] = inputSourcesById[String(describing: inputSourceId)] 276 | } 277 | } 278 | 279 | if let enabledMappings = defaults.dictionary(forKey: MAPPING_ENABLED_KEY) as? [String: Bool] { 280 | deviceEnabled = enabledMappings 281 | } 282 | } 283 | 284 | func saveMappings() { 285 | withPausedSettingsObserver { 286 | let mappings = kb2is.mapValues(is2Id) 287 | defaults.set(mappings, forKey: MAPPINGS_DEFAULTS_KEY) 288 | defaults.set(deviceEnabled, forKey: MAPPING_ENABLED_KEY) 289 | defaults.synchronize() 290 | 291 | postSettingsChangedNotification() 292 | } 293 | 294 | log.trace("Saved keyboard mappings to UserDefaults") 295 | } 296 | 297 | public func clearAllSettings() { 298 | withPausedSettingsObserver { 299 | kb2is.removeAll() 300 | deviceEnabled.removeAll() 301 | lastActiveKeyboard = nil 302 | defaults.removeObject(forKey: MAPPINGS_DEFAULTS_KEY) 303 | defaults.removeObject(forKey: MAPPING_ENABLED_KEY) 304 | defaults.synchronize() 305 | 306 | postSettingsChangedNotification() 307 | } 308 | } 309 | } 310 | 311 | // MARK: - Settings Change Notifications 312 | 313 | private extension IOKeyEventMonitor { 314 | private func startObservingSettingsChanges() { 315 | log.trace("Starting UserDefaults observation") 316 | 317 | let context = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque()) 318 | let callback: CFNotificationCallback = { _, observer, _, _, _ in 319 | let selfPtr = Unmanaged.fromOpaque(observer!).takeUnretainedValue() 320 | selfPtr.log.trace("Received settings change notification") 321 | selfPtr.onSettingsChanged() 322 | } 323 | 324 | CFNotificationCenterAddObserver( 325 | notificationCenter, 326 | context, 327 | callback, 328 | "com.autokbisw.settingsChanged" as CFString, 329 | nil, 330 | .deliverImmediately 331 | ) 332 | } 333 | 334 | private func stopObservingSettingsChanges() { 335 | let context = UnsafeMutableRawPointer(Unmanaged.passUnretained(self).toOpaque()) 336 | CFNotificationCenterRemoveObserver( 337 | notificationCenter, 338 | context, 339 | CFNotificationName("com.autokbisw.settingsChanged" as CFString), 340 | nil 341 | ) 342 | } 343 | 344 | private func postSettingsChangedNotification() { 345 | log.trace("Posting settings changed notification") 346 | CFNotificationCenterPostNotification( 347 | notificationCenter, 348 | CFNotificationName("com.autokbisw.settingsChanged" as CFString), 349 | nil, 350 | nil, 351 | true 352 | ) 353 | } 354 | 355 | private func withPausedSettingsObserver(_ operation: () -> T) -> T { 356 | stopObservingSettingsChanges() 357 | defer { startObservingSettingsChanges() } 358 | return operation() 359 | } 360 | 361 | private func onSettingsChanged() { 362 | loadMappings() 363 | 364 | // If mappings are empty, settings were cleared in another instance 365 | if kb2is.isEmpty, deviceEnabled.isEmpty { 366 | lastActiveKeyboard = nil 367 | } 368 | 369 | log.trace("Reloaded mappings due to UserDefaults change") 370 | } 371 | } 372 | 373 | // MARK: - Utilities 374 | 375 | extension IOKeyEventMonitor { 376 | private func is2Id(_ inputSource: TISInputSource) -> String? { 377 | return unmanagedStringToString(TISGetInputSourceProperty(inputSource, kTISPropertyInputSourceID))! 378 | } 379 | 380 | func unmanagedStringToString(_ p: UnsafeMutableRawPointer?) -> String? { 381 | if let cfValue = p { 382 | let value = Unmanaged.fromOpaque(cfValue).takeUnretainedValue() as CFString 383 | if CFGetTypeID(value) == CFStringGetTypeID() { 384 | return value as String 385 | } else { 386 | return nil 387 | } 388 | } else { 389 | return nil 390 | } 391 | } 392 | } 393 | --------------------------------------------------------------------------------