keyboard.py 10 KB

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