keymap.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. """Functions that help you work with QMK keymaps.
  2. """
  3. import os
  4. import qmk.path
  5. # The `keymap.c` template to use when a keyboard doesn't have its own
  6. DEFAULT_KEYMAP_C = """#include QMK_KEYBOARD_H
  7. /* THIS FILE WAS GENERATED!
  8. *
  9. * This file was generated by qmk-compile-json. You may or may not want to
  10. * edit it directly.
  11. */
  12. const uint16_t PROGMEM keymaps[][MATRIX_ROWS][MATRIX_COLS] = {
  13. __KEYMAP_GOES_HERE__
  14. };
  15. """
  16. def template(keyboard):
  17. """Returns the `keymap.c` template for a keyboard.
  18. If a template exists in `keyboards/<keyboard>/templates/keymap.c` that
  19. text will be used instead of `DEFAULT_KEYMAP_C`.
  20. Args:
  21. keyboard
  22. The keyboard to return a template for.
  23. """
  24. template_name = 'keyboards/%s/templates/keymap.c' % keyboard
  25. if os.path.exists(template_name):
  26. with open(template_name, 'r') as fd:
  27. return fd.read()
  28. return DEFAULT_KEYMAP_C
  29. def generate(keyboard, layout, layers):
  30. """Returns a keymap.c for the specified keyboard, layout, and layers.
  31. Args:
  32. keyboard
  33. The name of the keyboard
  34. layout
  35. The LAYOUT macro this keymap uses.
  36. layers
  37. An array of arrays describing the keymap. Each item in the inner array should be a string that is a valid QMK keycode.
  38. """
  39. layer_txt = []
  40. for layer_num, layer in enumerate(layers):
  41. if layer_num != 0:
  42. layer_txt[-1] = layer_txt[-1] + ','
  43. layer_keys = ', '.join(layer)
  44. layer_txt.append('\t[%s] = %s(%s)' % (layer_num, layout, layer_keys))
  45. keymap = '\n'.join(layer_txt)
  46. keymap_c = template(keyboard)
  47. return keymap_c.replace('__KEYMAP_GOES_HERE__', keymap)
  48. def write(keyboard, keymap, layout, layers):
  49. """Generate the `keymap.c` and write it to disk.
  50. Returns the filename written to.
  51. Args:
  52. keyboard
  53. The name of the keyboard
  54. keymap
  55. The name of the keymap
  56. layout
  57. The LAYOUT macro this keymap uses.
  58. layers
  59. An array of arrays describing the keymap. Each item in the inner array should be a string that is a valid QMK keycode.
  60. """
  61. keymap_c = generate(keyboard, layout, layers)
  62. keymap_path = qmk.path.keymap(keyboard)
  63. keymap_dir = os.path.join(keymap_path, keymap)
  64. keymap_file = os.path.join(keymap_dir, 'keymap.c')
  65. if not os.path.exists(keymap_dir):
  66. os.makedirs(keymap_dir)
  67. with open(keymap_file, 'w') as keymap_fd:
  68. keymap_fd.write(keymap_c)
  69. return keymap_file