keyboard.py 12 KB

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