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