|
| 1 | +{ config, lib, pkgs, ... }: |
| 2 | +let |
| 3 | + cfg = config.services.macos-remap-keys; |
| 4 | + keytables = import ./keytables.nix { inherit lib; }; |
| 5 | + |
| 6 | + keyToHIDCode = table: key: keytables.${table}.${key}; |
| 7 | + |
| 8 | + # Note: hidutil requires HIDKeyboardModifierMapping values to be in hexadecimal |
| 9 | + # format rather than decimal JSON. Using hex strings instead of numbers will |
| 10 | + # crash macOS. |
| 11 | + makeMapping = table: from: to: |
| 12 | + '' |
| 13 | + { "HIDKeyboardModifierMappingSrc": ${ |
| 14 | + keyToHIDCode table from |
| 15 | + }, "HIDKeyboardModifierMappingDst": ${keyToHIDCode table to} }''; |
| 16 | + |
| 17 | + makeMappingsList = table: mappings: |
| 18 | + lib.mapAttrsToList (from: to: makeMapping table from to) mappings; |
| 19 | + |
| 20 | + allMappings = (makeMappingsList "keyboard" (cfg.keyboard or { })) |
| 21 | + ++ (makeMappingsList "keypad" (cfg.keypad or { })); |
| 22 | + |
| 23 | + allMappingsString = lib.concatStringsSep ", " allMappings; |
| 24 | + propertyString = ''{ "UserKeyMapping": [ ${allMappingsString} ] }''; |
| 25 | +in { |
| 26 | + meta.maintainers = [ lib.maintainers.WeetHet ]; |
| 27 | + |
| 28 | + options.services.macos-remap-keys = { |
| 29 | + enable = lib.mkEnableOption "macOS key remapping service"; |
| 30 | + |
| 31 | + keyboard = lib.mkOption { |
| 32 | + type = lib.types.attrsOf lib.types.str; |
| 33 | + default = { }; |
| 34 | + example = { |
| 35 | + Capslock = "Escape"; |
| 36 | + SquareBracketOpen = "SquareBracketClose"; |
| 37 | + }; |
| 38 | + description = "Mapping of keyboard keys to remap"; |
| 39 | + }; |
| 40 | + |
| 41 | + keypad = lib.mkOption { |
| 42 | + type = lib.types.attrsOf lib.types.str; |
| 43 | + default = { }; |
| 44 | + example = { |
| 45 | + Enter = "Equal"; |
| 46 | + Plus = "Minus"; |
| 47 | + }; |
| 48 | + description = "Mapping of keypad keys to remap"; |
| 49 | + }; |
| 50 | + }; |
| 51 | + |
| 52 | + config = lib.mkIf cfg.enable { |
| 53 | + assertions = [{ |
| 54 | + assertion = (cfg.enable -> pkgs.stdenv.hostPlatform.isDarwin); |
| 55 | + message = "Key remapping only supports macOS"; |
| 56 | + }]; |
| 57 | + home.activation.macosRemapKeys = |
| 58 | + lib.hm.dag.entryAfter [ "writeBoundary" ] '' |
| 59 | + $DRY_RUN_CMD /usr/bin/hidutil property --set '${propertyString}' &> /dev/null |
| 60 | + ''; |
| 61 | + launchd.agents.remap-keys = { |
| 62 | + enable = true; |
| 63 | + config = { |
| 64 | + ProgramArguments = |
| 65 | + [ "/usr/bin/hidutil" "property" "--set" propertyString ]; |
| 66 | + KeepAlive.SuccessfulExit = false; |
| 67 | + RunAtLoad = true; |
| 68 | + }; |
| 69 | + }; |
| 70 | + }; |
| 71 | +} |
0 commit comments