keyboard.py 6.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. """Functions that help us work with keyboards.
  2. """
  3. import os
  4. from array import array
  5. from functools import lru_cache
  6. from glob import glob
  7. from math import ceil
  8. from pathlib import Path
  9. import qmk.path
  10. from qmk.c_parse import parse_config_h_file
  11. from qmk.json_schema import json_load
  12. from qmk.makefile import parse_rules_mk_file
  13. BOX_DRAWING_CHARACTERS = {
  14. "unicode": {
  15. "tl": "┌",
  16. "tr": "┐",
  17. "bl": "└",
  18. "br": "┘",
  19. "v": "│",
  20. "h": "─",
  21. },
  22. "ascii": {
  23. "tl": " ",
  24. "tr": " ",
  25. "bl": "|",
  26. "br": "|",
  27. "v": "|",
  28. "h": "_",
  29. },
  30. }
  31. base_path = os.path.join(os.getcwd(), "keyboards") + os.path.sep
  32. def find_keyboard_from_dir():
  33. """Returns a keyboard name based on the user's current directory.
  34. """
  35. relative_cwd = qmk.path.under_qmk_firmware()
  36. if relative_cwd and len(relative_cwd.parts) > 1 and relative_cwd.parts[0] == 'keyboards':
  37. # Attempt to extract the keyboard name from the current directory
  38. current_path = Path('/'.join(relative_cwd.parts[1:]))
  39. if 'keymaps' in current_path.parts:
  40. # Strip current_path of anything after `keymaps`
  41. keymap_index = len(current_path.parts) - current_path.parts.index('keymaps') - 1
  42. current_path = current_path.parents[keymap_index]
  43. if qmk.path.is_keyboard(current_path):
  44. return str(current_path)
  45. def find_readme(keyboard):
  46. """Returns the readme for this keyboard.
  47. """
  48. cur_dir = qmk.path.keyboard(keyboard)
  49. keyboards_dir = Path('keyboards')
  50. while not (cur_dir / 'readme.md').exists():
  51. if cur_dir == keyboards_dir:
  52. return None
  53. cur_dir = cur_dir.parent
  54. return cur_dir / 'readme.md'
  55. def is_keyboard_target(keyboard_target):
  56. """Checks to make sure the supplied keyboard_target is valid.
  57. This is mainly used by commands that accept --keyboard.
  58. """
  59. if keyboard_target in ['all', 'all-avr', 'all-chibios', 'all-arm_atsam']:
  60. return keyboard_target
  61. return keyboard_folder(keyboard_target)
  62. def keyboard_folder(keyboard):
  63. """Returns the actual keyboard folder.
  64. This checks aliases and DEFAULT_FOLDER to resolve the actual path for a keyboard.
  65. """
  66. aliases = json_load(Path('data/mappings/keyboard_aliases.json'))
  67. if keyboard in aliases:
  68. keyboard = aliases[keyboard].get('target', keyboard)
  69. rules_mk_file = Path(base_path, keyboard, 'rules.mk')
  70. if rules_mk_file.exists():
  71. rules_mk = parse_rules_mk_file(rules_mk_file)
  72. keyboard = rules_mk.get('DEFAULT_FOLDER', keyboard)
  73. if not qmk.path.is_keyboard(keyboard):
  74. raise ValueError(f'Invalid keyboard: {keyboard}')
  75. return keyboard
  76. def _find_name(path):
  77. """Determine the keyboard name by stripping off the base_path and rules.mk.
  78. """
  79. return path.replace(base_path, "").replace(os.path.sep + "rules.mk", "")
  80. def keyboard_completer(prefix, action, parser, parsed_args):
  81. """Returns a list of keyboards for tab completion.
  82. """
  83. return list_keyboards()
  84. def list_keyboards():
  85. """Returns a list of all keyboards.
  86. """
  87. # We avoid pathlib here because this is performance critical code.
  88. kb_wildcard = os.path.join(base_path, "**", "rules.mk")
  89. paths = [path for path in glob(kb_wildcard, recursive=True) if 'keymaps' not in path]
  90. return sorted(set(map(resolve_keyboard, map(_find_name, paths))))
  91. def resolve_keyboard(keyboard):
  92. cur_dir = Path('keyboards')
  93. rules = parse_rules_mk_file(cur_dir / keyboard / 'rules.mk')
  94. while 'DEFAULT_FOLDER' in rules and keyboard != rules['DEFAULT_FOLDER']:
  95. keyboard = rules['DEFAULT_FOLDER']
  96. rules = parse_rules_mk_file(cur_dir / keyboard / 'rules.mk')
  97. return keyboard
  98. def config_h(keyboard):
  99. """Parses all the config.h files for a keyboard.
  100. Args:
  101. keyboard: name of the keyboard
  102. Returns:
  103. a dictionary representing the content of the entire config.h tree for a keyboard
  104. """
  105. config = {}
  106. cur_dir = Path('keyboards')
  107. keyboard = Path(resolve_keyboard(keyboard))
  108. for dir in keyboard.parts:
  109. cur_dir = cur_dir / dir
  110. config = {**config, **parse_config_h_file(cur_dir / 'config.h')}
  111. return config
  112. def rules_mk(keyboard):
  113. """Get a rules.mk for a keyboard
  114. Args:
  115. keyboard: name of the keyboard
  116. Returns:
  117. a dictionary representing the content of the entire rules.mk tree for a keyboard
  118. """
  119. cur_dir = Path('keyboards')
  120. keyboard = Path(resolve_keyboard(keyboard))
  121. rules = parse_rules_mk_file(cur_dir / keyboard / 'rules.mk')
  122. for i, dir in enumerate(keyboard.parts):
  123. cur_dir = cur_dir / dir
  124. rules = parse_rules_mk_file(cur_dir / 'rules.mk', rules)
  125. return rules
  126. def render_layout(layout_data, render_ascii, key_labels=None):
  127. """Renders a single layout.
  128. """
  129. textpad = [array('u', ' ' * 200) for x in range(100)]
  130. style = 'ascii' if render_ascii else 'unicode'
  131. box_chars = BOX_DRAWING_CHARACTERS[style]
  132. for key in layout_data:
  133. x = ceil(key.get('x', 0) * 4)
  134. y = ceil(key.get('y', 0) * 3)
  135. w = ceil(key.get('w', 1) * 4)
  136. h = ceil(key.get('h', 1) * 3)
  137. if key_labels:
  138. label = key_labels.pop(0)
  139. if label.startswith('KC_'):
  140. label = label[3:]
  141. else:
  142. label = key.get('label', '')
  143. label_len = w - 2
  144. label_leftover = label_len - len(label)
  145. if len(label) > label_len:
  146. label = label[:label_len]
  147. label_blank = ' ' * label_len
  148. label_border = box_chars['h'] * label_len
  149. label_middle = label + ' '*label_leftover # noqa: yapf insists there be no whitespace around *
  150. top_line = array('u', box_chars['tl'] + label_border + box_chars['tr'])
  151. lab_line = array('u', box_chars['v'] + label_middle + box_chars['v'])
  152. mid_line = array('u', box_chars['v'] + label_blank + box_chars['v'])
  153. bot_line = array('u', box_chars['bl'] + label_border + box_chars['br'])
  154. textpad[y][x:x + w] = top_line
  155. textpad[y + 1][x:x + w] = lab_line
  156. for i in range(h - 3):
  157. textpad[y + i + 2][x:x + w] = mid_line
  158. textpad[y + h - 1][x:x + w] = bot_line
  159. lines = []
  160. for line in textpad:
  161. if line.tounicode().strip():
  162. lines.append(line.tounicode().rstrip())
  163. return '\n'.join(lines)
  164. @lru_cache(maxsize=0)
  165. def render_layouts(info_json, render_ascii):
  166. """Renders all the layouts from an `info_json` structure.
  167. """
  168. layouts = {}
  169. for layout in info_json['layouts']:
  170. layout_data = info_json['layouts'][layout]['layout']
  171. layouts[layout] = render_layout(layout_data, render_ascii)
  172. return layouts