keyboard.py 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334
  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. import shutil
  8. from glob import glob
  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. KEY_WIDTH = 4 if shutil.get_terminal_size().columns < 160 else 6
  14. BOX_DRAWING_CHARACTERS = {
  15. "unicode": {
  16. "tl": "┌",
  17. "tr": "┐",
  18. "bl": "└",
  19. "br": "┘",
  20. "v": "│",
  21. "h": "─",
  22. },
  23. "ascii": {
  24. "tl": " ",
  25. "tr": " ",
  26. "bl": "|",
  27. "br": "|",
  28. "v": "|",
  29. "h": "_",
  30. },
  31. }
  32. class AllKeyboards:
  33. """Represents all keyboards.
  34. """
  35. def __str__(self):
  36. return 'all'
  37. def __repr__(self):
  38. return 'all'
  39. def __eq__(self, other):
  40. return isinstance(other, AllKeyboards)
  41. base_path = os.path.join(os.getcwd(), "keyboards") + os.path.sep
  42. def is_all_keyboards(keyboard):
  43. """Returns True if the keyboard is an AllKeyboards object.
  44. """
  45. return isinstance(keyboard, AllKeyboards)
  46. def find_keyboard_from_dir():
  47. """Returns a keyboard name based on the user's current directory.
  48. """
  49. relative_cwd = qmk.path.under_qmk_firmware()
  50. if relative_cwd and len(relative_cwd.parts) > 1 and relative_cwd.parts[0] == 'keyboards':
  51. # Attempt to extract the keyboard name from the current directory
  52. current_path = Path('/'.join(relative_cwd.parts[1:]))
  53. if 'keymaps' in current_path.parts:
  54. # Strip current_path of anything after `keymaps`
  55. keymap_index = len(current_path.parts) - current_path.parts.index('keymaps') - 1
  56. current_path = current_path.parents[keymap_index]
  57. if qmk.path.is_keyboard(current_path):
  58. return str(current_path)
  59. def find_readme(keyboard):
  60. """Returns the readme for this keyboard.
  61. """
  62. cur_dir = qmk.path.keyboard(keyboard)
  63. keyboards_dir = Path('keyboards')
  64. while not (cur_dir / 'readme.md').exists():
  65. if cur_dir == keyboards_dir:
  66. return None
  67. cur_dir = cur_dir.parent
  68. return cur_dir / 'readme.md'
  69. def keyboard_folder(keyboard):
  70. """Returns the actual keyboard folder.
  71. This checks aliases and DEFAULT_FOLDER to resolve the actual path for a keyboard.
  72. """
  73. aliases = json_load(Path('data/mappings/keyboard_aliases.hjson'))
  74. if keyboard in aliases:
  75. keyboard = aliases[keyboard].get('target', keyboard)
  76. rules_mk_file = Path(base_path, keyboard, 'rules.mk')
  77. if rules_mk_file.exists():
  78. rules_mk = parse_rules_mk_file(rules_mk_file)
  79. keyboard = rules_mk.get('DEFAULT_FOLDER', keyboard)
  80. if not qmk.path.is_keyboard(keyboard):
  81. raise ValueError(f'Invalid keyboard: {keyboard}')
  82. return keyboard
  83. def keyboard_folder_or_all(keyboard):
  84. """Returns the actual keyboard folder.
  85. This checks aliases and DEFAULT_FOLDER to resolve the actual path for a keyboard.
  86. If the supplied argument is "all", it returns an AllKeyboards object.
  87. """
  88. if keyboard == 'all':
  89. return AllKeyboards()
  90. return keyboard_folder(keyboard)
  91. def _find_name(path):
  92. """Determine the keyboard name by stripping off the base_path and rules.mk.
  93. """
  94. return path.replace(base_path, "").replace(os.path.sep + "rules.mk", "")
  95. def keyboard_completer(prefix, action, parser, parsed_args):
  96. """Returns a list of keyboards for tab completion.
  97. """
  98. return list_keyboards()
  99. def list_keyboards(resolve_defaults=True):
  100. """Returns a list of all keyboards - optionally processing any DEFAULT_FOLDER.
  101. """
  102. # We avoid pathlib here because this is performance critical code.
  103. kb_wildcard = os.path.join(base_path, "**", "rules.mk")
  104. paths = [path for path in glob(kb_wildcard, recursive=True) if os.path.sep + 'keymaps' + os.path.sep not in path]
  105. found = map(_find_name, paths)
  106. if resolve_defaults:
  107. found = map(resolve_keyboard, found)
  108. return sorted(set(found))
  109. def resolve_keyboard(keyboard):
  110. cur_dir = Path('keyboards')
  111. rules = parse_rules_mk_file(cur_dir / keyboard / 'rules.mk')
  112. while 'DEFAULT_FOLDER' in rules and keyboard != rules['DEFAULT_FOLDER']:
  113. keyboard = rules['DEFAULT_FOLDER']
  114. rules = parse_rules_mk_file(cur_dir / keyboard / 'rules.mk')
  115. return keyboard
  116. def config_h(keyboard):
  117. """Parses all the config.h files for a keyboard.
  118. Args:
  119. keyboard: name of the keyboard
  120. Returns:
  121. a dictionary representing the content of the entire config.h tree for a keyboard
  122. """
  123. config = {}
  124. cur_dir = Path('keyboards')
  125. keyboard = Path(resolve_keyboard(keyboard))
  126. for dir in keyboard.parts:
  127. cur_dir = cur_dir / dir
  128. config = {**config, **parse_config_h_file(cur_dir / 'config.h')}
  129. return config
  130. def rules_mk(keyboard):
  131. """Get a rules.mk for a keyboard
  132. Args:
  133. keyboard: name of the keyboard
  134. Returns:
  135. a dictionary representing the content of the entire rules.mk tree for a keyboard
  136. """
  137. cur_dir = Path('keyboards')
  138. keyboard = Path(resolve_keyboard(keyboard))
  139. rules = parse_rules_mk_file(cur_dir / keyboard / 'rules.mk')
  140. for i, dir in enumerate(keyboard.parts):
  141. cur_dir = cur_dir / dir
  142. rules = parse_rules_mk_file(cur_dir / 'rules.mk', rules)
  143. return rules
  144. def render_layout(layout_data, render_ascii, key_labels=None):
  145. """Renders a single layout.
  146. """
  147. textpad = [array('u', ' ' * 200) for x in range(100)]
  148. style = 'ascii' if render_ascii else 'unicode'
  149. for key in layout_data:
  150. x = key.get('x', 0)
  151. y = key.get('y', 0)
  152. w = key.get('w', 1)
  153. h = key.get('h', 1)
  154. if key_labels:
  155. label = key_labels.pop(0)
  156. if label.startswith('KC_'):
  157. label = label[3:]
  158. else:
  159. label = key.get('label', '')
  160. if x >= 0.25 and w == 1.25 and h == 2:
  161. render_key_isoenter(textpad, x, y, w, h, label, style)
  162. elif w == 1.5 and h == 2:
  163. render_key_baenter(textpad, x, y, w, h, label, style)
  164. else:
  165. render_key_rect(textpad, x, y, w, h, label, style)
  166. lines = []
  167. for line in textpad:
  168. if line.tounicode().strip():
  169. lines.append(line.tounicode().rstrip())
  170. return '\n'.join(lines)
  171. def render_layouts(info_json, render_ascii):
  172. """Renders all the layouts from an `info_json` structure.
  173. """
  174. layouts = {}
  175. for layout in info_json['layouts']:
  176. layout_data = info_json['layouts'][layout]['layout']
  177. layouts[layout] = render_layout(layout_data, render_ascii)
  178. return layouts
  179. def render_key_rect(textpad, x, y, w, h, label, style):
  180. box_chars = BOX_DRAWING_CHARACTERS[style]
  181. x = ceil(x * KEY_WIDTH)
  182. y = ceil(y * 3)
  183. w = ceil(w * KEY_WIDTH)
  184. h = ceil(h * 3)
  185. label_len = w - 2
  186. label_leftover = label_len - len(label)
  187. if len(label) > label_len:
  188. label = label[:label_len]
  189. label_blank = ' ' * label_len
  190. label_border = box_chars['h'] * label_len
  191. label_middle = label + ' ' * label_leftover
  192. top_line = array('u', box_chars['tl'] + label_border + box_chars['tr'])
  193. lab_line = array('u', box_chars['v'] + label_middle + box_chars['v'])
  194. mid_line = array('u', box_chars['v'] + label_blank + box_chars['v'])
  195. bot_line = array('u', box_chars['bl'] + label_border + box_chars['br'])
  196. textpad[y][x:x + w] = top_line
  197. textpad[y + 1][x:x + w] = lab_line
  198. for i in range(h - 3):
  199. textpad[y + i + 2][x:x + w] = mid_line
  200. textpad[y + h - 1][x:x + w] = bot_line
  201. def render_key_isoenter(textpad, x, y, w, h, label, style):
  202. box_chars = BOX_DRAWING_CHARACTERS[style]
  203. x = ceil(x * KEY_WIDTH)
  204. y = ceil(y * 3)
  205. w = ceil(w * KEY_WIDTH)
  206. h = ceil(h * 3)
  207. label_len = w - 1
  208. label_leftover = label_len - len(label)
  209. if len(label) > label_len:
  210. label = label[:label_len]
  211. label_blank = ' ' * (label_len - 1)
  212. label_border_top = box_chars['h'] * label_len
  213. label_border_bottom = box_chars['h'] * (label_len - 1)
  214. label_middle = label + ' ' * label_leftover
  215. top_line = array('u', box_chars['tl'] + label_border_top + box_chars['tr'])
  216. lab_line = array('u', box_chars['v'] + label_middle + box_chars['v'])
  217. crn_line = array('u', box_chars['bl'] + box_chars['tr'] + label_blank + box_chars['v'])
  218. mid_line = array('u', box_chars['v'] + label_blank + box_chars['v'])
  219. bot_line = array('u', box_chars['bl'] + label_border_bottom + box_chars['br'])
  220. textpad[y][x - 1:x + w] = top_line
  221. textpad[y + 1][x - 1:x + w] = lab_line
  222. textpad[y + 2][x - 1:x + w] = crn_line
  223. textpad[y + 3][x:x + w] = mid_line
  224. textpad[y + 4][x:x + w] = mid_line
  225. textpad[y + 5][x:x + w] = bot_line
  226. def render_key_baenter(textpad, x, y, w, h, label, style):
  227. box_chars = BOX_DRAWING_CHARACTERS[style]
  228. x = ceil(x * KEY_WIDTH)
  229. y = ceil(y * 3)
  230. w = ceil(w * KEY_WIDTH)
  231. h = ceil(h * 3)
  232. label_len = w + 1
  233. label_leftover = label_len - len(label)
  234. if len(label) > label_len:
  235. label = label[:label_len]
  236. label_blank = ' ' * (label_len - 3)
  237. label_border_top = box_chars['h'] * (label_len - 3)
  238. label_border_bottom = box_chars['h'] * label_len
  239. label_middle = label + ' ' * label_leftover
  240. top_line = array('u', box_chars['tl'] + label_border_top + box_chars['tr'])
  241. mid_line = array('u', box_chars['v'] + label_blank + box_chars['v'])
  242. crn_line = array('u', box_chars['tl'] + box_chars['h'] + box_chars['h'] + box_chars['br'] + label_blank + box_chars['v'])
  243. lab_line = array('u', box_chars['v'] + label_middle + box_chars['v'])
  244. bot_line = array('u', box_chars['bl'] + label_border_bottom + box_chars['br'])
  245. textpad[y][x:x + w] = top_line
  246. textpad[y + 1][x:x + w] = mid_line
  247. textpad[y + 2][x:x + w] = mid_line
  248. textpad[y + 3][x - 3:x + w] = crn_line
  249. textpad[y + 4][x - 3:x + w] = lab_line
  250. textpad[y + 5][x - 3:x + w] = bot_line