keyboard.py 9.8 KB

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