keyboard.py 7.7 KB

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