keyboard.py 11 KB

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