keymap.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186
  1. """Functions that help you work with QMK keymaps.
  2. """
  3. from pathlib import Path
  4. from qmk.path import is_keyboard
  5. from qmk.keyboard import rules_mk
  6. # The `keymap.c` template to use when a keyboard doesn't have its own
  7. DEFAULT_KEYMAP_C = """#include QMK_KEYBOARD_H
  8. /* THIS FILE WAS GENERATED!
  9. *
  10. * This file was generated by qmk json2c. You may or may not want to
  11. * edit it directly.
  12. */
  13. const uint16_t PROGMEM keymaps[][MATRIX_ROWS][MATRIX_COLS] = {
  14. __KEYMAP_GOES_HERE__
  15. };
  16. """
  17. def template(keyboard):
  18. """Returns the `keymap.c` template for a keyboard.
  19. If a template exists in `keyboards/<keyboard>/templates/keymap.c` that
  20. text will be used instead of `DEFAULT_KEYMAP_C`.
  21. Args:
  22. keyboard
  23. The keyboard to return a template for.
  24. """
  25. template_file = Path('keyboards/%s/templates/keymap.c' % keyboard)
  26. if template_file.exists():
  27. return template_file.read_text()
  28. return DEFAULT_KEYMAP_C
  29. def _strip_any(keycode):
  30. """Remove ANY() from a keycode.
  31. """
  32. if keycode.startswith('ANY(') and keycode.endswith(')'):
  33. keycode = keycode[4:-1]
  34. return keycode
  35. def is_keymap_dir(keymap):
  36. """Return True if Path object `keymap` has a keymap file inside.
  37. """
  38. for file in ('keymap.c', 'keymap.json'):
  39. if (keymap / file).is_file():
  40. return True
  41. def generate(keyboard, layout, layers):
  42. """Returns a keymap.c for the specified keyboard, layout, and layers.
  43. Args:
  44. keyboard
  45. The name of the keyboard
  46. layout
  47. The LAYOUT macro this keymap uses.
  48. layers
  49. An array of arrays describing the keymap. Each item in the inner array should be a string that is a valid QMK keycode.
  50. """
  51. layer_txt = []
  52. for layer_num, layer in enumerate(layers):
  53. if layer_num != 0:
  54. layer_txt[-1] = layer_txt[-1] + ','
  55. layer = map(_strip_any, layer)
  56. layer_keys = ', '.join(layer)
  57. layer_txt.append('\t[%s] = %s(%s)' % (layer_num, layout, layer_keys))
  58. keymap = '\n'.join(layer_txt)
  59. keymap_c = template(keyboard)
  60. return keymap_c.replace('__KEYMAP_GOES_HERE__', keymap)
  61. def write(keyboard, keymap, layout, layers):
  62. """Generate the `keymap.c` and write it to disk.
  63. Returns the filename written to.
  64. Args:
  65. keyboard
  66. The name of the keyboard
  67. keymap
  68. The name of the keymap
  69. layout
  70. The LAYOUT macro this keymap uses.
  71. layers
  72. An array of arrays describing the keymap. Each item in the inner array should be a string that is a valid QMK keycode.
  73. """
  74. keymap_c = generate(keyboard, layout, layers)
  75. keymap_file = keymap(keyboard) / keymap / 'keymap.c'
  76. keymap_file.parent.mkdir(parents=True, exist_ok=True)
  77. keymap_file.write_text(keymap_c)
  78. return keymap_file
  79. def locate_keymap(keyboard, keymap):
  80. """Returns the path to a keymap for a specific keyboard.
  81. """
  82. if not is_keyboard(keyboard):
  83. raise KeyError('Invalid keyboard: ' + repr(keyboard))
  84. # Check the keyboard folder first, last match wins
  85. checked_dirs = ''
  86. keymap_path = ''
  87. for dir in keyboard.split('/'):
  88. if checked_dirs:
  89. checked_dirs = '/'.join((checked_dirs, dir))
  90. else:
  91. checked_dirs = dir
  92. keymap_dir = Path('keyboards') / checked_dirs / 'keymaps'
  93. if (keymap_dir / keymap / 'keymap.c').exists():
  94. keymap_path = keymap_dir / keymap / 'keymap.c'
  95. if (keymap_dir / keymap / 'keymap.json').exists():
  96. keymap_path = keymap_dir / keymap / 'keymap.json'
  97. if keymap_path:
  98. return keymap_path
  99. # Check community layouts as a fallback
  100. rules = rules_mk(keyboard)
  101. if "LAYOUTS" in rules:
  102. for layout in rules["LAYOUTS"].split():
  103. community_layout = Path('layouts/community') / layout / keymap
  104. if community_layout.exists():
  105. if (community_layout / 'keymap.json').exists():
  106. return community_layout / 'keymap.json'
  107. if (community_layout / 'keymap.c').exists():
  108. return community_layout / 'keymap.c'
  109. def list_keymaps(keyboard):
  110. """ List the available keymaps for a keyboard.
  111. Args:
  112. keyboard: the keyboards full name with vendor and revision if necessary, example: clueboard/66/rev3
  113. Returns:
  114. a set with the names of the available keymaps
  115. """
  116. # parse all the rules.mk files for the keyboard
  117. rules = rules_mk(keyboard)
  118. names = set()
  119. if rules:
  120. # qmk_firmware/keyboards
  121. keyboards_dir = Path('keyboards')
  122. # path to the keyboard's directory
  123. kb_path = keyboards_dir / keyboard
  124. # walk up the directory tree until keyboards_dir
  125. # and collect all directories' name with keymap.c file in it
  126. while kb_path != keyboards_dir:
  127. keymaps_dir = kb_path / "keymaps"
  128. if keymaps_dir.exists():
  129. names = names.union([keymap.name for keymap in keymaps_dir.iterdir() if is_keymap_dir(keymap)])
  130. kb_path = kb_path.parent
  131. # if community layouts are supported, get them
  132. if "LAYOUTS" in rules:
  133. for layout in rules["LAYOUTS"].split():
  134. cl_path = Path('layouts/community') / layout
  135. if cl_path.exists():
  136. names = names.union([keymap.name for keymap in cl_path.iterdir() if is_keymap_dir(keymap)])
  137. return sorted(names)